List of usage examples for org.apache.commons.fileupload FileItem getFieldName
String getFieldName();
From source file:kreidos.diamond.web.action.console.NewDocumentAction.java
@SuppressWarnings("rawtypes") public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL); String classId = request.getParameter("classid") != null ? request.getParameter("classid") : "0"; if (request.getMethod().equalsIgnoreCase("POST")) { try {/*from w ww .jav a 2 s.com*/ String userName = loggedInUser.getUserName(); String tempFilePath = System.getProperty("java.io.tmpdir"); if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) { tempFilePath += System.getProperty("file.separator"); } //variables String fileName = "", comments = ""; File file = null; // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING); //Create a file upload progress listener FileUploadProgressListener listener = new FileUploadProgressListener(); upload.setProgressListener(listener); //put the listener in session session.setAttribute("LISTENER", listener); session.setAttribute("UPLOAD_ERROR", null); session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0)); DocumentClass documentClass = null; Hashtable<String, String> indexRecord = new Hashtable<String, String>(); String name = ""; String value = ""; List listItems = upload.parseRequest((HttpServletRequest) request); Iterator iter = listItems.iterator(); FileItem fileItem = null; while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { name = fileItem.getFieldName(); value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals("classid")) { classId = value; } if (name.equals("txtNote")) { comments = value; } } else { try { fileName = fileItem.getName(); file = new File(fileName); fileName = file.getName(); file = new File(tempFilePath + fileName); fileItem.write(file); } catch (Exception ex) { session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage()); return null; } } } //if if (file.length() <= 0) { //code for checking minimum size of file session.setAttribute("UPLOAD_ERROR", "Zero length document"); return null; } documentClass = DocumentClassDAO.getInstance().readDocumentClassById(Integer.parseInt(classId)); if (documentClass == null) { session.setAttribute("UPLOAD_ERROR", "Invalid document class"); return null; } AccessControlManager aclManager = new AccessControlManager(); ACL acl = aclManager.getACL(documentClass, loggedInUser); if (!acl.canCreate()) { session.setAttribute("UPLOAD_ERROR", "Access Denied"); return null; } String indexValue = ""; String indexName = ""; session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(50)); for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) { indexName = indexDefinition.getIndexColumnName(); Iterator iter1 = listItems.iterator(); while (iter1.hasNext()) { FileItem item1 = (FileItem) iter1.next(); if (item1.isFormField()) { name = item1.getFieldName(); value = item1.getString(HTTPConstants.CHARACTER_ENCODING); if (name.equals(indexName)) { indexValue = value; String errorMessage = ""; if (indexValue != null) { if (indexDefinition.isMandatory()) { if (indexValue.trim().length() <= 0) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } if (IndexDefinition.INDEXTYPE_NUMBER .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.matchRegexp(indexValue, HTTPConstants.NUMERIC_REGEXP)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } } else if (IndexDefinition.INDEXTYPE_DATE .equalsIgnoreCase(indexDefinition.getIndexType())) { if (indexValue.trim().length() > 0) { if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) { errorMessage = "Invalid input for " + indexDefinition.getIndexDisplayName(); session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } } if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking index field length errorMessage = "Document index size exceeded for " + "Index Name : " + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : " + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : " + indexValue.length() + " ]"; session.setAttribute("UPLOAD_ERROR", errorMessage); return null; } } indexRecord.put(indexName, indexValue); } } } //while iter } //while indexCfgList session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(70)); DocumentRevision documentRevision = new DocumentRevision(); documentRevision.setClassId(documentClass.getClassId()); documentRevision.setDocumentId(0); documentRevision.setRevisionId("1.0"); documentRevision.setDocumentFile(file); documentRevision.setUserName(loggedInUser.getUserName()); documentRevision.setIndexRecord(indexRecord); documentRevision.setComments(comments); DocumentManager documentManager = new DocumentManager(); documentManager.storeDocument(documentRevision, documentClass); //Log the entry to audit logs AuditLogManager.log(new AuditLogRecord(documentRevision.getDocumentId(), AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CREATED, userName, request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Document created")); session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(100)); } catch (Exception e) { e.printStackTrace(System.out); } return null; } else { try { ArrayList<DocumentClass> availableDocumentClasses = DocumentClassDAO.getInstance() .readDocumentClasses(" ACTIVE = 'Y'"); ArrayList<DocumentClass> documentClasses = new ArrayList<DocumentClass>(); AccessControlManager aclManager = new AccessControlManager(); for (DocumentClass documentClass : availableDocumentClasses) { ACL acl = aclManager.getACL(documentClass, loggedInUser); if (acl.canCreate()) { documentClasses.add(documentClass); } } int documentClassId = 0; try { documentClassId = Integer.parseInt(classId); } catch (Exception ex) { request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input"); return (new NewDocumentView(request, response)); } if (documentClassId > 0) { DocumentClass selectedDocumentClass = DocumentClassDAO.getInstance() .readDocumentClassById(documentClassId); request.setAttribute("DOCUMENTCLASS", selectedDocumentClass); } request.setAttribute("CLASSID", documentClassId); request.setAttribute("CLASSLIST", documentClasses); } catch (Exception ex) { ex.printStackTrace(); } } return (new NewDocumentView(request, response)); }
From source file:gov.nist.appvet.tool.synchtest.Service.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get received HTTP parameters and file upload FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null;//from w ww . j a va2s .com FileItem fileItem = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } // Get received items Iterator iter = items.iterator(); FileItem item = null; while (iter.hasNext()) { item = (FileItem) iter.next(); if (item.isFormField()) { // Get HTML form parameters String incomingParameter = item.getFieldName(); String incomingValue = item.getString(); if (incomingParameter.equals("appid")) { appId = incomingValue; log.info("Received app ID: " + appId); } /** CHANGE (START): Get other tools-specific form parameters **/ /** CHANGE (END): Get other tools-specific form parameters **/ } else { // item should now hold the received file if (item != null) { fileItem = item; log.info("Received file: " + fileItem.getName()); } } } if (appId == null) { // All tool services require an AppVet app ID log.error("Received null app ID. Returning HTTP 400"); HttpUtil.sendHttp400(response, "No app ID specified"); return; } if (fileItem != null) { // Get app file fileName = FileUtil.getFileName(fileItem.getName()); if (!fileName.endsWith(".apk")) { log.error("Received invalid app file. Returning HTTP 400"); HttpUtil.sendHttp400(response, "Invalid app file: " + fileItem.getName()); return; } // Create app directory appDirPath = Properties.TEMP_DIR + "/" + appId; File appDir = new File(appDirPath); if (!appDir.exists()) { appDir.mkdir(); } // Create report path reportFilePath = Properties.TEMP_DIR + "/" + appId + "/" + reportName + "." + Properties.reportFormat.toLowerCase(); appFilePath = Properties.TEMP_DIR + "/" + appId + "/" + fileName; log.debug("App file path: " + appFilePath); if (!FileUtil.saveFileUpload(fileItem, appFilePath)) { log.error("Could not save file. Returning HTTP 500"); HttpUtil.sendHttp500(response, "Could not save uploaded file"); return; } log.debug("Saved app file"); } else { HttpUtil.sendHttp400(response, "No app was received."); return; } // Use if reading command from ToolProperties.xml. Otherwise, // comment-out if using custom command (called by customExecute()) //command = getCommand(); /* * CHANGE: Select either execute() to execute a native OS command or * customExecute() to execute your own custom code. Make sure that the * unused method call is commented-out. */ reportBuffer = new StringBuffer(); boolean succeeded = customExecute(reportBuffer); if (!succeeded) { log.error("Error detected: " + reportBuffer.toString()); String errorReport = ReportUtil.getHtmlReport(response, fileName, ToolStatus.ERROR, reportBuffer.toString()); // Send report to AppVet if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) { // Send back ASCII in HTTP Response ReportUtil.sendInHttpResponse(response, errorReport, ToolStatus.ERROR); } return; } // Analyze report and generate tool status log.info("Analyzing report for " + appFilePath); // ToolStatus risk = ReportUtil.analyzeReport(reportBuffer // .toString()); ToolStatus risk = ToolStatus.LOW; // Just set to LOW for testing log.info("Result: " + risk.name()); String reportContent = null; // Get report if (Properties.reportFormat.equals(ReportFormat.HTML.name())) { reportContent = ReportUtil.getHtmlReport(response, fileName, risk, reportBuffer.toString()); } // else if (Properties.reportFormat.equals(ReportFormat.TXT.name())) { // reportContent = getTxtReport(); // } else if (Properties.reportFormat.equals(ReportFormat.PDF.name())) { // reportContent = getPdfReport(); // } else if (Properties.reportFormat.equals(ReportFormat.JSON.name())) { // reportContent = getJsonReport(); // } // If report is null or empty, stop processing if (reportContent == null || reportContent.isEmpty()) { log.error("Tool report is null or empty"); return; } else { log.info("Report generated"); } // Send report to AppVet if (Properties.protocol.equals(Protocol.SYNCHRONOUS.name())) { // Send back ASCII in HTTP Response ReportUtil.sendPDFInHttpResponse(response, reportContent, risk); } // Clean up if (!Properties.keepApps) { if (FileUtil.deleteDirectory(new File(appDirPath))) { log.debug("Deleted " + appFilePath); } else { log.error("Could not delete " + appFilePath); } } log.info("Done processing app " + appId); reportBuffer = null; System.gc(); }
From source file:it.swim.servlet.RegistrazioneServlet.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response)// www . jav a 2 s. c om */ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<FileItem> items; Blob blob = null; String email = new String(); String password = new String(); String nome = new String(); String cognome = new String(); List<Abilita> abilitaPersonaliRegistrazione = new ArrayList<Abilita>(); //nel caso ci siano errori e devo tornare alla stessa jsp, preparo subito la lista delle abilita' da rivisualizzare // Ottengo abilita dall'insieme generale e le metto nella request List<Abilita> abilitaInsiemeGenerale = ricerche.insiemeAbilitaGenerali(); request.setAttribute("abilita", abilitaInsiemeGenerale); try { items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input // type="text|radio|checkbox|etc", select, etc). // ... (do your job here) if (item.getFieldName().equals("emailUtente")) { //ottengo il valore del form field email = item.getString(); } if (item.getFieldName().equals("password")) { password = item.getString(); } if (item.getFieldName().equals("nome")) { nome = item.getString(); } if (item.getFieldName().equals("cognome")) { cognome = item.getString(); } if (item.getFieldName().equals("abilita")) { abilitaPersonaliRegistrazione.add(registrazione.getAbilitaByNome(item.getString())); } } else { //non cancellare questi commenti, potranno tornare utili // Process form file field (input type="file"). // String fieldname = item.getFieldName(); // String filename = item.getName(); // InputStream filecontent = item.getInputStream(); try { blob = ConvertitoreFotoInBlob.getBlobFromFileItem(item, LUNGHEZZA, ALTEZZA, DIMMB); } catch (FotoException e) { try { if (e.getCausa().equals(FotoException.Causa.FILETROPPOGRANDE)) { blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage(); request.setAttribute("erroreFileTroppoGrande", "Errore, file troppo grande! E' stata impostata la foto di profilo predefinita"); } else { if (e.getCausa().equals(FotoException.Causa.NONRICONOSCIUTACOMEFOTO)) { blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage(); request.setAttribute("erroreNonFoto", "Errore, foto non riconosciuta! E' stata impostata la foto di profilo predefinita"); } } //in questo caso uploada una foto predefinita blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage(); request.setAttribute("erroreFotoSconosciuto", "Errore durante il caricamento della foto! E' stata impostata la foto di profilo predefinita"); } catch (FotoException e1) { request.setAttribute("erroreFotoSconosciuto", "Errore durante il caricamento della foto! E' stata impostata la foto di profilo predefinita"); } } } } log.debug("email: " + email); log.debug("password: " + password); log.debug("nome: " + nome); log.debug("cognome: " + cognome); log.debug("Lista abilita passate in registrazione: " + Arrays.toString(abilitaPersonaliRegistrazione.toArray())); if (blob == null) { try { blob = ConvertitoreFotoInBlob.getBlobFromDefaultImage(); } catch (FotoException e) { request.setAttribute("erroreFotoPredefinita", "Errore durante il caricamento della foto predefinita. Nessun file caricato!"); } } } catch (FileUploadException e) { log.error(e.getMessage(), e); request.setAttribute("erroreFotoIrreversibile", "Errore durante il caricamento della foto! Non e' stata impostata nessuna foto di profilo"); } catch (SerialException e) { log.error(e.getMessage(), e); request.setAttribute("erroreFotoIrreversibile", "Errore durante il caricamento della foto! Non e' stata impostata nessuna foto di profilo"); } catch (SQLException e) { log.error(e.getMessage(), e); request.setAttribute("erroreFotoIrreversibile", "Errore durante il caricamento della foto! Non e' stata impostata nessuna foto di profilo"); } Utente utenteRegistrato; try { utenteRegistrato = registrazione.registrazioneUtente(email, password, nome, cognome, blob, abilitaPersonaliRegistrazione); log.debug("utenteRegistrato: " + utenteRegistrato); if (utenteRegistrato != null) { log.debug("Registrazione avvenuta correttamente registrazione"); request.getSession().setAttribute("utenteCollegato", email); request.getSession().setAttribute("nomeUtenteCollegato", utenteRegistrato.getNome()); request.getSession().setAttribute("cognomeUtenteCollegato", utenteRegistrato.getCognome()); request.setAttribute("abilita", abilitaPersonaliRegistrazione); request.setAttribute("punteggioUtenteCollegato", "Non disponibile"); getServletConfig().getServletContext().getRequestDispatcher("/jsp/utenti/profilo/profilo.jsp") .forward(request, response); } else { log.debug("Errore registrazione"); request.setAttribute("erroreRegistrazione", "Errore durante la registrazione"); getServletConfig().getServletContext().getRequestDispatcher("/jsp/visitatore/registrazione.jsp") .forward(request, response); } } catch (HashingException e) { log.error(e.getMessage(), e); request.setAttribute("erroreHashing", "Errore hashing durante la registrazione"); getServletConfig().getServletContext().getRequestDispatcher("/jsp/visitatore/registrazione.jsp") .forward(request, response); } catch (RegistrazioneException e) { log.error(e.getMessage(), e); if (e.getCausa() == RegistrazioneException.Causa.EMAILGIAUTILIZZATA) { request.setAttribute("erroreEmailGiaUsata", "Errore! Indirizzo email gia' in uso"); } if (e.getCausa() == RegistrazioneException.Causa.SINTASSIEMAILNONCORRETTA) { request.setAttribute("erroreSintassiEmailNonCorretta", "Errore! Inserisci un'email valida"); } if (e.getCausa() == RegistrazioneException.Causa.ALCUNIPARAMETRINULLIOVUOTI) { request.setAttribute("erroreParametriNulliOVuoti", "Errore! Devi completare tutti i campi obbligatori"); } if (e.getCausa() == RegistrazioneException.Causa.ERRORESCONOSCIUTO) { request.setAttribute("erroreSconosciutoRegistrazione", "Errore sconosciuto durante la registrazione"); } getServletConfig().getServletContext().getRequestDispatcher("/jsp/visitatore/registrazione.jsp") .forward(request, response); } }
From source file:com.openkm.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);/* ww w . ja v a 2 s . c om*/ 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 (Exception e) { log.error(e.getMessage(), e); sendErrorRedirect(request, response, e); } }
From source file:Control.HandleAddFoodMenu.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.// w w w . j ava 2 s . c om * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); HttpSession session = request.getSession(); Food temp = new Food(); try (PrintWriter out = response.getWriter()) { LinkedList<String> names = new LinkedList<>(); /* TODO output your page here. You may use following sample code. */ String path = getClass().getResource("/").getPath(); String[] tempS = null; if (Paths.path == null) { File file = new File(path + "test.html"); path = file.getParent(); File file1 = new File(path + "test1.html"); path = file1.getParent(); File file2 = new File(path + "test1.html"); path = file2.getParent(); Paths.path = path; } else { path = Paths.path; } path = Paths.tempPath; String name; String sepName = Tools.CurrentTime(); if (ServletFileUpload.isMultipartContent(request)) { List<?> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); Iterator iter = multiparts.iterator(); int index = 0; tempS = new String[multiparts.size() - 1]; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { name = new File(item.getName()).getName(); names.add(name); String FilePath = path + Paths.foodImagePath + sepName + name; item.write(new File(FilePath)); } else { String test = item.getFieldName(); tempS[index++] = item.getString(); } } index = 0; temp.categoryid = Integer.parseInt(tempS[index++]); temp.ID = tempS[index++]; temp.name = tempS[index++]; temp.price = Double.parseDouble(tempS[index++]); temp.pieces = Integer.parseInt(tempS[index++]); temp.description = tempS[index++]; temp.restid = Integer.parseInt(tempS[index++]); temp.resID = tempS[index++]; temp.rename = tempS[index++]; } if (Food.checkExisted(temp.ID, temp.name)) { response.sendRedirect("./Admin/AddMenu.jsp?index=1" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } else { if (Food.addNewFood(temp)) { int id = Food.getFoodID(temp.ID); boolean flag = true; for (String s : names) { if (Image.addImage(s, Paths.foodImagePathStore + sepName + s, id)) { } else { flag = false; break; } } if (flag) { response.sendRedirect("./Admin/AddMenu.jsp?index=2" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } else { response.sendRedirect("./Admin/AddMenu.jsp?index=4" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } } else { response.sendRedirect("./Admin/AddMenu.jsp?index=3" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } } } catch (Exception e) { response.sendRedirect("./Admin/AddMenu.jsp?index=0" + "&id=" + temp.restid + "&restid=" + temp.resID + "&name=" + temp.rename); } }
From source file:controller.SignUpController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww . jav a2 s. com*/ * @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 { CreditDao creditDao = new CreditDaoImpl(); try { boolean creditExist = false; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> it = items.iterator(); HttpSession session = request.getSession(false); User user = new User(); Credit credit = new Credit(); UserDao userDaoImpl = new UserDaoImpl(); ArrayList<String> newInterests = new ArrayList<>(); while (it.hasNext()) { FileItem item = it.next(); if (!item.isFormField()) { byte[] image = item.get(); if (image != null && image.length != 0) { user.setImage(image); } System.out.println(user.getImage()); } else { switch (item.getFieldName()) { case "name": user.setUserName(item.getString()); break; case "mail": user.setEmail(item.getString()); break; case "password": user.setPassword(item.getString()); break; case "job": user.setJob(item.getString()); break; case "date": DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate date = LocalDate.parse(item.getString(), formatter); user.setDOB(date); break; case "address": user.setAddress(item.getString()); break; case "credit": user.setCreditNumber(item.getString()); credit.setNumber(item.getString()); if (creditDao.checkCredit(credit)) {//credit number is exist is if (!(userDaoImpl.isCreditNumberAssigned(credit))) { creditExist = true; System.out.println("creditExist = true;"); } else { creditExist = false; System.out.println("creditExist = falsefalse;"); } } else { creditExist = false; System.out.println("creditExist=false;"); } break; default: newInterests.add(item.getString()); System.out.println(item.getFieldName() + " : " + item.getString()); } } } // check if user exist in Db if (creditExist) { user.setInterests(newInterests); UserDaoImpl userDao = new UserDaoImpl(); // userDao.signUp(user); session.setAttribute("user", user); System.out.println(user.getInterests()); System.out.println(user.getImage()); response.sendRedirect("index.jsp"); } else { response.sendRedirect("sign_up.jsp"); System.out.println("user didnt saved"); } } catch (FileUploadException ex) { Logger.getLogger(SignUpController.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:hu.ptemik.gallery.servlets.UploadServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); User user = (User) session.getAttribute("user"); String uploadFolder = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY; if (ServletFileUpload.isMultipartContent(request) && user != null) { try {//from www . j a v a 2s .c o m List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); Picture pic = new Picture(); File uploadedFile = null; for (FileItem item : multiparts) { if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); String filePath = uploadFolder + File.separator + fileName; String relativePath = UPLOAD_DIRECTORY + "/" + fileName; uploadedFile = new File(filePath); item.write(uploadedFile); pic.setUrl(relativePath); } else { if (item.getFieldName().equals("title")) { pic.setTitle(item.getString()); } else if (item.getFieldName().equals("description")) { pic.setDescription(item.getString()); } } } if (Controller.newPicture(pic, user)) { request.setAttribute("successMessage", "A fjl feltltse sikerlt!"); } else { FileUtils.deleteQuietly(uploadedFile); throw new Exception(); } } catch (FileNotFoundException ex) { request.setAttribute("errorMessage", "Hinyzik a fjl!"); } catch (Exception ex) { request.setAttribute("errorMessage", "Hiba a fjl feltltse sorn!"); } } else { request.setAttribute("errorMessage", "Form hiba"); } request.getRequestDispatcher("upload.jsp").forward(request, response); }
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;// ww w .jav a2s . 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:gov.nist.appvet.tool.AsynchronousService.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List items = null;//from ww w . java 2 s .c o m FileItem fileItem = null; String appId = null; try { items = upload.parseRequest(request); } catch (FileUploadException e) { e.printStackTrace(); } // Get form fields Iterator iter = items.iterator(); FileItem item = null; while (iter.hasNext()) { item = (FileItem) iter.next(); if (item.isFormField()) { String incomingParameter = item.getFieldName(); String incomingValue = item.getString(); if (incomingParameter.equals("appid")) { appId = incomingValue; } log.debug("Received: " + incomingParameter + " = " + incomingValue); } else { // item should now hold the received file if (item != null) { fileItem = item; } } } // If app ID and file were received, send back HTTP 202 now if (appId != null && fileItem != null) { sendHttp202(response, "Received app " + appId + " for processing."); } else { sendHttp400(response, "Did not receive proper request."); return; } String appFilePath = null; String reportPath = null; String fileName = null; if (item != null) { fileName = getFileName(fileItem.getName()); if (!fileName.endsWith(".apk")) { sendHttp400(response, "Invalid app file: " + fileItem.getName()); return; } appFilePath = Properties.TEMP_DIR + "/" + appId + fileName; reportPath = Properties.TEMP_DIR + "/" + appId + "_report.txt"; log.debug("appFilePath: " + appFilePath); if (!saveFileUpload(fileItem, appFilePath)) { sendHttp500(response, "Could not save uploaded file"); return; } } else { log.error("File item was null."); return; } // Test app AndroidVulnerabilityScanner vulnerabilityScanner = new AndroidVulnerabilityScanner(appFilePath); boolean masterKeyFound = vulnerabilityScanner.hasMasterKey(); boolean extraFieldFound = vulnerabilityScanner.hasExtraField(); vulnerabilityScanner.close(); // Generate report String htmlReport = null; ToolStatus reportStatus = null; if (masterKeyFound) { reportStatus = ToolStatus.FAIL; htmlReport = generateReport(fileName, reportStatus, "Master Key vulnerability detected."); } if (extraFieldFound) { reportStatus = ToolStatus.FAIL; htmlReport = generateReport(fileName, reportStatus, "Extra Field vulnerability detected."); } if (!masterKeyFound && !extraFieldFound) { reportStatus = ToolStatus.PASS; htmlReport = generateReport(fileName, reportStatus, "No Master Key or Extra Field vulnerablity detected."); } // Write report file PrintWriter out = new PrintWriter(reportPath); out.write(htmlReport); out.close(); // Now send report sendReport(appId, reportStatus.name(), reportPath); boolean deleted = deleteFile(appFilePath); if (deleted) { log.debug("Deleted app " + appFilePath); } else { log.error("Could not delete app file " + appFilePath); } deleted = deleteFile(reportPath); if (deleted) { log.debug("Deleted report " + reportPath); } else { log.error("Could not delete report file " + reportPath); } // Clean up System.gc(); }