List of usage examples for org.apache.commons.fileupload.servlet ServletFileUpload parseRequest
public List parseRequest(HttpServletRequest request) throws FileUploadException
From source file:com.ephesoft.gxt.admin.server.ImportDocumentTypeUploadServlet.java
/** * This API is used to process uploaded file and unzip file in export-batch-folder . * // ww w . j a v a2s . c o m * @param upload {@link ServletFileUpload} uploaded file. * @param req {@link HttpServletRequest}. * @param printWriter {@link PrintWriter}. * @param parentDirPath {@link String} to create absolute unzip directory path. * @return {@link File} temporary file after unzip. */ private String processUploadedFile(final ServletFileUpload upload, final HttpServletRequest req, final PrintWriter printWriter, final String parentDirPath) { String tempUnZipDir = ""; String zipFileName = ""; String zipPathname = ""; File tempZipFile = null; List<FileItem> items; try { items = upload.parseRequest(req); for (final FileItem item : items) { if (!item.isFormField()) {// && "importFile".equals(item.getFieldName())) { zipPathname = getZipPath(item, parentDirPath); zipFileName = getZipFileName(item); tempZipFile = copyItemContentInFile(item, zipPathname, printWriter); } } } catch (final FileUploadException e) { printWriter.write("Unable to read the form contents.Please try again."); } tempUnZipDir = parentDirPath + File.separator + zipFileName.substring(0, zipFileName.lastIndexOf('.')) + System.nanoTime(); try { FileUtils.unzip(tempZipFile, tempUnZipDir); } catch (final Exception e) { printWriter.write("Unable to unzip the file.Please try again."); tempZipFile.delete(); } return tempUnZipDir; }
From source file:com.boundlessgeo.geoserver.api.controllers.IconController.java
@RequestMapping(value = "/{wsName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseStatus(value = HttpStatus.CREATED) @ResponseBody JSONArr create(@PathVariable String wsName, HttpServletRequest request) throws IOException, FileUploadException { WorkspaceInfo ws;/*from w w w. j a va2s .c o m*/ Resource styles; if (wsName == null) { ws = null; styles = dataDir().getRoot("styles"); } else { ws = findWorkspace(wsName, catalog()); styles = dataDir().get(ws, "styles"); } ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); @SuppressWarnings("unchecked") List<FileItem> input = (List<FileItem>) upload.parseRequest(request); JSONArr created = new JSONArr(); for (FileItem file : input) { String filename = file.getName(); // trim filename if required if (filename.lastIndexOf('/') != -1) { filename = filename.substring(filename.lastIndexOf('/')); } if (filename.lastIndexOf('\\') != -1) { filename = filename.substring(filename.lastIndexOf('\\')); } String ext = fileExt(filename); if (!ICON_FORMATS.containsKey(ext)) { String msg = "Icon " + filename + " format " + ext + " unsupported - try:" + ICON_FORMATS.keySet(); LOG.warning(msg); throw new FileUploadException(msg); } try { InputStream data = file.getInputStream(); Resources.copy(data, styles, filename); icon(created.addObject(), ws, styles.get(filename), request); } catch (Exception e) { throw new FileUploadException("Unable to write " + filename, e); } } return created; }
From source file:de.zib.gndms.kit.monitor.GroovyMonitor.java
/** * Evaluate the multiparts of a http multipart request as groovy shell script code. * * @param servletRequest/*www.j a va 2 s .c om*/ * @param args to the script/command (plain string) *@param b64 if true, the content is asumed to be encoded in base64 @throws IOException */ synchronized void evalParts(@NotNull HttpServletRequest servletRequest, @NotNull String args, boolean b64) throws IOException { try { if (isRemainingOpen()) { boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequest); if (isMultipart) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(servletRequest); for (FileItem fi : items) handlePart(b64, args, fi); } catch (FileUploadException fue) { throw new RuntimeException(fue); } } else throw new RuntimeException("Non-multipart content received"); } else { throw new RuntimeException("Processing of multiple requests on a monitor in " + " mode " + runMode + " is either invalid " + " or monitor was closed down in the middle of processing"); } } finally { postDone(); notifyAll(); } }
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 ""; }/*w w w.j a v a 2s. c om*/ 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.reachcall.pretty.http.ProxyServlet.java
@SuppressWarnings("unchecked") private void doMultipart(HttpPost method, HttpServletRequest req) throws ServletException, FileUploadException, UnsupportedEncodingException, IOException { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setSizeThreshold(this.getMaxFileUploadSize()); diskFileItemFactory.setRepository(TEMP_DIR); ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); List<FileItem> fileItems = (List<FileItem>) upload.parseRequest(req); MultipartEntity entity = new MultipartEntity(); for (FileItem fItem : fileItems) { if (fItem.isFormField()) { LOG.log(Level.INFO, "Form field {0}", fItem.getName()); StringBody part = new StringBody(fItem.getFieldName()); entity.addPart(fItem.getFieldName(), part); } else {//w ww . j av a 2s . c o m LOG.log(Level.INFO, "File item {0}", fItem.getName()); InputStreamBody file = new InputStreamBody(fItem.getInputStream(), fItem.getName(), fItem.getContentType()); entity.addPart(fItem.getFieldName(), file); } } method.setEntity(entity); }
From source file:com.exedio.cope.live.Bar.java
void doRequest(final HttpServletRequest request, final HttpSession httpSession, final HttpServletResponse response, final Anchor anchor) throws IOException { if (!Cop.isPost(request)) { try {//from ww w . j a v a 2 s .com startTransaction("redirectHome"); anchor.redirectHome(request, response); model.commit(); } finally { model.rollbackIfNotCommitted(); } return; } final String referer; if (isMultipartContent(request)) { final HashMap<String, String> fields = new HashMap<String, String>(); final HashMap<String, FileItem> files = new HashMap<String, FileItem>(); final FileItemFactory factory = new DiskFileItemFactory(); final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(UTF_8.name()); try { for (final Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext();) { final FileItem item = (FileItem) i.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString(UTF_8.name())); else files.put(item.getFieldName(), item); } } catch (final FileUploadException e) { throw new RuntimeException(e); } final String featureID = fields.get(FEATURE); if (featureID == null) throw new NullPointerException(); final Media feature = (Media) model.getFeature(featureID); if (feature == null) throw new NullPointerException(featureID); final String itemID = fields.get(ITEM); if (itemID == null) throw new NullPointerException(); final FileItem file = files.get(FILE); try { startTransaction("publishFile(" + featureID + ',' + itemID + ')'); final Item item = model.getItem(itemID); if (fields.get(PUBLISH_NOW) != null) { for (final History history : History.getHistories(item.getCopeType())) { final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(), false); event.createFeature(feature, feature.getName(), feature.isNull(item) ? null : ("file type=" + feature.getContentType(item) + " size=" + feature.getLength(item)), "file name=" + file.getName() + " type=" + file.getContentType() + " size=" + file.getSize()); } // TODO use more efficient setter with File or byte[] feature.set(item, file.getInputStream(), file.getContentType()); } else { anchor.modify(file, feature, item); } model.commit(); } catch (final NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } referer = fields.get(REFERER); } else // isMultipartContent { if (request.getParameter(BORDERS_ON) != null || request.getParameter(BORDERS_ON_IMAGE) != null) { anchor.borders = true; } else if (request.getParameter(BORDERS_OFF) != null || request.getParameter(BORDERS_OFF_IMAGE) != null) { anchor.borders = false; } else if (request.getParameter(CLOSE) != null || request.getParameter(CLOSE_IMAGE) != null) { httpSession.removeAttribute(LoginServlet.ANCHOR); } else if (request.getParameter(SWITCH_TARGET) != null) { anchor.setTarget(servlet.getTarget(request.getParameter(SWITCH_TARGET))); } else if (request.getParameter(SAVE_TARGET) != null) { try { startTransaction("saveTarget"); anchor.getTarget().save(anchor); model.commit(); } finally { model.rollbackIfNotCommitted(); } anchor.notifyPublishedAll(); } else { final String featureID = request.getParameter(FEATURE); if (featureID == null) throw new NullPointerException(); final Feature featureO = model.getFeature(featureID); if (featureO == null) throw new NullPointerException(featureID); final String itemID = request.getParameter(ITEM); if (itemID == null) throw new NullPointerException(); if (featureO instanceof StringField) { final StringField feature = (StringField) featureO; final String value = request.getParameter(TEXT); try { startTransaction("barText(" + featureID + ',' + itemID + ')'); final Item item = model.getItem(itemID); if (request.getParameter(PUBLISH_NOW) != null) { String v = value; if ("".equals(v)) v = null; for (final History history : History.getHistories(item.getCopeType())) { final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(), false); event.createFeature(feature, feature.getName(), feature.get(item), v); } feature.set(item, v); anchor.notifyPublished(feature, item); } else { anchor.modify(value, feature, item); } model.commit(); } catch (final NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } } else { final IntegerField feature = (IntegerField) featureO; final String itemIDFrom = request.getParameter(ITEM_FROM); if (itemIDFrom == null) throw new NullPointerException(); try { startTransaction("swapPosition(" + featureID + ',' + itemIDFrom + ',' + itemID + ')'); final Item itemFrom = model.getItem(itemIDFrom); final Item itemTo = model.getItem(itemID); final Integer positionFrom = feature.get(itemFrom); final Integer positionTo = feature.get(itemTo); feature.set(itemFrom, feature.getMinimum()); feature.set(itemTo, positionFrom); feature.set(itemFrom, positionTo); for (final History history : History.getHistories(itemFrom.getCopeType())) { final History.Event event = history.createEvent(itemFrom, anchor.getHistoryAuthor(), false); event.createFeature(feature, feature.getName(), positionFrom, positionTo); } for (final History history : History.getHistories(itemTo.getCopeType())) { final History.Event event = history.createEvent(itemTo, anchor.getHistoryAuthor(), false); event.createFeature(feature, feature.getName(), positionTo, positionFrom); } model.commit(); } catch (final NoSuchIDException e) { throw new RuntimeException(e); } finally { model.rollbackIfNotCommitted(); } } } referer = request.getParameter(REFERER); } if (referer != null) response.sendRedirect(response.encodeRedirectURL(referer)); }
From source file:com.blog.fckeditor.ConnectorServlet.java
/** * Manage the <code>POST</code> requests (<code>FileUpload</code>).<br /> * // ww w . ja va 2 s . co m * The servlet accepts commands sent in the following format:<br /> * <code>connector?Command=<FileUpload>&Type=<ResourceType>&CurrentFolder=<FolderPath></code> * with the file in the <code>POST</code> body.<br /> * <br> * It stores an uploaded file (renames a file if another exists with the * same name) and then returns the JavaScript callback. */ @SuppressWarnings("unchecked") public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command"); String typeStr = request.getParameter("Type"); String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr); logger.debug("Parameter Type: {}", typeStr); logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr' // are empty if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) { commandStr = "QuickUpload"; currentFolderStr = "/"; } if (!RequestCycleHandler.isEnabledForFileUpload(request)) ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null, Messages.NOT_AUTHORIZED_FOR_UPLOAD); else if (!CommandHandler.isValidForPost(commandStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND); else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr)) ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE); else if (!UtilsFile.isValidPath(currentFolderStr)) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType); String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath); UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists()) ur = UploadResponse.UR_INVALID_CURRENT_FOLDER; else { String newFilename = null; FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // upload.setHeaderEncoding("UTF-8"); try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time FileItem uplFile = items.get(0); String rawName = UtilsFile.sanitizeFileName(uplFile.getName()); String filename = FilenameUtils.getName(rawName); String baseName = FilenameUtils.removeExtension(filename); String extension = FilenameUtils.getExtension(filename); // filename = UUID.randomUUID().toString() + "." + extension; if (!ExtensionsHandler.isAllowed(resourceType, extension)) ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); else { // construct an unique file name File pathToSave = new File(currentDir, filename); int counter = 1; while (pathToSave.exists()) { newFilename = baseName.concat("(").concat(String.valueOf(counter)).concat(")") .concat(".").concat(extension); pathToSave = new File(currentDir, newFilename); counter++; } if (Utils.isEmpty(newFilename)) ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(filename)); else ur = new UploadResponse(UploadResponse.SC_RENAMED, UtilsResponse.constructResponseUrl(request, resourceType, currentFolderStr, true, ConnectorHandler.isFullUrl()).concat(newFilename), newFilename); // secure image check if (resourceType.equals(ResourceTypeHandler.IMAGE) && ConnectorHandler.isSecureImageUploads()) { if (UtilsFile.isImage(uplFile.getInputStream())) uplFile.write(pathToSave); else { uplFile.delete(); ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION); } } else uplFile.write(pathToSave); } } catch (Exception e) { ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR); } } } out.print(ur); out.flush(); out.close(); logger.debug("Exiting Connector#doPost"); }
From source file:edu.pitt.servlets.processAddMedia.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from www . j a v a 2s.c o m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); String userID = (String) session.getAttribute("userID"); String error = "select correct format "; session.setAttribute("error", error); response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { // Process only if its multipart content // Create a factory for disk-based file items File file; // We might need to play with the file sizes int maxFileSize = 50000 * 1024; int maxMemSize = 50000 * 1024; ServletContext context = this.getServletContext(); // Note that this file path refers to a virtual path // relative to this servlet. The uploads directory // is part of this project. The physical path varies // from the virtual path String filePath = context.getRealPath("/uploads") + "/"; out.println("Physical folder is located at: " + filePath + "<br />"); // Verify the content type String contentType = request.getContentType(); // This is very important - make sure that the web form that // uploads the file is actually set to enctype="multipart/form-data" // An example of upload form for this project is in index.html if ((contentType.indexOf("multipart/form-data") >= 0)) { DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize. factory.setRepository(new File(filePath)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded. upload.setSizeMax(maxFileSize); try { // Parse the request to get file items. List fileItems = upload.parseRequest(request); // Process the uploaded file items Iterator i = fileItems.iterator(); while (i.hasNext()) { FileItem fi = (FileItem) i.next(); if (!fi.isFormField()) { // Get the uploaded file parameters String fieldName = fi.getFieldName(); out.println("field name" + fieldName); String fileName = fi.getName(); out.println("file name" + fileName); // file name is present boolean isInMemory = fi.isInMemory(); long sizeInBytes = fi.getSize(); // out.println("file size"+ sizeInBytes); // Write the file if (fileName.lastIndexOf("\\") >= 0) { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\"))); } else { file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1)); } fi.write(file); // out.println("Uploaded Filename: " + filePath + fileName + "<br />"); String savepath = filePath + fileName; // to check correct format is entered or not int dotindex = fileName.indexOf("."); if (!(fileName.substring(dotindex).matches(".ogv|.webm|.mp4|.png|.jpeg|.jpg|.gif"))) { response.sendRedirect("./pages/addMedia.jsp"); } // receives projectID from listProjects.jsp from edit href link , adding in existing project // corresponding constructor is used if (session.getAttribute("projectID") != null) { Integer projectID = (Integer) session.getAttribute("projectID"); media = new Media(projectID, fileName); } // first time when user enters media for project , this constructor is used else { media = new Media(userID, fileName); } System.out.println("Into the media constructor"); // redirected to listProject response.sendRedirect("./pages/listProject.jsp"); // media constructor // response.redirect(listprojects.jsp); processRequest(request, response); } } } catch (FileUploadException ex) { Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(processAddMedia.class.getName()).log(Level.SEVERE, null, ex); } } } }
From source file:net.i2cat.csade.life2.backoffice.servlet.UserManagementService.java
/** * Funcin que se ejecuta cuando el servlet recibe los datos *//*from ww w. j av a 2 s. c o m*/ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ChangablePropertiesManager cpm = new ChangablePropertiesManager(this.getServletContext()); String operation = request.getParameter("operation"); PlatformUserManager pum = new PlatformUserManager(); String data = ""; if (operation != null && !"".equals(operation)) { if (operation.equals("savePicturePreference")) { String photo_hor = request.getParameter("photo_hor"); cpm.saveProperty("photo_hor", photo_hor); data = "{ \"message\": \"preferences saved.\" }"; } if (operation.equals("getPicturePreference")) { String photo_hor = cpm.getProperty("photo_hor"); data = "{ \"photo_hor\": \"" + photo_hor + "\"}"; } if (operation.equals("getPlatformUser")) { String login = request.getParameter("login"); try { data = pum.getUser(login).toJSON().toString(); } catch (RemoteException re) { data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:" + re.getMessage() + ".\" }"; } catch (ServiceException se) { data = "{ \"message\": \"Could not not retrieve user with login=" + login + " Reason:" + se.getMessage() + ".\" }"; } } if (operation.equals("delPlatformUser")) { String login = request.getParameter("login"); try { if (!request.isUserInRole("admin")) throw new ServiceException("You are not allowed to delete users"); if (login != null && login.equals(request.getUserPrincipal().getName())) throw new ServiceException("You cannot delete your own user"); pum.deleteUser(login); data = "{ \"message\": \"User with login " + login + " deleted.\" }"; } catch (RemoteException re) { data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:" + re.getMessage() + ".\" }"; } catch (ServiceException se) { data = "{ \"message\": \"Could not not delete user with login=" + login + " Reason:" + se.getMessage() + ".\" }"; } } if (operation.equals("savePlatformUser")) { FileItem uploadedFile = null; PlatformUser user = null; int res = 0; byte[] foto = null; try { if (!request.isUserInRole("admin")) throw new ServiceException("You are not allowed to upadte users"); user = new PlatformUser(); user.setNew(false); ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory()); sfu.setFileSizeMax(329000); sfu.setHeaderEncoding("UTF-8"); @SuppressWarnings("unchecked") List<FileItem> items = sfu.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { if (item.getFieldName().equals("login")) user.setLogin(item.getString()); if (item.getFieldName().equals("username")) user.setLogin(item.getString()); if (item.getFieldName().equals("password")) { user.setPass(item.getString()); } if (item.getFieldName().equals("idUser")) { if (item.getString() == null || "".equals(item.getString())) user.setNew(true); } if (item.getFieldName().equals("name")) { byte[] fnb = item.get(); String text = PasswordGenerator.utf8Decoder(fnb); user.setName(text); } if (item.getFieldName().equals("email")) { String mail = item.getString(); if (MailUtils.isValidEmail(mail)) user.setEmail(mail); else throw new ServiceException("El email del usuario es incorrecto"); } if (item.getFieldName().equals("telephonenumber")) user.setTelephonenumber(item.getString()); if (item.getFieldName().equals("role")) user.setRole(Integer.parseInt(item.getString())); if (item.getFieldName().equals("language")) user.setLanguage(item.getString()); if (item.getFieldName().equals("notification_level")) user.setNotification_level(item.getString()); if (item.getFieldName().equals("promoter_id")) user.setPromoter_id(item.getString()); if (item.getFieldName().equals("user_average_mark")) user.setUser_average_mark(item.getString()); if (item.getFieldName().equals("user_votes")) user.setUser_votes(item.getString()); if (item.getFieldName().equals("latitude")) user.setHome_area_lat(item.getString()); if (item.getFieldName().equals("longitude")) user.setHome_area_lon(item.getString()); if (item.getFieldName().equals("enabled")) user.setEnabled(item.getString().equals("0") ? 0 : 1); } else { uploadedFile = item; String inputExtension = FilenameUtils .getExtension(uploadedFile.getName().toLowerCase()); if ("jpg".equals(inputExtension) || "gif".equals(inputExtension) || "png".equals(inputExtension)) { InputStream filecontent = item.getInputStream(); foto = new byte[(int) uploadedFile.getSize()]; filecontent.read(foto, 0, (int) uploadedFile.getSize()); } //else // throw new FileUploadException("Extension not supported. Only jpg,gif or png files are allowed"); } } res = pum.saveUser(user); if (foto != null) { //String v=cpm.getProperty("photo_hor"); //byte[] resizedPhoto=ImageUtil.resizeImageAsJPG(foto, (v==null || "".equals(v)) ?200:Integer.parseInt(v)); pum.uploadFoto(user.getLogin(), foto); } data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res + ") saved.\" }"; } catch (RemoteException exc) { data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:" + exc.getMessage() + ".\" }"; } catch (ServiceException exc) { data = "{ \"message\": \"Could not not save user with login=" + user.getLogin() + " Reason:" + exc.getMessage() + ".\" }"; } catch (FileUploadException exc) { data = "{ \"message\": \"User with login " + user.getLogin() + " (id=" + res + ") saved, but there was a problem uploading picture:" + exc.getMessage() + "\" }"; } } if (operation.equals("listPlatformUsers")) { JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request); try { JSONObject jsonResponse = pum.getPlatformUsersJSON(param); data = jsonResponse.toString(); } catch (RemoteException re) { data = "{ \"message\": \"Could not not retrieve platform user listing. Reason:" + re.getMessage() + ".\" }"; } catch (ServiceException se) { data = "{ \"message\": \"Could not not retrieve platform user listing. Reason:" + se.getMessage() + ".\" }"; } } } response.setContentType("application/json;charset=UTF-8"); //response.setContentType("application/json"); response.getWriter().print(data); response.getWriter().close(); }
From source file:com.ikon.servlet.admin.LanguageServlet.java
@Override @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"); boolean persist = WebUtils.getBoolean(request, "persist"); String userId = request.getRemoteUser(); Session dbSession = null;// w w w.j ava 2 s . com 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); Language lang = new Language(); 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("lg_id")) { lang.setId(item.getString("UTF-8")); } else if (item.getFieldName().equals("lg_name")) { lang.setName(item.getString("UTF-8")); } else if (item.getFieldName().equals("persist")) { persist = true; } } else { is = item.getInputStream(); data = IOUtils.toByteArray(is); lang.setImageMime(MimeTypeConfig.mimeTypes.getContentType(item.getName())); is.close(); } } if (action.equals("create")) { lang.setImageContent(SecureStore.b64Encode(data)); LanguageDAO.create(lang); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_CREATE", lang.getId(), null, lang.toString()); } else if (action.equals("edit")) { lang.setImageContent(SecureStore.b64Encode(data)); LanguageDAO.update(lang); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_EDIT", lang.getId(), null, lang.toString()); } else if (action.equals("delete")) { LanguageDAO.delete(lang.getId()); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_DELETE", lang.getId(), null, null); } else if (action.equals("import")) { dbSession = HibernateUtil.getSessionFactory().openSession(); importLanguage(userId, request, response, data, dbSession); // Activity log UserActivity.log(request.getRemoteUser(), "ADMIN_LANGUAGE_IMPORT", null, null, null); } } else if (action.equals("translate")) { translate(userId, request, response); } else if (action.equals("addTranslation")) { addTranslation(userId, request, response); } if (!action.equals("addTranslation") && (action.equals("") || action.equals("import") || persist)) { list(userId, request, response); } } catch (FileUploadException e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } catch (DatabaseException 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); } }