List of usage examples for org.apache.commons.fileupload FileItem get
byte[] get();
From source file:fr.paris.lutece.plugins.suggest.web.SuggestSubmitTypeJspBean.java
/** * Get the request data and if there is no error insert the data in the * suggestSubmitType object specified in parameter. * return null if there is no error or else return the error page url * @param multipartRequest the request//from w w w.j a v a2s. com * @param suggestSubmitType the suggestSubmitType Object * @return null if there is no error or else return the error page url */ private String getSuggestSubmitTypeData(MultipartHttpServletRequest multipartRequest, SuggestSubmitType suggestSubmitType) { String strName = multipartRequest.getParameter(PARAMETER_NAME); String strColor = multipartRequest.getParameter(PARAMETER_COLOR); String strParameterizable = multipartRequest.getParameter(PARAMETER_PARAMETERIZABLE); Boolean bParameterizable = true; String strFieldError = EMPTY_STRING; FileItem imageSource = multipartRequest.getFile(PARAMETER_IMAGE_SOURCE); String strImageName = FileUploadService.getFileNameOnly(imageSource); String strUpdateFile = multipartRequest.getParameter(PARAMETER_UPDATE_FILE); if ((strName == null) || strName.trim().equals(EMPTY_STRING)) { strFieldError = FIELD_NAME; } else if ((strParameterizable == null) || strParameterizable.trim().equals(EMPTY_STRING)) { bParameterizable = false; } //Mandatory fields if (!strFieldError.equals(EMPTY_STRING)) { Object[] tabRequiredFields = { I18nService.getLocalizedString(strFieldError, getLocale()) }; return AdminMessageService.getMessageUrl(multipartRequest, MESSAGE_MANDATORY_FIELD, tabRequiredFields, AdminMessage.TYPE_STOP); } if ((suggestSubmitType.getIdType() == SuggestUtils.CONSTANT_ID_NULL) || (strUpdateFile != null)) { ImageResource image = new ImageResource(); byte[] baImageSource = imageSource.get(); if ((strImageName != null) && !strImageName.equals("")) { image.setImage(baImageSource); image.setMimeType(imageSource.getContentType()); } suggestSubmitType.setPictogram(image); } suggestSubmitType.setColor(strColor); suggestSubmitType.setName(strName); suggestSubmitType.setParameterizableInFO(bParameterizable); return null; }
From source file:net.ion.radon.impl.let.webdav.FCKConnectorRestlet.java
protected void handlePost(final Request request, final Response response, final String currentFolderStr) { final Form parameters = request.getResourceRef().getQueryAsForm(); final String commandStr = parameters.getValues("Command"); String retVal = "0"; String newName = ""; if (!commandStr.equalsIgnoreCase("FileUpload")) retVal = "203"; else {//w w w . ja v a 2 s . c om final RestletFileUpload upload = new RestletFileUpload(new DiskFileItemFactory()); try { final List<?> items = upload.parseRequest(request); final Map<String, Object> fields = new HashMap<String, Object>(); final Iterator<?> iterator = items.iterator(); while (iterator.hasNext()) { final FileItem item = (FileItem) iterator.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } final FileItem uploadFile = (FileItem) fields.get("NewFile"); String fileNameLong = uploadFile.getName(); fileNameLong = fileNameLong.replace('\\', '/'); final String[] pathParts = fileNameLong.split("/"); final String fileName = pathParts[pathParts.length - 1]; final String nameWithoutExt = getNameWithoutExtension(fileName); final String ext = getExtension(fileName); File pathToSave = new File(currentFolderStr, fileName); int counter = 1; while (pathToSave.exists()) { newName = nameWithoutExt + "(" + (counter++) + ")" + "." + ext; retVal = "201"; pathToSave = new File(currentFolderStr, newName); } try { OutputStream fout = vfs.getOutputStream(VFSUtils.parseVFSPath(pathToSave.getPath())); fout.write(uploadFile.get()); fout.close(); } catch (Exception e) { } // uploadFile.write(pathToSave); } catch (final Exception e) { e.printStackTrace(); retVal = "203"; } } response.setStatus(Status.SUCCESS_OK); Form headers = (Form) response.getAttributes().get("org.restlet.http.headers"); if (headers == null) { headers = new Form(); response.getAttributes().put("org.restlet.http.headers", headers); } headers.add("Content-type", "text/xml; charset=UTF-8"); headers.add("Cache-control", "no-cache"); String script = "<html><head><title></title><script type=\"text/javascript\">"; script += "function doWork() {"; script += "window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');"; // script += "window.parent.OnUploadComplete(" + retVal + ",'" + newName + "', '" + newName + "');"; // script += "window.location.reload(true);"; script += "}</script></head><body onload=\"doWork()\">Upload done!</body></html>"; response.setEntity(new StringRepresentation(script, MediaType.TEXT_HTML)); // System.out.println(script); }
From source file:com.openkm.servlet.admin.DatabaseQueryServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); updateSessionManager(request);/* w w w .j a v a2s. c om*/ String user = request.getRemoteUser(); ServletContext sc = getServletContext(); Session session = null; try { if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); boolean showSql = false; String vtable = ""; String type = ""; String qs = ""; byte[] data = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("qs")) { qs = item.getString("UTF-8"); } else if (item.getFieldName().equals("type")) { type = item.getString("UTF-8"); } else if (item.getFieldName().equals("showSql")) { showSql = true; } else if (item.getFieldName().equals("vtables")) { vtable = item.getString("UTF-8"); } } else { data = item.get(); } } if (!qs.equals("") && !type.equals("")) { session = HibernateUtil.getSessionFactory().openSession(); sc.setAttribute("qs", qs); sc.setAttribute("type", type); if (type.equals("jdbc")) { executeJdbc(session, qs, sc, request, response); // Activity log UserActivity.log(user, "ADMIN_DATABASE_QUERY_JDBC", null, null, qs); } else if (type.equals("hibernate")) { executeHibernate(session, qs, showSql, sc, request, response); // Activity log UserActivity.log(user, "ADMIN_DATABASE_QUERY_HIBERNATE", null, null, qs); } else if (type.equals("metadata")) { sc.setAttribute("vtable", vtable); executeMetadata(session, qs, false, sc, request, response); // Activity log UserActivity.log(user, "ADMIN_DATABASE_QUERY_METADATA", null, null, qs); } } else if (data != null && data.length > 0) { sc.setAttribute("exception", null); session = HibernateUtil.getSessionFactory().openSession(); executeUpdate(session, data, sc, request, response); // Activity log UserActivity.log(user, "ADMIN_DATABASE_QUERY_FILE", null, null, new String(data)); } else { sc.setAttribute("qs", qs); sc.setAttribute("type", type); sc.setAttribute("showSql", showSql); sc.setAttribute("exception", null); sc.setAttribute("globalResults", new ArrayList<DbQueryGlobalResult>()); sc.getRequestDispatcher("/admin/database_query.jsp").forward(request, response); } } else { // Edit table cell value String action = request.getParameter("action"); String vtable = request.getParameter("vtable"); String column = request.getParameter("column"); String value = request.getParameter("value"); String id = request.getParameter("id"); if (action.equals("edit")) { int idx = column.indexOf('('); if (idx > 0) { column = column.substring(idx + 1, idx + 6); } String hql = "update DatabaseMetadataValue dmv set dmv." + column + "='" + value + "' where dmv.table='" + vtable + "' and dmv.id=" + id; log.info("HQL: {}", hql); session = HibernateUtil.getSessionFactory().openSession(); int rows = session.createQuery(hql).executeUpdate(); log.info("Rows affected: {}", rows); } } } catch (FileUploadException e) { sendError(sc, request, response, e); } catch (SQLException e) { sendError(sc, request, response, e); } catch (HibernateException e) { sendError(sc, request, response, e); } catch (DatabaseException e) { sendError(sc, request, response, e); } catch (IllegalAccessException e) { sendError(sc, request, response, e); } catch (InvocationTargetException e) { sendError(sc, request, response, e); } catch (NoSuchMethodException e) { sendError(sc, request, response, e); } finally { HibernateUtil.close(session); } }
From source file:gsn.http.FieldUpload.java
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String msg;/*from w w w.j a v a 2 s . co m*/ Integer code; PrintWriter out = res.getWriter(); ArrayList<String> paramNames = new ArrayList<String>(); ArrayList<String> paramValues = new ArrayList<String>(); //Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { out.write("not multipart!"); code = 666; msg = "Error post data is not multipart!"; logger.error(msg); } else { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(5 * 1024 * 1024); List items; try { // Parse the request items = upload.parseRequest(req); //building xml data out of the input String cmd = ""; String vsname = ""; Base64 b64 = new Base64(); StringBuilder sb = new StringBuilder("<input>\n"); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.getFieldName().equals("vsname")) { //define which cmd block is sent sb.append("<vsname>" + item.getString() + "</vsname>\n"); vsname = item.getString(); } else if (item.getFieldName().equals("cmd")) { //define which cmd block is sent cmd = item.getString(); sb.append("<command>" + item.getString() + "</command>\n"); sb.append("<fields>\n"); } else if (item.getFieldName().split(";")[0].equals(cmd)) { //only for the defined cmd sb.append("<field>\n"); sb.append("<name>" + item.getFieldName().split(";")[1] + "</name>\n"); paramNames.add(item.getFieldName().split(";")[1]); if (item.isFormField()) { sb.append("<value>" + item.getString() + "</value>\n"); paramValues.add(item.getString()); } else { sb.append("<value>" + new String(b64.encode(item.get())) + "</value>\n"); paramValues.add(new String(b64.encode(item.get()))); } sb.append("</field>\n"); } } sb.append("</fields>\n"); sb.append("</input>\n"); //do something with xml aka statement.toString() AbstractVirtualSensor vs = null; try { vs = Mappings.getVSensorInstanceByVSName(vsname).borrowVS(); vs.dataFromWeb(cmd, paramNames.toArray(new String[] {}), paramValues.toArray(new Serializable[] {})); } catch (VirtualSensorInitializationFailedException e) { logger.warn("Sending data back to the source virtual sensor failed !: " + e.getMessage(), e); } finally { Mappings.getVSensorInstanceByVSName(vsname).returnVS(vs); } code = 200; msg = "The upload to the virtual sensor went successfully! (" + vsname + ")"; } catch (ServletFileUpload.SizeLimitExceededException e) { code = 600; msg = "Upload size exceeds maximum limit!"; logger.error(msg, e); } catch (Exception e) { code = 500; msg = "Internal Error: " + e; logger.error(msg, e); } } //callback to the javascript out.write("<script>window.parent.GSN.msgcallback('" + msg + "'," + code + ");</script>"); }
From source file:calliope.handler.put.AesePutHandler.java
private void parseRequest(HttpServletRequest request) throws AeseException { try {//from w ww . java2s .c o m FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request List items = upload.parseRequest(request); for (int i = 0; i < items.size(); i++) { FileItem item = (FileItem) items.get(i); if (item.isFormField()) { String fieldName = item.getFieldName(); if (fieldName != null) { String contents = item.getString(); if (fieldName.equals(Params.STRIPPER)) stripperName = contents; else if (fieldName.equals(Params.ENCODING)) encoding = contents; else if (fieldName.equals(Params.STYLE)) style = contents; else if (fieldName.equals(Params.TITLE)) title = contents; else if (fieldName.equals(Params.VERSION1)) version1 = contents; else if (fieldName.equals(Params.AUTHOR)) author = contents; else if (fieldName.equals(Params.DESCRIPTION)) description = contents; } } else if (item.getName().length() > 0) { byte[] rawData = item.get(); guessEncoding(rawData); if (encoding == null) encoding = guessEncoding(rawData); fileContent = new String(rawData, encoding); } } } catch (Exception e) { throw new AeseException(e); } }
From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java
/** * Sets up the given {@link PostMethod} to send the same multipart POST * data as was sent in the given {@link HttpServletRequest} * * @param postMethodProxyRequest The {@link PostMethod} that we are * configuring to send a multipart POST request * @param httpServletRequest The {@link HttpServletRequest} that contains * the mutlipart POST data to be sent via the {@link PostMethod} * @throws javax.servlet.ServletException If something fails when uploading the content to the server *///ww w. ja va 2 s .c o m @SuppressWarnings({ "unchecked", "ToArrayCallWithZeroLengthArrayArgument" }) private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:fr.paris.lutece.plugins.form.web.ExportFormatJspBean.java
/** * Get the request data and if there is no error insert the data in the exportFormat object specified in parameter. * return null if there is no error or else return the error page url * @param multipartRequest the request//www . j a v a2 s . com * @param exportFormat the exportFormat Object * @return null if there is no error or else return the error page url */ private String getExportFormatData(MultipartHttpServletRequest multipartRequest, ExportFormat exportFormat) { String strTitle = multipartRequest.getParameter(PARAMETER_TITLE); String strDescription = multipartRequest.getParameter(PARAMETER_DESCRIPTION); String strExtension = multipartRequest.getParameter(PARAMETER_EXTENSION); String strFieldError = EMPTY_STRING; FileItem fileSource = multipartRequest.getFile(Parameters.STYLESHEET_SOURCE); String strFilename = FileUploadService.getFileNameOnly(fileSource); if ((strTitle == null) || strTitle.trim().equals(EMPTY_STRING)) { strFieldError = FIELD_TITLE; } else if ((strDescription == null) || strDescription.trim().equals(EMPTY_STRING)) { strFieldError = FIELD_DESCRIPTION; } else if ((strExtension == null) || strExtension.trim().equals(EMPTY_STRING)) { strFieldError = FIELD_EXTENSION; } else if ((strFilename == null) || (strFilename.equals("") && (exportFormat.getXsl() == null))) { strFieldError = FIELD_XSL; } //Mandatory fields if (!strFieldError.equals(EMPTY_STRING)) { Object[] tabRequiredFields = { I18nService.getLocalizedString(strFieldError, getLocale()) }; return AdminMessageService.getMessageUrl(multipartRequest, MESSAGE_MANDATORY_FIELD, tabRequiredFields, AdminMessage.TYPE_STOP); } byte[] baXslSource = fileSource.get(); //Check the XML validity of the XSL stylesheet if ((strFilename != null) && !strFilename.equals("") && (isValid(baXslSource) != null)) { Object[] args = { isValid(baXslSource) }; return AdminMessageService.getMessageUrl(multipartRequest, MESSAGE_STYLESHEET_NOT_VALID, args, AdminMessage.TYPE_STOP); } exportFormat.setTitle(strTitle); exportFormat.setDescription(strDescription); exportFormat.setExtension(strExtension); if ((strFilename != null) && !strFilename.equals("")) { exportFormat.setXsl(baXslSource); } return null; }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same multipart POST * data as was sent in the given {@link javax.servlet.http.HttpServletRequest} * * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are * configuring to send a multipart POST request * @param httpServletRequest The {@link javax.servlet.http.HttpServletRequest} that contains * the mutlipart POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod} *///w w w .j a v a 2 s . co m @SuppressWarnings("unchecked") private void handleMultipartPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) throws ServletException { // Create a factory for disk-based file items DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); // Set factory constraints diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(FILE_UPLOAD_TEMP_DIRECTORY); // Create a new file upload handler ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); // Parse the request try { // Get the multipart items as a list List<FileItem> listFileItems = (List<FileItem>) servletFileUpload.parseRequest(httpServletRequest); // Create a list to hold all of the parts List<Part> listParts = new ArrayList<Part>(); // Iterate the multipart items list for (FileItem fileItemCurrent : listFileItems) { // If the current item is a form field, then create a string part if (fileItemCurrent.isFormField()) { StringPart stringPart = new StringPart(fileItemCurrent.getFieldName(), // The field name fileItemCurrent.getString() // The field value ); // Add the part to the list listParts.add(stringPart); } else { // The item is a file upload, so we create a FilePart FilePart filePart = new FilePart(fileItemCurrent.getFieldName(), // The field name new ByteArrayPartSource(fileItemCurrent.getName(), // The uploaded file name fileItemCurrent.get() // The uploaded file contents )); // Add the part to the list listParts.add(filePart); } } MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity( listParts.toArray(new Part[] {}), postMethodProxyRequest.getParams()); postMethodProxyRequest.setRequestEntity(multipartRequestEntity); // The current content-type header (received from the client) IS of // type "multipart/form-data", but the content-type header also // contains the chunk boundary string of the chunks. Currently, this // header is using the boundary of the client request, since we // blindly copied all headers from the client request to the proxy // request. However, we are creating a new request with a new chunk // boundary string, so it is necessary that we re-set the // content-type string to reflect the new chunk boundary string postMethodProxyRequest.setRequestHeader(STRING_CONTENT_TYPE_HEADER_NAME, multipartRequestEntity.getContentType()); } catch (FileUploadException fileUploadException) { throw new ServletException(fileUploadException); } }
From source file:fr.paris.lutece.plugins.pluginwizard.web.PluginWizardApp.java
/** * The load action of the plugin/*from w w w . j a v a 2 s . c o m*/ * * @param request The Http Request * @return The plugin id * @throws org.apache.commons.fileupload.FileUploadException */ @Action(ACTION_LOAD_PLUGIN) public XPage doLoadPlugin(HttpServletRequest request) throws FileUploadException { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile(PARAM_FILE); if (fileItem.getName() == null || fileItem.getName().isEmpty()) { addError(ERROR_LOAD_PLUGIN, getLocale(request)); return redirectView(request, VIEW_CREATE_PLUGIN); } String strJson = new String(fileItem.get(), StandardCharsets.UTF_8); PluginModel pluginModel = MapperService.readJson(strJson); _nPluginId = ModelService.savePluginModelFromJson(pluginModel); _description = ModelService.getDescription(_nPluginId); return redirectView(request, VIEW_MODIFY_DESCRIPTION); }
From source file:com.enonic.vertical.adminweb.UserHandlerServlet.java
private void storeUserPhotoInSession(HttpSession session, ExtendedMap formItems) { FileItem item = formItems.getFileItem(UserFieldType.PHOTO.getName(), null); if (item != null) { UserPhotoHolder userPhoto = new UserPhotoHolder(); userPhoto.setPhoto(item.get()); session.setAttribute(SESSION_PHOTO_ITEM_KEY, userPhoto); }//from ww w . j av a 2 s . c o m }