List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:fr.paris.lutece.plugins.plu.web.PluJspBean.java
/** * Generates a message of confirmation for modify a folder * @param request the Http request//from w w w . j av a 2 s. c o m * @parma correct true if the modification is a correction, false if the plu * is in "work" state * @return message */ public String getConfirmModifyFolder(HttpServletRequest request, boolean correct) { if (request.getParameter(PARAMETER_FOLDER_TITLE).equals("") || (correct && request.getParameter(PARAMETER_HISTORY_DESCRIPTION).equals(""))) { if (correct) { return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_REQUIRED_FIELD, AdminMessage.TYPE_STOP); } else { return this.getMessageJsp(request, MESSAGE_ERROR_REQUIRED_FIELD, null, "jsp/admin/plugins/plu/folder/ModifyFolder.jsp", null); } } int nIdPlu = Integer.parseInt(request.getParameter(PARAMETER_PLU_ID)); String folderTitle = request.getParameter(PARAMETER_FOLDER_TITLE); int nIdFolder = Integer.parseInt(request.getParameter(PARAMETER_FOLDER_ID)); Folder folder = _folderServices.findByPrimaryKey(nIdFolder); UrlItem url = new UrlItem(JSP_DO_MODIFY_FOLDER); url.addParameter(PARAMETER_PLU_ID, nIdPlu); try { url.addParameter(PARAMETER_FOLDER_ID, URIUtil.encodeAll(request.getParameter(PARAMETER_FOLDER_ID))); url.addParameter(PARAMETER_FOLDER_PARENT_ID, URIUtil.encodeAll(request.getParameter(PARAMETER_FOLDER_PARENT_ID))); url.addParameter(PARAMETER_FOLDER_TITLE, URIUtil.encodeAll(folderTitle)); if (correct) { url.addParameter(PARAMETER_HISTORY_DESCRIPTION, URIUtil.encodeAll(request.getParameter(PARAMETER_HISTORY_DESCRIPTION))); } } catch (URIException e) { throw new AppException("An error occured while parsing request parameters"); } // save description into session because it's too large for url request.getSession().setAttribute(PARAMETER_FOLDER_DESCRIPTION, request.getParameter(PARAMETER_FOLDER_DESCRIPTION)); if (request.getParameterValues(PARAMETER_FOLDER_IMAGE_CHECK) != null) { String[] check = request.getParameterValues(PARAMETER_FOLDER_IMAGE_CHECK); for (int j = 0; j < check.length; ++j) { url.addParameter(PARAMETER_FOLDER_IMAGE_CHECK, check[j]); } } if (request.getParameterValues(PARAMETER_FOLDER_HTML_CHECK) != null) { String[] check = request.getParameterValues(PARAMETER_FOLDER_HTML_CHECK); for (int j = 0; j < check.length; ++j) { url.addParameter(PARAMETER_FOLDER_HTML_CHECK, check[j]); } } if (request.getParameterValues(PARAMETER_FOLDER_HTML_CHECK_IMPRESSION) != null) { String[] check = request.getParameterValues(PARAMETER_FOLDER_HTML_CHECK_IMPRESSION); for (int j = 0; j < check.length; ++j) { url.addParameter(PARAMETER_FOLDER_HTML_CHECK_IMPRESSION, check[j]); } } Object[] args = { folderTitle }; if ((folder != null) && !folder.getTitle().equals(request.getParameter(PARAMETER_FOLDER_TITLE_OLD))) { return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_FOLDER_CREATE, args, AdminMessage.TYPE_STOP); } if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile(PARAMETER_FOLDER_IMAGE); if (fileItem.getSize() > 0) { String name = fileItem.getName(); String type = name.substring(name.lastIndexOf(".")); if (!type.equalsIgnoreCase(".jpg") && !type.equalsIgnoreCase(".png") && !type.equalsIgnoreCase(".gif")) { return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_FOLDER_IMAGE_TYPE, args, AdminMessage.TYPE_STOP); } PhysicalFile physicalFile = new PhysicalFile(); physicalFile.setValue(fileItem.get()); _folderImage.setImg(physicalFile.getValue()); _folderImage.setNomImage(fileItem.getName()); } } return AdminMessageService.getMessageUrl(request, correct ? MESSAGE_CONFIRM_CORRECT_FOLDER : MESSAGE_CONFIRM_MODIFY_FOLDER, args, url.getUrl(), AdminMessage.TYPE_CONFIRMATION); }
From source file:fr.paris.lutece.plugins.plu.web.PluJspBean.java
/** * Generates a HTML form for create a new folder * @param request the Http request/*w ww . j av a2 s . c om*/ * @return HTML */ public String getCreateFolder(HttpServletRequest request) { //Clean _listFile this.reinitListFile(request); setPageTitleProperty(PROPERTY_PAGE_TITLE_CREATE_FOLDER); Plu plu = _pluServices.findPluWork(); if (plu.getId() == 0) { // FIXME renvoie l'url au lieu du message d'erreur return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_PLU_WORK, AdminMessage.TYPE_STOP); } FolderFilter folderFilter = new FolderFilter(); folderFilter.setPlu(plu.getId()); List<Folder> folderList = _folderServices.findByFilter(folderFilter); Map<String, Object> model = new HashMap<String, Object>(); model.put(MARK_PLU, plu); model.put(MARK_LIST_FOLDER_LIST, folderList); model.put(MARK_WEBAPP_URL, AppPathService.getBaseUrl(request)); model.put(MARK_LOCALE, getLocale()); model.put(PARAMETER_FOLDER_PARENT_ID, request.getParameter(PARAMETER_FOLDER_PARENT_ID)); model.put(PARAMETER_FOLDER_TITLE, request.getParameter(PARAMETER_FOLDER_TITLE)); model.put(PARAMETER_FOLDER_IMAGE, request.getParameter(PARAMETER_FOLDER_IMAGE)); model.put(PARAMETER_FOLDER_DESCRIPTION, request.getParameter(PARAMETER_FOLDER_DESCRIPTION)); if (request.getParameter(PARAMETER_FOLDER_ID) != null && request.getParameter(PARAMETER_FOLDER_HTML_NOT_EMPTY) != null && request.getParameter(PARAMETER_FOLDER_HTML_NOT_EMPTY).equals("true") && !request.getParameter(PARAMETER_FOLDER_ID).equals("0")) { String utilisation = ""; if (request.getParameter(PARAMETER_FOLDER_HTML_UTILISATION) != null) { utilisation = request.getParameter(PARAMETER_FOLDER_HTML_UTILISATION); } if (request.getParameter(PARAMETER_FOLDER_ID_DUPLICATE) != null) { int idFolder = Integer.parseInt(request.getParameter(PARAMETER_FOLDER_ID_DUPLICATE)); Folder folderDuplicate = _folderServices.findByPrimaryKey(idFolder); if (folderDuplicate != null) { if (utilisation.equals("C")) { _folderHtml.setHtml(folderDuplicate.getHtml()); } else if (utilisation.equals("I")) { _folderHtml.setHtmlImpression(folderDuplicate.getHtmlImpression()); } else { _folderHtml.setHtml(folderDuplicate.getHtml()); _folderHtml.setHtmlImpression(folderDuplicate.getHtmlImpression()); } } } else { if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile(PARAMETER_FOLDER_HTML); if (fileItem != null && fileItem.getSize() != 0) { if (utilisation.equals("C")) { _folderHtml.setHtml(fileItem.getString()); } else if (utilisation.equals("I")) { _folderHtml.setHtmlImpression(fileItem.getString()); } } } else { if (StringUtils.isNotEmpty(request.getParameter(PARAMETER_FOLDER_HTML))) { String strHtml = request.getParameter(PARAMETER_FOLDER_HTML); if (utilisation.equals("C")) { _folderHtml.setHtml(strHtml); } else if (utilisation.equals("I")) { _folderHtml.setHtmlImpression(strHtml); } } } } } if (StringUtils.isNotEmpty(_folderHtml.getHtml())) { model.put(MARK_HTML, 1); } if (StringUtils.isNotEmpty(_folderHtml.getHtmlImpression())) { model.put(MARK_HTML_IMPRESSION, 1); } HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_CREATE_FOLDER, getLocale(), model); return getAdminPage(template.getHtml()); }
From source file:fr.paris.lutece.plugins.plu.web.PluJspBean.java
/** * Generates a HTML form for modify or correct a folder * @param request the Http request//from w w w. j a v a 2 s . co m * @param correct true if it's a correction (archive state), false if it's a * modification (work state) * @return HTML */ private String getHTMLModifyOrCorrectFolder(HttpServletRequest request, boolean correct) { //Clean _listFile this.reinitListFile(request); setPageTitleProperty(correct ? PROPERTY_PAGE_TITLE_CORRECT_FOLDER : PROPERTY_PAGE_TITLE_MODIFY_FOLDER); int nIdPlu = Integer.parseInt(request.getParameter(PARAMETER_PLU_ID)); Plu plu = _pluServices.findByPrimaryKey(nIdPlu); int nIdFolder = 0; if (!correct && StringUtils.isNotEmpty(request.getParameter(PARAMETER_FOLDER_ID_RETURN))) { nIdFolder = Integer.parseInt(request.getParameter(PARAMETER_FOLDER_ID_RETURN)); } else { nIdFolder = Integer.parseInt(request.getParameter(PARAMETER_FOLDER_ID)); } Folder folder = _folderServices.findByPrimaryKey(nIdFolder); Folder folderParent = _folderServices.findByPrimaryKey(folder.getParentFolder()); if (!correct && folderParent == null) { folderParent = new Folder(); } FolderFilter folderFilter = new FolderFilter(); folderFilter.setPlu(plu.getId()); List<Folder> folderList = _folderServices.findByFilter(folderFilter); if (!correct) { if (request.getParameter(PARAMETER_FOLDER_PARENT_ID) != null) { folderParent.setId(Integer.parseInt(request.getParameter(PARAMETER_FOLDER_PARENT_ID))); } if (request.getParameter(PARAMETER_FOLDER_TITLE) != null) { folder.setTitle(request.getParameter(PARAMETER_FOLDER_TITLE)); } if (request.getParameter(PARAMETER_FOLDER_IMAGE) != null) { folder.setImg(request.getParameter(PARAMETER_FOLDER_IMAGE).getBytes()); } if (request.getParameter(PARAMETER_FOLDER_DESCRIPTION) != null) { folder.setDescription(request.getParameter(PARAMETER_FOLDER_DESCRIPTION)); } } Map<String, Object> model = new HashMap<String, Object>(); model.put(MARK_PLU, plu); model.put(MARK_FOLDER, folder); model.put(MARK_FOLDER_PARENT, folderParent); model.put(MARK_LIST_FOLDER_LIST, folderList); model.put(MARK_WEBAPP_URL, AppPathService.getBaseUrl(request)); model.put(MARK_LOCALE, getLocale()); String utilisation = ""; if (request.getParameter(PARAMETER_FOLDER_HTML_UTILISATION) != null) { utilisation = request.getParameter(PARAMETER_FOLDER_HTML_UTILISATION); } if (request.getParameter(PARAMETER_FOLDER_HTML_NOT_EMPTY) != null && request.getParameter(PARAMETER_FOLDER_HTML_NOT_EMPTY).equals("true")) { if (request.getParameter(PARAMETER_FOLDER_HTML) != null) { String strHtml = request.getParameter(PARAMETER_FOLDER_HTML); if (utilisation.equals("C")) { _folderHtml.setHtml(strHtml); } else if (utilisation.equals("I")) { _folderHtml.setHtmlImpression(strHtml); } } else if (request.getParameter(PARAMETER_FOLDER_ID_DUPLICATE) != null) { int idFolder = Integer.parseInt(request.getParameter(PARAMETER_FOLDER_ID_DUPLICATE)); Folder folderDuplicate = _folderServices.findByPrimaryKey(idFolder); if (folderDuplicate != null) { if (utilisation.equals("C")) { _folderHtml.setHtml(folderDuplicate.getHtml()); } else if (utilisation.equals("I")) { _folderHtml.setHtmlImpression(folderDuplicate.getHtmlImpression()); } else { _folderHtml.setHtml(folderDuplicate.getHtml()); _folderHtml.setHtmlImpression(folderDuplicate.getHtmlImpression()); } } } else if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; FileItem fileItem = multipartRequest.getFile(PARAMETER_FOLDER_HTML); if (fileItem != null && fileItem.getSize() != 0) { if (utilisation.equals("C")) { _folderHtml.setHtml(fileItem.getString()); } else if (utilisation.equals("I")) { _folderHtml.setHtmlImpression(fileItem.getString()); } } } } else { if (_folderHtml.getHtml() == null && _folderHtml.getHtmlImpression() == null) { _folderHtml.setHtml(folder.getHtml()); _folderHtml.setHtmlImpression(folder.getHtmlImpression()); } } if (StringUtils.isNotEmpty(_folderHtml.getHtml())) { model.put(MARK_HTML, 1); } if (StringUtils.isNotEmpty(_folderHtml.getHtmlImpression())) { model.put(MARK_HTML_IMPRESSION, 1); } HtmlTemplate template = AppTemplateService .getTemplate(correct ? TEMPLATE_CORRECT_FOLDER : TEMPLATE_MODIFY_FOLDER, getLocale(), model); return getAdminPage(template.getHtml()); }
From source file:dk.clarin.tools.create.java
public String getParmsAndFiles(List<FileItem> items, HttpServletResponse response, PrintWriter out) throws ServletException { if (!BracMat.loaded()) { response.setStatus(500);/*from w w w . j a v a2 s.co m*/ throw new ServletException("Bracmat is not loaded. Reason:" + BracMat.reason()); } String arg = "(method.POST) (DATE." + workflow.quote(date) + ")"; // bj 20120801 "(action.POST)"; try { /* * Parse the request */ Iterator<FileItem> itr = items.iterator(); while (itr.hasNext()) { logger.debug("in loop"); FileItem item = itr.next(); /* * Handle Form Fields. */ if (item.isFormField()) { logger.debug("Field Name = " + item.getFieldName() + ", String = " + item.getString()); if (item.getFieldName().equals("text")) { String LocalFileName = BracMat .Eval("storeUpload$(" + workflow.quote("text") + "." + workflow.quote(date) + ")"); int textLength = item.getString().length(); File file = new File(destinationDir, LocalFileName); item.write(file); arg = arg + " (FieldName," + workflow.quote("text") + ".Name," + workflow.quote("text") + ".ContentType," + workflow.quote("text/plain") + ".Size," + Long.toString(textLength) + ".DestinationDir," + workflow.quote( ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*//*DESTINATION_DIR_PATH*/) + ".LocalFileName," + workflow.quote(LocalFileName) + ")"; } else arg = arg + " (" + workflow.quote(item.getFieldName()) + "." + workflow.quote(item.getString()) + ")"; } else if (item.getName() != "") { //Handle Uploaded files. String LocalFileName = BracMat.Eval( "storeUpload$(" + workflow.quote(item.getName()) + "." + workflow.quote(date) + ")"); /* * Write file to the ultimate location. */ File file = new File(destinationDir, LocalFileName); item.write(file); String ContentType = item.getContentType(); logger.debug("hasNoPDFfonts ?"); logger.debug("ContentType :" + ContentType); boolean hasNoPDFfonts = false; if (ContentType.equals("application/pdf") || ContentType.equals("application/x-download") || ContentType.equals("application/octet-stream")) { logger.debug("calling PDFhasNoFonts"); hasNoPDFfonts = PDFhasNoFonts(file); logger.debug("hasNoPDFfonts " + (hasNoPDFfonts ? "true" : "false")); } arg = arg + " (FieldName," + workflow.quote(item.getFieldName()) + ".Name," + workflow.quote(item.getName()) + ".ContentType," + workflow.quote(item.getContentType()) + (hasNoPDFfonts ? " true" : "") + ".Size," + Long.toString(item.getSize()) + ".DestinationDir," + workflow.quote( ToolsProperties.documentRoot /*+ ToolsProperties.stagingArea*//*DESTINATION_DIR_PATH*/) + ".LocalFileName," + workflow.quote(LocalFileName) + ")"; } } } catch (Exception ex) { log("Error encountered while uploading file", ex); out.close(); } logger.debug("arg " + arg); return arg; }
From source file:com.stratelia.webactiv.survey.control.SurveySessionController.java
/** * @param function//from w ww . j a v a2s. co m * @param request * @return the view to display */ public String manageQuestionBusiness(String function, HttpServletRequest request) { String view; String surveyImageDirectory = FileServerUtils.getUrl(this.getComponentId(), "REPLACE_FILE_NAME", "REPLACE_FILE_NAME", "image/gif", getSettings().getString("imagesSubDirectory")); request.setAttribute("ImageDirectory", surveyImageDirectory); // Parameter variable declaration String action = ""; String question = ""; String nbAnswers = ""; String answerInput; String suggestion = ""; String style = ""; String questionId = null; File dir; String logicalName; String type; String physicalName; boolean file = false; long size; int attachmentSuffix = 0; List<Answer> answers = new ArrayList<Answer>(); Answer answer = null; // Retrieve all the parameter from request try { List<FileItem> items = HttpRequest.decorate(request).getFileItems(); for (FileItem item : items) { if (item.isFormField()) { String mpName = item.getFieldName(); if ("Action".equals(mpName)) { action = item.getString(); } else if ("question".equals(mpName)) { question = item.getString(FileUploadUtil.DEFAULT_ENCODING); } else if ("nbAnswers".equals(mpName)) { nbAnswers = item.getString(FileUploadUtil.DEFAULT_ENCODING); } else if ("SuggestionAllowed".equals(mpName)) { suggestion = item.getString(FileUploadUtil.DEFAULT_ENCODING); } else if ("questionStyle".equals(mpName)) { style = item.getString(FileUploadUtil.DEFAULT_ENCODING); } else if (mpName.startsWith("answer")) { answerInput = item.getString(FileUploadUtil.DEFAULT_ENCODING); answer = new Answer(null, null, answerInput, 0, 0, false, "", 0, false, null); answers.add(answer); } else if ("suggestionLabel".equals(mpName)) { answerInput = item.getString(FileUploadUtil.DEFAULT_ENCODING); answer = new Answer(null, null, answerInput, 0, 0, false, "", 0, true, null); answers.add(answer); } else if (mpName.startsWith("valueImageGallery")) { if (StringUtil.isDefined(item.getString(FileUploadUtil.DEFAULT_ENCODING))) { // traiter les images venant de la gallery si pas d'image externe if (!file) { answer.setImage(item.getString(FileUploadUtil.DEFAULT_ENCODING)); } } } else if ("QuestionId".equals(mpName)) { questionId = item.getString(FileUploadUtil.DEFAULT_ENCODING); } // String value = paramPart.getStringValue(); } else { // it's a file part if (FileHelper.isCorrectFile(item)) { // the part actually contained a file logicalName = item.getName(); type = logicalName.substring(logicalName.indexOf('.') + 1, logicalName.length()); physicalName = Long.toString(new Date().getTime()) + attachmentSuffix + "." + type; attachmentSuffix = attachmentSuffix + 1; dir = new File(FileRepositoryManager.getAbsolutePath(this.getComponentId()) + getSettings().getString("imagesSubDirectory") + File.separator + physicalName); FileUploadUtil.saveToFile(dir, item); size = item.getSize(); if (size > 0) { answer.setImage(physicalName); file = true; } } else { // the field did not contain a file file = false; } } } } catch (UtilException e) { SilverTrace.error("Survey", "SurveySessionController.manageQuestionBusiness", "root.EX_IGNORED", e); } catch (UnsupportedEncodingException e) { SilverTrace.error("Survey", "SurveySessionController.manageQuestionBusiness", "root.EX_IGNORED", e); } catch (IOException e) { SilverTrace.error("Survey", "SurveySessionController.manageQuestionBusiness", "root.EX_IGNORED", e); } if ("SendUpdateQuestion".equals(action) || "SendNewQuestion".equals(action)) { // Remove answer for open question if ("open".equals(style)) { answers.clear(); answers.add(new Answer(null, null, "", 0, 0, false, "", 0, false, null)); } // Remove the suggestion answer from the list if ("0".equals(suggestion)) { for (Answer curAnswer : answers) { if (curAnswer.isOpened()) { answers.remove(curAnswer); break; } } } if ("SendNewQuestion".equals(action)) { Question questionObject = new Question(null, null, question, "", "", null, style, 0); questionObject.setAnswers(answers); List<Question> questionsV = this.getSessionQuestions(); questionsV.add(questionObject); this.setSessionQuestions(questionsV); } else if (action.equals("SendUpdateQuestion")) { Question questionObject = new Question(null, null, question, "", "", null, style, 0); questionObject.setAnswers(answers); List<Question> questionsV = this.getSessionQuestions(); questionsV.set(Integer.parseInt(questionId), questionObject); this.setSessionQuestions(questionsV); } } else if (action.equals("End")) { QuestionContainerDetail surveyDetail = this.getSessionSurveyUnderConstruction(); // Vector 2 Collection List<Question> questionsV = this.getSessionQuestions(); surveyDetail.setQuestions(questionsV); } if ((action.equals("SendQuestionForm")) || "UpdateQuestion".equals(action)) { if (action.equals("SendQuestionForm")) { request.setAttribute("NbAnswers", nbAnswers); } else if ("UpdateQuestion".equals(action)) { request.setAttribute("QuestionId", questionId); } } // Prepare destination request attribute if ("SendNewQuestion".equals(action) || "SendUpdateQuestion".equals(action)) { request.setAttribute("Action", "UpdateQuestions"); request.setAttribute("SurveyName", this.getSessionSurveyName()); view = "questionsUpdate.jsp"; } else { request.setAttribute("Suggestion", suggestion); request.setAttribute("Style", style); request.setAttribute("Action", action); view = function; } return view; }
From source file:it.infn.ct.nuclemd.Nuclemd.java
public String[] uploadNuclemdSettings(ActionRequest actionRequest, ActionResponse actionResponse, String username) {/*from w w w .j a v a 2 s. co m*/ String[] NUCLEMD_Parameters = new String[9]; boolean status; // Check that we have a file upload request boolean isMultipart = PortletFileUpload.isMultipartContent(actionRequest); if (isMultipart) { // Create a factory for disk-based file items. DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constrains File NUCLEMD_Repository = new File("/tmp"); if (!NUCLEMD_Repository.exists()) status = NUCLEMD_Repository.mkdirs(); factory.setRepository(NUCLEMD_Repository); // Create a new file upload handler. PortletFileUpload upload = new PortletFileUpload(factory); try { // Parse the request List items = upload.parseRequest(actionRequest); // Processing items Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName(); DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); String timeStamp = dateFormat.format(Calendar.getInstance().getTime()); // Processing a regular form field if (item.isFormField()) { if (fieldName.equals("nuclemd_release")) NUCLEMD_Parameters[8] = item.getString(); if (fieldName.equals("nuclemd_desc")) if (item.getString().equals("Please, insert here a description")) NUCLEMD_Parameters[0] = "NUCLEMD Simulation Started"; else NUCLEMD_Parameters[0] = item.getString(); if (fieldName.equals("nuclemd_CE")) NUCLEMD_Parameters[1] = item.getString(); } else { // Processing a file upload if (fieldName.equals("nuclemd_fileinp")) { log.info("\n- Uploading the input file: " + "\n[ " + item.getName() + " ]" + "\n[ " + item.getContentType() + " ]" + "\n[ " + item.getSize() + "KBytes ]"); // Writing the file to disk String uploadNuclemdFile = NUCLEMD_Repository + "/" + timeStamp + "_" + username + "_" + item.getName(); log.info("\n- Writing the file: [ " + uploadNuclemdFile.toString() + " ] to disk"); item.write(new File(uploadNuclemdFile)); // Writing the file to disk String uploadNuclemdFile_stripped = NUCLEMD_Repository + "/" + timeStamp + "_" + username + "_" + item.getName() + "_stripped"; NUCLEMD_Parameters[2] = RemoveCarriageReturn(uploadNuclemdFile, uploadNuclemdFile_stripped); } if (fieldName.equals("nuclemd_fileconf_1")) { log.info("\n- Uploading the input file: " + "\n[ " + item.getName() + " ]" + "\n[ " + item.getContentType() + " ]" + "\n[ " + item.getSize() + "KBytes ]"); // Writing the file to disk String uploadNuclemdFile = NUCLEMD_Repository + "/" + timeStamp + "_" + username + "_" + item.getName(); log.info("\n- Writing the file: [ " + uploadNuclemdFile.toString() + " ] to disk"); item.write(new File(uploadNuclemdFile)); // Writing the file to disk String uploadNuclemdFile_stripped = NUCLEMD_Repository + "/" + timeStamp + "_" + username + "_" + item.getName() + "_stripped"; NUCLEMD_Parameters[3] = RemoveCarriageReturn(uploadNuclemdFile, uploadNuclemdFile_stripped); } if (fieldName.equals("nuclemd_fileconf_2")) { log.info("\n- Uploading the input file: " + "\n[ " + item.getName() + " ]" + "\n[ " + item.getContentType() + " ]" + "\n[ " + item.getSize() + "KBytes ]"); // Writing the file to disk String uploadNuclemdFile = NUCLEMD_Repository + "/" + timeStamp + "_" + username + "_" + item.getName(); log.info("\n- Writing the file: [ " + uploadNuclemdFile.toString() + " ] to disk"); item.write(new File(uploadNuclemdFile)); // Writing the file to disk String uploadNuclemdFile_stripped = NUCLEMD_Repository + "/" + timeStamp + "_" + username + "_" + item.getName() + "_stripped"; NUCLEMD_Parameters[4] = RemoveCarriageReturn(uploadNuclemdFile, uploadNuclemdFile_stripped); } } if (fieldName.equals("EnableNotification")) NUCLEMD_Parameters[5] = item.getString(); if (fieldName.equals("nuclemd_maxwallclocktime")) NUCLEMD_Parameters[6] = item.getString(); if (fieldName.equals("EnableDemo")) NUCLEMD_Parameters[7] = item.getString(); } // end while } catch (FileUploadException ex) { Logger.getLogger(Nuclemd.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(Nuclemd.class.getName()).log(Level.SEVERE, null, ex); } } return NUCLEMD_Parameters; }
From source file:net.i2cat.csade.life2.backoffice.servlet.UserManagementService.java
/** * Funcin que se ejecuta cuando el servlet recibe los datos *///from w w w. j ava 2s . c om 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.stratelia.webactiv.kmelia.servlets.KmeliaRequestRouter.java
/** * Process Form Upload for publications import */* www.ja v a 2s . co m*/ * @param kmeliaScc * @param request * @param routeDestination * @return destination */ private String processFormUpload(KmeliaSessionController kmeliaScc, HttpRequest request, String routeDestination, boolean isMassiveMode) { String destination = ""; String topicId = ""; String importMode; boolean draftMode = false; String logicalName; String message; boolean error = false; String tempFolderName; String tempFolderPath = null; String fileType; long fileSize; long processStart = new Date().getTime(); ResourceLocator attachmentResourceLocator = new ResourceLocator( "org.silverpeas.util.attachment.multilang.attachment", kmeliaScc.getLanguage()); FileItem fileItem; int versionType = DocumentVersion.TYPE_DEFAULT_VERSION; try { List<FileItem> items = request.getFileItems(); topicId = FileUploadUtil.getParameter(items, "topicId"); importMode = FileUploadUtil.getParameter(items, "opt_importmode"); String sVersionType = FileUploadUtil.getParameter(items, "opt_versiontype"); if (StringUtil.isDefined(sVersionType)) { versionType = Integer.parseInt(sVersionType); } String sDraftMode = FileUploadUtil.getParameter(items, "chk_draft"); if (StringUtil.isDefined(sDraftMode)) { draftMode = StringUtil.getBooleanValue(sDraftMode); } fileItem = FileUploadUtil.getFile(items, "file_name"); if (fileItem != null) { logicalName = fileItem.getName(); if (logicalName != null) { boolean runOnUnix = !FileUtil.isWindows(); if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); SilverTrace.info("kmelia", "KmeliaRequestRouter.processFormUpload", "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); // Name of temp folder: timestamp and userId tempFolderName = Long.toString(System.currentTimeMillis()) + "_" + kmeliaScc.getUserId(); // Mime type of the file fileType = fileItem.getContentType(); // Zip contentType not detected under Firefox ! if (!ClientBrowserUtil.isInternetExplorer(request)) { fileType = MimeTypes.ARCHIVE_MIME_TYPE; } fileSize = fileItem.getSize(); // Directory Temp for the uploaded file tempFolderPath = FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName; if (!new File(tempFolderPath).exists()) { FileRepositoryManager.createAbsolutePath(kmeliaScc.getComponentId(), GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName); } // Creation of the file in the temp folder File fileUploaded = new File(FileRepositoryManager.getAbsolutePath(kmeliaScc.getComponentId()) + GeneralPropertiesManager.getString("RepositoryTypeTemp") + File.separator + tempFolderName + File.separator + logicalName); fileItem.write(fileUploaded); // Is a real file ? if (fileSize <= 0L) { // File access failed message = attachmentResourceLocator.getString("liaisonInaccessible"); error = true; } else { SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "fileUploaded = " + fileUploaded + " fileSize=" + fileSize + " fileType=" + fileType + " importMode=" + importMode + " draftMode=" + draftMode); // Import !! ImportReport importReport = kmeliaScc.importFile(fileUploaded, fileType, topicId, importMode, draftMode, versionType); long processDuration = new Date().getTime() - processStart; // Compute nbPublication created int nbPublication = kmeliaScc.getNbPublicationImported(importReport); // nbFiles imported (only in unitary Import mode) int nbFiles = importReport.getNbFilesProcessed(); // Title for popup report String importModeTitle; if (importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE)) { importModeTitle = kmeliaScc.getString("kmelia.ImportModeUnitaireTitre"); } else { importModeTitle = kmeliaScc.getString("kmelia.ImportModeMassifTitre"); } SilverTrace.debug("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.MSG_GEN_PARAM_VALUE", "nbFiles = " + nbFiles + " nbPublication=" + nbPublication + " ProcessDuration=" + processDuration + " ImportMode=" + importMode + " Draftmode=" + draftMode + " Title=" + importModeTitle); message = kmeliaScc.getErrorMessageImportation(importReport, importMode); if (message != null && importMode.equals(KmeliaSessionController.UNITARY_IMPORT_MODE)) { error = true; } request.setAttribute("NbPublication", nbPublication); request.setAttribute("NbFiles", nbFiles); request.setAttribute("ProcessDuration", FileRepositoryManager.formatFileUploadTime(processDuration)); request.setAttribute("ImportMode", importMode); request.setAttribute("DraftMode", draftMode); request.setAttribute("Title", importModeTitle); request.setAttribute("Context", URLManager.getApplicationURL()); request.setAttribute("Message", message); destination = routeDestination + "reportImportFiles.jsp"; String componentId = kmeliaScc.getComponentId(); if (kmeliaScc.isDefaultClassificationModifiable(topicId, componentId)) { List<PublicationDetail> publicationDetails = kmeliaScc .getListPublicationImported(importReport, importMode); if (publicationDetails.size() > 0) { request.setAttribute("PublicationsDetails", publicationDetails); destination = routeDestination + "validateImportedFilesClassification.jsp"; } } } // Delete temp folder FileFolderManager.deleteFolder(tempFolderPath); } else { // the field did not contain a file message = attachmentResourceLocator.getString("liaisonInaccessible"); error = true; } } else { // the field did not contain a file message = attachmentResourceLocator.getString("liaisonInaccessible"); error = true; } if (error) { request.setAttribute("Message", message); request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } } } catch (Exception e) { String exMessage = SilverpeasTransverseErrorUtil.performExceptionMessage(e, kmeliaScc.getLanguage()); if (StringUtil.isNotDefined(exMessage)) { request.setAttribute("Message", e.getMessage()); } // Other exception request.setAttribute("TopicId", topicId); destination = routeDestination + "importOneFile.jsp"; if (isMassiveMode) { destination = routeDestination + "importMultiFiles.jsp"; } SilverTrace.warn("kmelia", "KmeliaRequestRouter.processFormUpload()", "root.EX_LOAD_ATTACHMENT_FAILED", e); } finally { if (tempFolderPath != null) { FileFolderManager.deleteFolder(tempFolderPath); } } return destination; }
From source file:ffsutils.TaskUtils.java
public static ArrayList<TaskImage> getTaskUpImag(Connection connconn, String tranid1, UserAccount userName, String Description, String filetype, FileItem thisfile) throws SQLException { String tranid2;// w ww. j ava 2 s . co m Integer comp = 2; Integer tranlen = tranid1.length(); int retval = comp.compareTo(tranlen); if (retval > 0) { tranid2 = "0" + tranid1; } else if (retval < 0) { tranid2 = tranid1.substring(tranid1.length() - 2); } else { tranid2 = tranid1; } System.out.println( "getTaskUpImag " + userName + " size " + String.valueOf(thisfile.getSize()) + " " + tranid2); PreparedStatement pstm2 = null; FileInputStream fis; pstm2 = connconn.prepareStatement("insert into " + userName.getcompany() + ".taskimag" + tranid2 + " (user, dateup,imagedesc, taskid, imagetype, imag1) values (?, current_timestamp, ? , '" + tranid1 + "' ,'" + filetype + "', ?)"); //PreparedStatement pstm2 = connconn.prepareStatement(sql2); OutputStream inputstream = null; try { inputstream = thisfile.getOutputStream(); } catch (Exception ex) { ex.printStackTrace(); } pstm2.setString(1, userName.getUserName()); pstm2.setString(2, Description); //pstm2.setBlob(3,inputstream); try { pstm2.setBinaryStream(3, thisfile.getInputStream(), (int) thisfile.getSize()); } catch (IOException e) { e.printStackTrace(); } // pstm2.setString(1, tranid1); Integer temp1 = pstm2.executeUpdate(); String sql = "Select * from " + userName.getcompany() + ".taskimag" + tranid2 + " a where a.taskid =?"; PreparedStatement pstm = connconn.prepareStatement(sql); pstm.setString(1, tranid1); ResultSet rs = pstm.executeQuery(); ArrayList<TaskImage> list = new ArrayList<TaskImage>(); while (rs.next()) { String Tranid = rs.getString("tranid"); String User = rs.getString("user"); String ImageDesc = rs.getString("imagedesc"); String ImageType = rs.getString("imagetype"); Date date = new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(rs.getTimestamp("dateup")); String year = Integer.toString(calendar.get(Calendar.YEAR)); String month = Integer.toString(calendar.get(Calendar.MONTH) + 1); String day = Integer.toString(calendar.get(Calendar.DAY_OF_MONTH)); String hour = Integer.toString(calendar.get(Calendar.HOUR_OF_DAY)); String minute = Integer.toString(calendar.get(Calendar.MINUTE)); int length = month.length(); if (length == 1) { month = "0" + month; } int length2 = day.length(); if (length2 == 1) { day = "0" + day; } int length3 = hour.length(); if (length3 == 1) { hour = "0" + hour; } int length4 = minute.length(); if (length4 == 1) { minute = "0" + minute; } String thistime = year + "/" + month + "/" + day + " " + hour + ":" + minute; String DateUp = thistime; TaskImage taskimage = new TaskImage(); taskimage.setTranid(Tranid); taskimage.setUser(User); taskimage.setImageDesc(ImageDesc); taskimage.setImageType(ImageType); taskimage.setDateUp(DateUp); list.add(taskimage); } return list; }
From source file:es.sm2.openppm.front.servlets.MaintenanceServlet.java
/** * Save a document or manual//from w w w . ja v a2 s .co m * @param req * @param resp * @throws IOException * @throws ServletException */ private void saveDocumentation(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { int docId = Integer.parseInt(getMultipartField("idDocumentation")); int idManten = Integer.parseInt(getMultipartField("idManten")); String namePopup = getMultipartField("namePopup"); try { FileItem dataFile = getMultipartFields().get("file"); if (dataFile != null) { Documentation doc = new Documentation(); Contentfile docFile = new Contentfile(); // Declare logics DocumentationLogic docLogic = new DocumentationLogic(); ContentFileLogic fileLogic = new ContentFileLogic(); if (docId != -1) { // Logic find doc doc = docLogic.findById(docId); infoUpdated(req, "maintenance.documentation_manuals.documentation"); } else { infoCreated(req, "maintenance.documentation_manuals.documentation"); } if (dataFile.getSize() > 0) { // Delete old file if update doc if (docId != -1) { fileLogic.delete(fileLogic.findByDocumentation(doc)); } // Set data content file docFile.setExtension(FilenameUtils.getExtension(dataFile.getName())); docFile.setMime(dataFile.getContentType()); docFile.setContent(dataFile.get()); // Logic save content file docFile = fileLogic.save(docFile); // Update doc doc.setNameFile(dataFile.getName()); doc.setContentfile(docFile); } doc.setNamePopup(namePopup); doc.setCompany(getCompany(req)); // Logic save doc docLogic.save(doc); } } catch (Exception e) { ExceptionUtil.evalueException(req, getResourceBundle(req), LOGGER, e); } consMaintenance(req, resp, idManten); }