List of usage examples for org.apache.commons.fileupload FileItem getString
String getString(String encoding) throws UnsupportedEncodingException;
From source file:com.edgenius.wiki.ext.textnut.NutServlet.java
private String saveOrUpdatePage(HttpServletRequest request, HttpServletResponse response) { if (!doBasicAuthentication(request)) return NutCode.AUTHENTICATION_ERROR + ""; String spaceUname = null, title = null, pageUuid = null; InputStream content = null;// w ww .j a va 2 s . c o m int version = 0; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { @SuppressWarnings("unchecked") List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { String name = item.getFieldName(); if (StringUtils.equals(name, "space")) { spaceUname = item.getString(Constants.UTF8); } else if (StringUtils.equals(name, "title")) { title = item.getString(Constants.UTF8); } else if (StringUtils.equals(name, "puuid")) { pageUuid = item.getString(Constants.UTF8); } else if (StringUtils.equals(name, "version")) { version = NumberUtils.toInt(item.getString(Constants.UTF8)); } else if (StringUtils.equals(name, "content")) { content = item.getInputStream(); } } log.warn("Nut service for page {} (UUID:{}) on space {}.", new String[] { title, pageUuid, spaceUname }); if (content != null && spaceUname != null && title != null) { //parse BPlist Map<String, File> files = nutParser.parseBPlist(content); Space space = getSpaceService().getSpaceByUname(spaceUname); if (files != null && space != null) { File htmlFile = files.remove(NutParser.MAIN_RESOURCE_URL); if (htmlFile != null) { String htmlText = nutParser.convertNutHTMLToPageHTML(FileUtils.readFileToString(htmlFile)); //save Page Page page = new Page(); PageContent pageContent = new PageContent(); page.setContent(pageContent); pageContent.setContent(getRenderService().renderHTMLtoMarkup(spaceUname, htmlText)); page.setPageUuid(pageUuid); page.setTitle(title); page.setSpace(space); page.setVersion(version); //upload attachments if (files.size() > 0) { if (pageUuid == null) { //must get pageUUID first for upload attachment, so save page to draft first Draft draft = getPageService().saveDraft(WikiUtil.getUser(), page.cloneToDraft(), PageType.AUTO_DRAFT); pageUuid = draft.getPageUuid(); page.setPageUuid(pageUuid); log.info("Nut save draft with new page uuid {}", pageUuid); } List<FileNode> attachments = new ArrayList<FileNode>(); for (File attach : files.values()) { FileNode node = new FileNode(); node.setFilename(attach.getName()); node.setFile(new FileInputStream(attach)); node.setBulkZip(false); node.setShared(false); node.setIdentifier(pageUuid); node.setCreateor(WikiUtil.getUserName()); node.setType(RepositoryService.TYPE_ATTACHMENT); node.setStatus(PageType.NONE_DRAFT.value()); node.setComment("TextNut uploaded attached file"); //???node.setContentType(contentType); attachments.add(node); log.info("Uploading attachment {}", node.getFilename()); } attachments = getPageService().uploadAttachments(spaceUname, pageUuid, attachments, true); page.setAttachments(attachments); log.info("Nut uploaded attachments successfully."); } getPageService().savePage(page, WikiConstants.NOTIFY_ALL, true); log.info("Nut save page {} by version {} successfully.", title, version); getActivityLog().logPageSaved(page); //return version:pageUUID combination. Version number must greater than 0 return page.getVersion() + ":" + page.getPageUuid(); } } } log.warn("Nut save or update page {} (UUID:{}) failed on space {}.", new String[] { title, pageUuid, spaceUname }); if (pageUuid == null) { return String.valueOf(NutCode.PAGE_CREATED_FAILED); } else { return String.valueOf(NutCode.PAGE_UPDATE_FAILED); } } catch (FileUploadException e) { log.error("Upload Nut file failed", e); } catch (UnsupportedEncodingException e) { log.error("Upload Nut file failed", e); } catch (IOException e) { log.error("Upload Nut file failed", e); } catch (PageException e) { log.error("Upload Nut file failed", e); } catch (VersionConflictException e) { log.error("Upload Nut file failed", e); } catch (PageSaveTiemoutExcetpion e) { log.error("Upload Nut file failed", e); } catch (DuplicatedPageException e) { log.error("Duplicate name for nut file.", e); return String.valueOf(NutCode.PAGE_DUPLICATED_TITLE); } catch (RepositoryException e) { log.error("Upload Nut file failed", e); } catch (RepositoryTiemoutExcetpion e) { log.error("Upload Nut file failed", e); } catch (RepositoryQuotaException e) { log.error("Upload Nut file failed", e); } return String.valueOf(NutCode.PAGE_UPDATED); }
From source file:com.ikon.servlet.admin.OmrServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = ""; String userId = request.getRemoteUser(); updateSessionManager(request);//from ww w . ja v a 2 s . c o m try { if (ServletFileUpload.isMultipartContent(request)) { String fileName = null; InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Set<String> properties = new HashSet<String>(); Omr om = new Omr(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("om_id")) { om.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("om_name")) { om.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("om_properties")) { properties.add(item.getString("UTF-8")); } else if (item.getFieldName().equals("om_active")) { om.setActive(true); } } else { is = item.getInputStream(); fileName = item.getName(); } } om.setProperties(properties); if (action.equals("create") || action.equals("edit")) { // Store locally template file to be used later if (is != null && is.available() > 0) { // Case update only name byte[] data = IOUtils.toByteArray(is); File tmp = FileUtils.createTempFile(); FileOutputStream fos = new FileOutputStream(tmp); IOUtils.write(data, fos); IOUtils.closeQuietly(fos); // Store template file om.setTemplateFileName(FilenameUtils.getName(fileName)); om.setTemplateFileMime(MimeTypeConfig.mimeTypes.getContentType(fileName)); om.setTemplateFilContent(data); IOUtils.closeQuietly(is); // Create training files Map<String, File> trainingMap = OMRHelper.trainingTemplate(tmp); File ascFile = trainingMap.get(OMRHelper.ASC_FILE); File configFile = trainingMap.get(OMRHelper.CONFIG_FILE); // Store asc file om.setAscFileName(om.getTemplateFileName() + ".asc"); om.setAscFileMime(MimeTypeConfig.MIME_TEXT); is = new FileInputStream(ascFile); om.setAscFileContent(IOUtils.toByteArray(is)); IOUtils.closeQuietly(is); // Store config file om.setConfigFileName(om.getTemplateFileName() + ".config"); om.setConfigFileMime(MimeTypeConfig.MIME_TEXT); is = new FileInputStream(configFile); om.setConfigFileContent(IOUtils.toByteArray(is)); IOUtils.closeQuietly(is); // Delete temporal files FileUtils.deleteQuietly(tmp); FileUtils.deleteQuietly(ascFile); FileUtils.deleteQuietly(configFile); } if (action.equals("create")) { long id = OmrDAO.getInstance().create(om); // Activity log UserActivity.log(userId, "ADMIN_OMR_CREATE", Long.toString(id), null, om.toString()); } else if (action.equals("edit")) { OmrDAO.getInstance().updateTemplate(om); om = OmrDAO.getInstance().findByPk(om.getId()); // Activity log UserActivity.log(userId, "ADMIN_OMR_EDIT", Long.toString(om.getId()), null, om.toString()); } list(userId, request, response); } else if (action.equals("delete")) { OmrDAO.getInstance().delete(om.getId()); // Activity log UserActivity.log(userId, "ADMIN_OMR_DELETE", Long.toString(om.getId()), null, null); list(userId, request, response); } else if (action.equals("editAsc")) { Omr omr = OmrDAO.getInstance().findByPk(om.getId()); omr.setAscFileContent(IOUtils.toByteArray(is)); omr.setAscFileMime(MimeTypeConfig.MIME_TEXT); omr.setAscFileName(omr.getTemplateFileName() + ".asc"); OmrDAO.getInstance().update(omr); omr = OmrDAO.getInstance().findByPk(om.getId()); IOUtils.closeQuietly(is); // Activity log UserActivity.log(userId, "ADMIN_OMR_EDIT_ASC", Long.toString(om.getId()), null, null); list(userId, request, response); } else if (action.equals("editFields")) { Omr omr = OmrDAO.getInstance().findByPk(om.getId()); omr.setFieldsFileContent(IOUtils.toByteArray(is)); omr.setFieldsFileMime(MimeTypeConfig.MIME_TEXT); omr.setFieldsFileName(omr.getTemplateFileName() + ".fields"); OmrDAO.getInstance().update(omr); omr = OmrDAO.getInstance().findByPk(om.getId()); IOUtils.closeQuietly(is); // Activity log UserActivity.log(userId, "ADMIN_OMR_EDIT_FIELDS", Long.toString(om.getId()), null, null); list(userId, request, response); } else if (action.equals("check")) { File form = FileUtils.createTempFile(); OutputStream formFile = new FileOutputStream(form); formFile.write(IOUtils.toByteArray(is)); IOUtils.closeQuietly(formFile); formFile.close(); Map<String, String> results = OMRHelper.process(form, om.getId()); FileUtils.deleteQuietly(form); IOUtils.closeQuietly(is); UserActivity.log(userId, "ADMIN_OMR_CHECK_TEMPLATE", Long.toString(om.getId()), null, null); results(userId, request, response, action, results, om.getId()); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (OMRException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (InvalidFileStructureException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (InvalidImageIndexException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (UnsupportedTypeException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (MissingParameterException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (WrongParameterException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:com.openkm.servlet.admin.StampServlet.java
@SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); String action = WebUtils.getString(request, "action"); Session session = null;//ww w . j a v a2 s . c om updateSessionManager(request); try { if (ServletFileUpload.isMultipartContent(request)) { session = JCRUtils.getSession(); InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); StampImage si = new StampImage(); for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("si_id")) { si.setId(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("si_name")) { si.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_description")) { si.setDescription(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_layer")) { si.setLayer(Integer.parseInt(item.getString("UTF-8"))); } else if (item.getFieldName().equals("si_opacity")) { si.setOpacity(Float.parseFloat(item.getString("UTF-8"))); } else if (item.getFieldName().equals("si_expr_x")) { si.setExprX(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_expr_y")) { si.setExprY(item.getString("UTF-8")); } else if (item.getFieldName().equals("si_active")) { si.setActive(true); } else if (item.getFieldName().equals("si_users")) { si.getUsers().add(item.getString("UTF-8")); } } else { is = item.getInputStream(); si.setImageMime(Config.mimeTypes.getContentType(item.getName())); si.setImageContent(SecureStore.b64Encode(IOUtils.toByteArray(is))); is.close(); } } if (action.equals("imageCreate")) { int id = StampImageDAO.create(si); // Activity log UserActivity.log(session.getUserID(), "ADMIN_STAMP_IMAGE_CREATE", Integer.toString(id), si.toString()); imageList(session, request, response); } else if (action.equals("imageEdit")) { StampImageDAO.update(si); // Activity log UserActivity.log(session.getUserID(), "ADMIN_STAMP_IMAGE_EDIT", Integer.toString(si.getId()), si.toString()); imageList(session, request, response); } else if (action.equals("imageDelete")) { StampImageDAO.delete(si.getId()); // Activity log UserActivity.log(session.getUserID(), "ADMIN_STAMP_IMAGE_DELETE", Integer.toString(si.getId()), null); imageList(session, request, response); } } } catch (LoginException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (RepositoryException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } finally { JCRUtils.logout(session); } }
From source file:com.takin.mvc.mvc.server.CommonsMultipartResolver.java
/** * Parse the given List of Commons FileItems into a Spring MultipartParsingResult, * containing Spring MultipartFile instances and a Map of multipart parameter. * @param fileItems the Commons FileIterms to parse * @param encoding the encoding to use for form fields * @return the Spring MultipartParsingResult * @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem) *//*from w w w .ja v a 2s . c om*/ protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) { MultiValueMap<String, CommonsMultipartFile> multipartFiles = new LinkedMultiValueMap<String, CommonsMultipartFile>(); Map<String, String[]> multipartParameters = new HashMap<String, String[]>(); // Extract multipart files and multipart parameters. for (FileItem fileItem : fileItems) { if (fileItem.isFormField()) { String value; String partEncoding = determineEncoding(fileItem.getContentType(), encoding); if (partEncoding != null) { try { value = fileItem.getString(partEncoding); } catch (UnsupportedEncodingException ex) { if (logger.isWarnEnabled()) { logger.warn("Could not decode multipart item '" + fileItem.getFieldName() + "' with encoding '" + partEncoding + "': using platform default"); } value = fileItem.getString(); } } else { value = fileItem.getString(); } String[] curParam = multipartParameters.get(fileItem.getFieldName()); if (curParam == null) { // simple form field multipartParameters.put(fileItem.getFieldName(), new String[] { value }); } else { // array of simple form fields String[] newParam = StringUtils.addStringToArray(curParam, value); multipartParameters.put(fileItem.getFieldName(), newParam); } } else { // multipart file field CommonsMultipartFile file = new CommonsMultipartFile(fileItem); multipartFiles.add(file.getName(), file); if (logger.isDebugEnabled()) { logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() + " bytes with original filename [" + file.getOriginalFilename() + "], stored " + file.getStorageDescription()); } } } return new MultipartParsingResult(multipartFiles, multipartParameters); }
From source file:controller.ProductProcess.java
public String processImage(HttpServletRequest request, HttpServletResponse response) throws IOException { if (!ServletFileUpload.isMultipartContent(request)) { PrintWriter writer = response.getWriter(); writer.print("error"); return ""; }/*from w ww .j a va 2 s . c o m*/ String pathh = ""; DiskFileItemFactory factory = new DiskFileItemFactory(MEMORY_THRESHOLD, new File(System.getProperty("java.io.tmpdir"))); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(MAX_FILE_SIZE); upload.setSizeMax(MAX_REQUEST_SIZE); String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } try { List<FileItem> formItems = upload.parseRequest(request); if (formItems != null && formItems.size() > 0) { for (FileItem formItem : formItems) { if (!formItem.isFormField()) { String a = formItem.getName(); String fileName = new File(a).getName(); pathh = fileName; String filePath = uploadPath + File.separator + fileName; File storeFile = new File(filePath); formItem.write(storeFile); } else { String nameAttribute = formItem.getFieldName(); String valueAttribute = formItem.getString("UTF-8"); request.setAttribute(nameAttribute, valueAttribute); } } } } catch (Exception e) { e.printStackTrace(); return ""; } return pathh; }
From source file:com.ikon.servlet.admin.ConfigServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); ServletContext sc = getServletContext(); String action = null;//from ww w. j av a 2 s .c o m String filter = null; String userId = request.getRemoteUser(); Session dbSession = null; updateSessionManager(request); try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Config cfg = new Config(); byte data[] = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("filter")) { filter = item.getString("UTF-8"); } else if (item.getFieldName().equals("cfg_key")) { cfg.setKey(item.getString("UTF-8")); } else if (item.getFieldName().equals("cfg_type")) { cfg.setType(item.getString("UTF-8")); } else if (item.getFieldName().equals("cfg_value")) { cfg.setValue(item.getString("UTF-8").trim()); } } else { is = item.getInputStream(); data = IOUtils.toByteArray(is); is.close(); } } if (action.equals("create")) { if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals(""))); } else if (Config.SELECT.equals(cfg.getType())) { ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey()); if (stSelect != null) { for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.getValue().equals(cfg.getValue())) { stOption.setSelected(true); } } } cfg.setValue(new Gson().toJson(stSelect)); } ConfigDAO.create(cfg); com.ikon.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_CREATE", cfg.getKey(), null, cfg.toString()); list(userId, filter, request, response); } else if (action.equals("edit")) { if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals(""))); } else if (Config.SELECT.equals(cfg.getType())) { ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey()); if (stSelect != null) { for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.getValue().equals(cfg.getValue())) { stOption.setSelected(true); } else { stOption.setSelected(false); } } } cfg.setValue(new Gson().toJson(stSelect)); } ConfigDAO.update(cfg); com.ikon.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_EDIT", cfg.getKey(), null, cfg.toString()); list(userId, filter, request, response); } else if (action.equals("delete")) { ConfigDAO.delete(cfg.getKey()); com.ikon.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_DELETE", cfg.getKey(), null, null); list(userId, filter, request, response); } else if (action.equals("import")) { dbSession = HibernateUtil.getSessionFactory().openSession(); importConfig(userId, request, response, data, dbSession); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_CONFIG_IMPORT", null, null, null); list(userId, filter, request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (SQLException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } finally { HibernateUtil.close(dbSession); } }
From source file:com.esri.gpt.catalog.gxe.GxeServlet.java
/** * Reads a posted XML document.//from ww w . j a va2s . c o m * @param request the HTTP servlet request * @param response the HTTP servlet response * @param context the request context * @throws Exception if a processing exception occurs */ private String readPostedXml(HttpServletRequest request, HttpServletResponse response, RequestContext context) throws Exception { String sXml = ""; String sContentType = Val.chkStr(request.getContentType()); if (sContentType.toLowerCase().startsWith("multipart/form-data;")) { String sMultipartAttribute = "uploadedfiles[]"; Object oFile = request.getAttribute(sMultipartAttribute); if (oFile == null) { sMultipartAttribute = "uploadedfile"; oFile = request.getAttribute(sMultipartAttribute); } if ((oFile != null) && (oFile instanceof FileItem)) { FileItem item = (FileItem) oFile; sXml = Val.chkStr(Val.removeBOM(item.getString("UTF-8"))); } } else if (sContentType.toLowerCase().startsWith("application/x-www-form-urlencoded")) { String sFormUrlParamater = "xml"; sXml = Val.chkStr(Val.removeBOM(request.getParameter(sFormUrlParamater))); } else { sXml = Val.chkStr(Val.removeBOM(this.readInputCharacters(request))); } /* // check for multipart/form-data String sMultipartAttribute = "uploadedfiles[]"; Object oFile = request.getAttribute(sMultipartAttribute); if ((oFile != null) && (oFile instanceof FileItem)) { FileItem item = (FileItem)oFile; sXml = Val.chkStr(Val.removeBOM(item.getString("UTF-8"))); } else { // check for application/x-www-form-urlencoded String sFormUrlParamater = "xml"; sXml = Val.chkStr(request.getParameter(sFormUrlParamater)); if (sXml == null) { // check the raw post body sXml = this.readInputCharacters(request); } } */ return sXml; }
From source file:com.enonic.cms.web.portal.services.ServicesProcessorBase.java
private ExtendedMap parseMultiPartRequest(HttpServletRequest request) { ExtendedMap formItems = new ExtendedMap(true); try {/*from w w w .j a va2 s. co m*/ List paramList = fileUpload.parseRequest(new ServletRequestContext(request)); for (Iterator iter = paramList.iterator(); iter.hasNext();) { FileItem fileItem = (FileItem) iter.next(); String name = fileItem.getFieldName(); if (fileItem.isFormField()) { String value = fileItem.getString("UTF-8"); if (formItems.containsKey(name)) { ArrayList<Object> values = new ArrayList<Object>(); Object obj = formItems.get(name); if (obj instanceof Object[]) { String[] objArray = (String[]) obj; for (int i = 0; i < objArray.length; i++) { values.add(objArray[i]); } } else { values.add(obj); } values.add(value); formItems.put(name, values.toArray(new String[values.size()])); } else { formItems.put(name, value); } } else { if (fileItem.getSize() > 0) { if (formItems.containsKey(name)) { ArrayList<Object> values = new ArrayList<Object>(); Object obj = formItems.get(name); if (obj instanceof FileItem[]) { FileItem[] objArray = (FileItem[]) obj; for (int i = 0; i < objArray.length; i++) { values.add(objArray[i]); } } else { values.add(obj); } values.add(fileItem); formItems.put(name, values.toArray(new FileItem[values.size()])); } else { formItems.put(name, fileItem); } } } } } catch (FileUploadException fue) { String message = "Error occurred with file upload: %t"; VerticalAdminLogger.error(message, fue); } catch (UnsupportedEncodingException uee) { String message = "Character encoding not supported: %t"; VerticalAdminLogger.error(message, uee); } // Add parameters from url Map paramMap = request.getParameterMap(); for (Iterator iter = paramMap.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); if (entry.getValue() instanceof String[]) { String[] values = (String[]) entry.getValue(); for (int i = 0; i < values.length; i++) { formItems.put(key, values[i]); } } else { formItems.put(key, entry.getValue()); } } return formItems; }
From source file:controllers.LinguagemController.java
private void adicionarOuEditarLinguagem() throws IOException, ServletException { String anoLancamento, nome, id, licenca, descricao, caminhoLogo; anoLancamento = nome = licenca = descricao = caminhoLogo = id = ""; File file;/*from ww w . j a va2s. c o m*/ int maxFileSize = 5000 * 1024; int maxMemSize = 5000 * 1024; ServletContext context = getServletContext(); String filePath = context.getInitParameter("file-upload"); String contentType = request.getContentType(); if ((contentType.contains("multipart/form-data"))) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(maxMemSize); factory.setRepository(new File("c:\\temp")); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxFileSize); try { List fileItems = upload.parseRequest(request); Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { String fileName = fi.getName(); if (fileName != null) { String name = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf(".")); file = new File(filePath + name); caminhoLogo = file.getName(); fi.write(file); } } else { String campo = fi.getFieldName(); String valor = fi.getString("UTF-8"); switch (campo) { case "nome": nome = valor; break; case "ano_lancamento": anoLancamento = valor; break; case "licenca": licenca = valor; break; case "descricao": descricao = valor; break; case "id": id = valor; break; default: break; } } } } catch (Exception ex) { System.out.println(ex); } } boolean atualizando = !id.isEmpty(); if (atualizando) { Linguagem linguagem = dao.select(Integer.parseInt(id)); linguagem.setAnoLancamento(anoLancamento); linguagem.setDescricao(descricao); linguagem.setLicenca(licenca); linguagem.setNome(nome); if (!caminhoLogo.isEmpty()) { File imagemAntiga = new File(filePath + linguagem.getCaminhoLogo()); imagemAntiga.delete(); linguagem.setCaminhoLogo(caminhoLogo); } dao.update(linguagem); } else { Linguagem linguagem = new Linguagem(nome, anoLancamento, licenca, descricao, caminhoLogo); dao.insert(linguagem); } response.sendRedirect("linguagens.jsp"); // response.getWriter().print("<script>setTimeout(function () {" // + "window.location.href='linguagens.jsp';" // + "}" // + ", 1500);</script>"); }
From source file:com.openkm.servlet.admin.ConfigServlet.java
@Override @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { log.debug("doPost({}, {})", request, response); request.setCharacterEncoding("UTF-8"); ServletContext sc = getServletContext(); String action = null;/*from w ww . java2 s . c o m*/ String filter = ""; String userId = request.getRemoteUser(); Session dbSession = null; updateSessionManager(request); try { if (ServletFileUpload.isMultipartContent(request)) { InputStream is = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); ConfigStoredFile stFile = new ConfigStoredFile(); Config cfg = new Config(); byte data[] = null; for (Iterator<FileItem> it = items.iterator(); it.hasNext();) { FileItem item = it.next(); if (item.isFormField()) { if (item.getFieldName().equals("action")) { action = item.getString("UTF-8"); } else if (item.getFieldName().equals("filter")) { filter = item.getString("UTF-8"); } else if (item.getFieldName().equals("cfg_key")) { cfg.setKey(item.getString("UTF-8")); } else if (item.getFieldName().equals("cfg_type")) { cfg.setType(item.getString("UTF-8")); } else if (item.getFieldName().equals("cfg_value")) { cfg.setValue(item.getString("UTF-8").trim()); } } else { is = item.getInputStream(); stFile.setName(item.getName()); stFile.setMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); if (cfg.getKey() != null && cfg.getKey().startsWith("logo")) { String size = null; if (cfg.getKey().equals(com.openkm.core.Config.PROPERTY_LOGO_LOGIN)) { size = "316x74>"; } else if (cfg.getKey().equals(com.openkm.core.Config.PROPERTY_LOGO_REPORT)) { size = "150x35>"; } File tmpIn = FileUtils.createTempFileFromMime(stFile.getMime()); File tmpOut = FileUtils.createTempFileFromMime(stFile.getMime()); FileOutputStream fos = null; try { fos = new FileOutputStream(tmpIn); IOUtils.copy(is, fos); ImageUtils.resize(tmpIn, size, tmpOut); data = FileUtils.readFileToByteArray(tmpOut); } finally { FileUtils.deleteQuietly(tmpIn); FileUtils.deleteQuietly(tmpOut); IOUtils.closeQuietly(fos); IOUtils.closeQuietly(is); } } else { data = IOUtils.toByteArray(is); IOUtils.closeQuietly(is); } stFile.setContent(SecureStore.b64Encode(data)); } } if (action.equals("create")) { if (Config.FILE.equals(cfg.getType())) { cfg.setValue(new Gson().toJson(stFile)); } else if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals(""))); } else if (Config.SELECT.equals(cfg.getType())) { ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey()); if (stSelect != null) { for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.getValue().equals(cfg.getValue())) { stOption.setSelected(true); } } } cfg.setValue(new Gson().toJson(stSelect)); } ConfigDAO.create(cfg); com.openkm.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_CREATE", cfg.getKey(), null, cfg.toString()); list(userId, filter, request, response); } else if (action.equals("edit")) { if (Config.FILE.equals(cfg.getType())) { cfg.setValue(new Gson().toJson(stFile)); } else if (Config.BOOLEAN.equals(cfg.getType())) { cfg.setValue(Boolean.toString(cfg.getValue() != null && !cfg.getValue().equals(""))); } else if (Config.SELECT.equals(cfg.getType())) { ConfigStoredSelect stSelect = ConfigDAO.getSelect(cfg.getKey()); if (stSelect != null) { for (ConfigStoredOption stOption : stSelect.getOptions()) { if (stOption.getValue().equals(cfg.getValue())) { stOption.setSelected(true); } else { stOption.setSelected(false); } } } cfg.setValue(new Gson().toJson(stSelect)); } ConfigDAO.update(cfg); com.openkm.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_EDIT", cfg.getKey(), null, cfg.toString()); list(userId, filter, request, response); } else if (action.equals("delete")) { ConfigDAO.delete(cfg.getKey()); com.openkm.core.Config.reload(sc, new Properties()); // Activity log UserActivity.log(userId, "ADMIN_CONFIG_DELETE", cfg.getKey(), null, null); list(userId, filter, request, response); } else if (action.equals("import")) { dbSession = HibernateUtil.getSessionFactory().openSession(); importConfig(userId, request, response, data, dbSession); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_CONFIG_IMPORT", null, null, null); list(userId, filter, request, response); } } } catch (DatabaseException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (SQLException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } finally { HibernateUtil.close(dbSession); } }