List of usage examples for org.apache.commons.fileupload FileItem getSize
long getSize();
From source file:it.eng.spagobi.tools.importexport.services.ImportExportModule.java
/** * Manages the request of the user to import contents of an exported archive * /* w ww . j av a 2s . c om*/ * @param request * Spago SourceBean request * @param response * Spago SourceBean response * @throws EMFUserError */ private void importConf(SourceBean request, SourceBean response) throws EMFUserError { logger.debug("IN"); HashMap<String, String> logParam = new HashMap(); SessionContainer permanentSession = this.getRequestContainer().getSessionContainer() .getPermanentContainer(); IEngUserProfile profile = (IEngUserProfile) permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE); IImportManager impManager = null; // get exported file and eventually the associations file // UploadedFile archive = null; // UploadedFile associationsFile = null; FileItem archive = null; FileItem associationsFileItem = null; UploadedFile associationsFile = null; AssociationFile assFile = null; try { String assKindFromReq = (String) request.getAttribute("importAssociationKind"); boolean isNoAssociationModality = assKindFromReq != null && assKindFromReq.equalsIgnoreCase("noassociations"); List uplFiles = request.getAttributeAsList("UPLOADED_FILE"); if (uplFiles != null) { logger.debug("Uploded files [" + uplFiles.size() + "]"); } Iterator uplFilesIter = uplFiles.iterator(); while (uplFilesIter.hasNext()) { FileItem uplFile = (FileItem) uplFilesIter.next(); logger.debug("Uploded file name [" + uplFile + "]"); logParam.put("ImportFileName", uplFile.getName()); String nameInForm = uplFile.getFieldName(); if (nameInForm.equals("exportedArchive")) { archive = uplFile; } else if (nameInForm.equals("associationsFile")) { associationsFileItem = uplFile; } } // check that the name of the uploaded archive is not empty //String archiveName = archive.getFileName(); String archiveName = GeneralUtilities.getRelativeFileNames(archive.getName()); logger.debug("Archive file name [" + archiveName + "]"); if (archiveName.trim().equals("")) { logger.error("Missing exported file"); response.setAttribute(ImportExportConstants.PUBLISHER_NAME, "ImportExportLoopbackStopImport"); try { AuditLogUtilities.updateAudit(getHttpRequest(), profile, "IMPORT", logParam, "KO"); } catch (Exception e) { e.printStackTrace(); } throw new EMFValidationError(EMFErrorSeverity.ERROR, "exportedArchive", "8007", ImportManager.messageBundle); } int maxSize = ImportUtilities.getImportFileMaxSize(); if (archive.getSize() > maxSize) { logger.error("File is too large!!!"); response.setAttribute(ImportExportConstants.PUBLISHER_NAME, "ImportExportLoopbackStopImport"); try { AuditLogUtilities.updateAudit(getHttpRequest(), profile, "IMPORT", logParam, "KO"); } catch (Exception e) { e.printStackTrace(); } throw new EMFValidationError(EMFErrorSeverity.ERROR, "exportedArchive", "202"); } // checks if the association file is bigger than 1 MB, that is more than enough!! if (associationsFileItem != null) { if (associationsFileItem.getSize() > 1048576) { try { AuditLogUtilities.updateAudit(getHttpRequest(), profile, "IMPORT", logParam, "KO"); } catch (Exception e) { e.printStackTrace(); } throw new EMFValidationError(EMFErrorSeverity.ERROR, "associationsFile", "202"); } // loads association file associationsFile = new UploadedFile(); associationsFile.setFileContent(associationsFileItem.get()); associationsFile.setFieldNameInForm(associationsFileItem.getFieldName()); associationsFile.setSizeInBytes(associationsFileItem.getSize()); associationsFile.setFileName(GeneralUtilities.getRelativeFileNames(associationsFileItem.getName())); } // if the user choose to have no associations, checks the form, otherwise set the variable associationsFile = null if (!isNoAssociationModality) { // check if the name of associations file is empty (in this case set // null to the variable) if (associationsFile != null) { String associationsFileName = associationsFile.getFileName(); if (associationsFileName.trim().equals("")) { associationsFile = null; } } // if the association file is empty then check if there is an // association id // rebuild the uploaded file and assign it to associationsFile variable if (associationsFile == null) { String assId = (String) request.getAttribute("hidAssId"); if ((assId != null) && !assId.trim().equals("")) { IAssociationFileDAO assfiledao = new AssociationFileDAO(); assFile = assfiledao.loadFromID(assId); byte[] content = assfiledao.getContent(assFile); UploadedFile uplFile = new UploadedFile(); uplFile.setSizeInBytes(content.length); uplFile.setFileContent(content); uplFile.setFileName("association.xml"); uplFile.setFieldNameInForm(""); associationsFile = uplFile; } } } else { associationsFile = null; } // get the association mode String assMode = IImportManager.IMPORT_ASS_DEFAULT_MODE; if (assKindFromReq.equalsIgnoreCase("predefinedassociations")) { assMode = IImportManager.IMPORT_ASS_PREDEFINED_MODE; } // get bytes of the archive byte[] archiveBytes = archive.get(); // get path of the import tmp directory String pathImpTmpFolder = ImportUtilities.getImportTempFolderPath(); // apply transformation TransformManager transManager = new TransformManager(); archiveBytes = transManager.applyTransformations(archiveBytes, archiveName, pathImpTmpFolder); logger.debug("Transformation applied succesfully"); // prepare import environment impManager = ImportUtilities.getImportManagerInstance(); impManager.setUserProfile(profile); impManager.init(pathImpTmpFolder, archiveName, archiveBytes); impManager.openSession(); impManager.setAssociationFile(assFile); // if the associations file has been uploaded fill the association keeper if (associationsFile != null) { byte[] assFilebys = associationsFile.getFileContent(); String assFileStr = new String(assFilebys); try { impManager.getUserAssociation().fillFromXml(assFileStr); } catch (Exception e) { logger.error("Error while loading association file content:\n " + e); response.setAttribute(ImportExportConstants.PUBLISHER_NAME, "ImportExportLoopbackStopImport"); throw new EMFValidationError(EMFErrorSeverity.ERROR, "exportedArchive", "8009", ImportManager.messageBundle); } } // set into import manager the association import mode impManager.setImpAssMode(assMode); RequestContainer requestContainer = this.getRequestContainer(); SessionContainer session = requestContainer.getSessionContainer(); session.setAttribute(ImportExportConstants.IMPORT_MANAGER, impManager); // start import operations if (impManager.getImpAssMode().equals(IImportManager.IMPORT_ASS_PREDEFINED_MODE) && !impManager.associateAllExportedRolesByUserAssociation()) { response.setAttribute(ImportExportConstants.PUBLISHER_NAME, "ImportExportSkipRoleAssociation"); } else { // move to jsp List exportedRoles = impManager.getExportedRoles(); IRoleDAO roleDAO = DAOFactory.getRoleDAO(); List currentRoles = roleDAO.loadAllRoles(); response.setAttribute(ImportExportConstants.LIST_EXPORTED_ROLES, exportedRoles); response.setAttribute(ImportExportConstants.LIST_CURRENT_ROLES, currentRoles); response.setAttribute(ImportExportConstants.PUBLISHER_NAME, "ImportExportRoleAssociation"); } } catch (EMFUserError emfue) { logger.error("Error inr etrieving import configuration ", emfue); if (impManager != null) { impManager.stopImport(); } throw emfue; } catch (ClassNotFoundException cnde) { logger.error("Importer class not found", cnde); if (impManager != null) impManager.stopImport(); try { AuditLogUtilities.updateAudit(getHttpRequest(), profile, "IMPORT", logParam, "ERR"); } catch (Exception e) { e.printStackTrace(); } throw new EMFUserError(EMFErrorSeverity.ERROR, "8004", ImportManager.messageBundle); } catch (InstantiationException ie) { logger.error("Cannot create an instance of importer class ", ie); if (impManager != null) impManager.stopImport(); try { AuditLogUtilities.updateAudit(getHttpRequest(), profile, "IMPORT", logParam, "ERR"); } catch (Exception e) { e.printStackTrace(); } throw new EMFUserError(EMFErrorSeverity.ERROR, "8004", ImportManager.messageBundle); } catch (IllegalAccessException iae) { logger.error("Cannot create an instance of importer class ", iae); if (impManager != null) impManager.stopImport(); try { AuditLogUtilities.updateAudit(getHttpRequest(), profile, "IMPORT", logParam, "ERR"); } catch (Exception e) { e.printStackTrace(); } throw new EMFUserError(EMFErrorSeverity.ERROR, "8004", ImportManager.messageBundle); } catch (SourceBeanException sbe) { logger.error("Error: " + sbe); if (impManager != null) impManager.stopImport(); throw new EMFUserError(EMFErrorSeverity.ERROR, "8004", ImportManager.messageBundle); } catch (Exception e) { logger.error("An unexpected error occured while performing import", e); if (impManager != null) { impManager.stopImport(); } try { AuditLogUtilities.updateAudit(getHttpRequest(), profile, "IMPORT", logParam, "ERR"); } catch (Exception ee) { ee.printStackTrace(); } throw new EMFUserError(EMFErrorSeverity.ERROR, "8004", ImportManager.messageBundle); } finally { if (impManager != null) impManager.closeSession(); logger.debug("OUT"); try { AuditLogUtilities.updateAudit(getHttpRequest(), profile, "IMPORT", logParam, "OK"); } catch (Exception e) { e.printStackTrace(); } } }
From source file:es.sm2.openppm.front.servlets.ProjectServlet.java
/** * /*w w w. java 2s . c om*/ * @param req * @param resp * @throws ServletException * @throws IOException */ private void uploadFileSystem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Request // int idProject = Integer.parseInt(getMultipartField(Documentproject.PROJECT)); int docId = Integer.parseInt(getMultipartField(Documentproject.IDDOCUMENTPROJECT)); String docType = getMultipartField(Documentproject.TYPE); String oldName = StringPool.BLANK; String contentComment = getMultipartField(Documentproject.CONTENTCOMMENT, StringPool.UTF8); String creationContact = getUser(req).getContact().getFullName(); Date creationDate = DateUtil.getCalendar().getTime(); Integer idClosureCheckProject = ValidateUtil .isNotNull(getMultipartField(Closurecheckproject.IDCLOSURECHECKPROJECT)) ? Integer.parseInt(getMultipartField(Closurecheckproject.IDCLOSURECHECKPROJECT)) : null; Integer idTimeline = ValidateUtil.isNotNull(getMultipartField(Timeline.IDTIMELINE)) ? Integer.parseInt(getMultipartField(Timeline.IDTIMELINE)) : null; // Date format SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.TIME_PATTERN); JSONObject docJSON = new JSONObject(); String errorFile = StringPool.BLANK; PrintWriter out = resp.getWriter(); resp.setContentType("text/plain"); Documentproject doc = new Documentproject(); // Declare logic DocumentprojectLogic documentprojectLogic = new DocumentprojectLogic(getSettings(req), getResourceBundle(req)); ProjectLogic projectLogic = new ProjectLogic(getSettings(req)); try { FileItem dataFile = getMultipartFields().get("file"); // Update if (docId != -1) { doc = documentprojectLogic.findById(docId, false); oldName = doc.getIdDocumentProject() + StringPool.UNDERLINE + (doc.getName().lastIndexOf("\\") != -1 ? StringUtils .formatting(doc.getName().substring(doc.getName().lastIndexOf("\\") + 1)) : StringUtils.formatting(doc.getName())); } // if new file set data if (dataFile != null && dataFile.getSize() > 0) { doc.setName(dataFile.getName().lastIndexOf("\\") != -1 ? dataFile.getName().substring(dataFile.getName().lastIndexOf("\\") + 1) : dataFile.getName()); doc.setExtension(FilenameUtils.getExtension(dataFile.getName())); doc.setMime(dataFile.getContentType()); } Project project = projectLogic.consProject(idProject); // Set another data doc.setProject(project); doc.setType(docType); doc.setContentComment(contentComment); doc.setCreationContact(creationContact); doc.setCreationDate(creationDate); // Logic doc = documentprojectLogic.save(doc); if (dataFile != null && dataFile.getSize() > 0) { String newName = doc.getIdDocumentProject() + StringPool.UNDERLINE + (dataFile.getName().lastIndexOf("\\") != -1 ? StringUtils.formatting( dataFile.getName().substring(dataFile.getName().lastIndexOf("\\") + 1)) : StringUtils.formatting(dataFile.getName())); // TODO jordi.ripoll - 12/05/2015 - los archivos se guardaban en esta ruta - al migrar reestructurar codigo String dirBySetting = SettingUtil.getString(getSettings(req), Settings.SETTING_PROJECT_DOCUMENT_FOLDER, Settings.DEFAULT_PROJECT_DOCUMENT_FOLDER); // Create folder by project and status // String docFolder = dirBySetting.concat(File.separator + StringUtils.formatting(project.getChartLabel()) + StringPool.UNDERLINE + idProject); File folderProject = new File(docFolder); if (!folderProject.isDirectory()) { // Create dir project folderProject.mkdir(); } // Update doc folder docFolder = docFolder.concat(File.separator + docType); File folderProjectStatus = new File(docFolder); if (!folderProjectStatus.isDirectory()) { // Create dir status folderProjectStatus.mkdir(); } File file = new File(docFolder, newName); // Validate file and permissions errorFile = documentprojectLogic.validateFile(new File(docFolder)); // Save file dataFile.write(file); if (!oldName.equals(newName)) { file = new File(dirBySetting, oldName); // Search in new path if (!file.exists()) { file = new File(docFolder, oldName); } // Delete old file file.delete(); } } // Set document into closure check project if (idClosureCheckProject != null) { // Declare logic ClosurecheckprojectLogic closurecheckprojectLogic = new ClosurecheckprojectLogic(); closurecheckprojectLogic.saveDocument(idClosureCheckProject, doc); // Response docJSON.put(Closurecheckproject.IDCLOSURECHECKPROJECT, idClosureCheckProject); } // Set document into timeline else if (idTimeline != null) { // Declare logic TimelineLogic timelineLogic = new TimelineLogic(getSettings(req), getResourceBundle(req)); timelineLogic.saveDocument(idTimeline, doc); // Response docJSON.put(Timeline.IDTIMELINE, idTimeline); } // Response // docJSON.put(Documentproject.IDDOCUMENTPROJECT, doc.getIdDocumentProject()); docJSON.put(Documentproject.TYPE, getResourceBundle(req).getString("documentation." + doc.getType())); docJSON.put(Documentproject.NAME, (doc.getName().lastIndexOf("\\") != -1 ? doc.getName().substring(doc.getName().lastIndexOf("\\") + 1) : doc.getName())); docJSON.put(Documentproject.CONTENTCOMMENT, doc.getContentComment()); docJSON.put(Documentproject.CREATIONCONTACT, doc.getCreationContact()); docJSON.put(Documentproject.CREATIONDATE, dateFormat.format(doc.getCreationDate())); docJSON.put("documentType", DocumentType.FILE_SYSTEM.getName()); if (docId == -1) { infoCreated(getResourceBundle(req), docJSON, "document"); //TODO esto no funciona LA CULPA ES DEL METODO AJAX de subir documento que es diferente } else { infoUpdated(getResourceBundle(req), docJSON, "document"); } // Add messages file error if (ValidateUtil.isNotNull(errorFile)) { docJSON.put(StringPool.InfoType.ERROR.getName(), errorFile); } out.print(docJSON); } catch (Exception e) { try { documentprojectLogic.delete(doc); } catch (Exception e1) { ExceptionUtil.evalueExceptionJX(out, req, getResourceBundle(req), LOGGER, e1); } ExceptionUtil.evalueExceptionJX(out, req, getResourceBundle(req), LOGGER, e); } finally { out.close(); } }
From source file:com.dien.upload.server.UploadShpServlet.java
/** * Override executeAction to save the received files in a custom place and delete this items from session. *//* w w w . j a v a 2s. c o m*/ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { JSONObject obj = new JSONObject(); HttpSession session = request.getSession(); User users = (User) session.getAttribute("user"); if (users != null && users.isDataAuth()) { for (FileItem item : sessionFiles) { if (false == item.isFormField()) { try { // 1. ? File file = File.createTempFile(item.getFieldName(), ".zip"); item.write(file); FileInputStream fis = new FileInputStream(file); if (fis.available() > 0) { System.out.println("File has " + fis.available() + " bytes"); // 2.zip CopyFile copyFile = new CopyFile(); SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); // String tmpFolder = Config.getOutPath() + File.separator + item.getFieldName() + "_" + df.format(new Date()) + "_" + new Random().nextInt(1000); copyFile.delFolder(tmpFolder); copyFile.newFolder(tmpFolder); ZipUtil.unZip(file.getAbsolutePath(), tmpFolder + File.separator, true); // 3.???shp ArrayList<String> slist = new ArrayList<String>(); getAllFile(new File(tmpFolder), slist); if (slist.size() > 0) { ArrayList<String> msglist = new ArrayList<String>(); if (checkShpFileComplete(slist.get(0), msglist)) { // 4. shp // SDEWrapper sde = new SDEWrapper(Config.getProperties()); File shpFile = new File(slist.get(0)); String path = shpFile.getPath(); String layerName = shpFile.getName(); layerName = layerName.substring(0, layerName.indexOf(".")); // ??? // ?? layerName = basis.generatorTableName(layerName); session.setAttribute(layerName, path); // sde.shpToSde(path, layerName); // 5. ? // logger.info("--" + file.getAbsolutePath() + "--isexist: "+ file.exists()); // / Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); /// Compose a xml message with the full file information obj.put("fieldname", item.getFieldName()); obj.put("name", item.getName()); obj.put("size", item.getSize()); obj.put("type", item.getContentType()); obj.put("layerName", layerName); obj.put("ret", true); obj.put("msg", "??"); } else { obj.put("ret", false); obj.put("msg", Util.listToWhere(msglist, ",")); } } else { obj.put("ret", false); obj.put("msg", "zipshp"); } } else { obj.put("ret", false); obj.put("msg", "?"); } } catch (IOException e) { obj.put("ret", false); obj.put("msg", "shpshp?????"); } catch (InterruptedException e) { obj.put("ret", false); obj.put("msg", "??"); } catch (Exception e) { obj.put("ret", false); obj.put("msg", "??"); } } } } else { obj.put("msg", "??"); } removeSessionFileItems(request); return obj.toString(); }
From source file:com.dien.manager.servlet.UploadShpServlet.java
/** * Override executeAction to save the received files in a custom place and delete this items from session. *//*from w w w . j a va2 s. c om*/ @Override public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles) throws UploadActionException { String response = ""; int cont = 0; HttpSession session = request.getSession(); User users = (User) session.getAttribute("user"); if (users != null && users.isDataAuth()) { for (FileItem item : sessionFiles) { if (false == item.isFormField()) { cont++; try { // 1. ? File file = File.createTempFile(item.getFieldName(), ".zip"); item.write(file); FileInputStream fis = new FileInputStream(file); if (fis.available() > 0) { System.out.println("File has " + fis.available() + " bytes"); // 2.zip CopyFile copyFile = new CopyFile(); String tmpFolder = Config.getOutPath() + File.separator + item.getFieldName(); copyFile.delFolder(tmpFolder); copyFile.newFolder(tmpFolder); ZipUtil.unZip(file.getAbsolutePath(), tmpFolder + File.separator, true); // 3.???shp ArrayList<String> slist = new ArrayList<String>(); getAllFile(new File(tmpFolder), slist); if (slist.size() > 0) { ArrayList<String> msglist = new ArrayList<String>(); if (checkShpFileComplete(slist.get(0), msglist)) { // 4. shp // SDEWrapper sde = new SDEWrapper(Config.getProperties()); File shpFile = new File(slist.get(0)); String path = shpFile.getPath(); String layerName = shpFile.getName(); layerName = layerName.substring(0, layerName.indexOf(".")); // ??? // ?? layerName = basis.generatorTableName(layerName); session.setAttribute(layerName, path); // sde.shpToSde(path, layerName); // 5. ? logger.info("--" + file.getAbsolutePath() + "--isexist: " + file.exists()); // / Save a list with the received files receivedFiles.put(item.getFieldName(), file); receivedContentTypes.put(item.getFieldName(), item.getContentType()); // / Compose a xml message with the full file information response += "<file-" + cont + "-field>" + item.getFieldName() + "</file-" + cont + "-field>\n"; response += "<file-" + cont + "-name>" + item.getName() + "</file-" + cont + "-name>\n"; response += "<file-" + cont + "-size>" + item.getSize() + "</file-" + cont + "-size>\n"; response += "<file-" + cont + "-type>" + item.getContentType() + "</file-" + cont + "type>\n"; response += "<file-" + cont + "-layerid>" + layerName + "</file-" + cont + "layerid>\n"; } else { response += "<file-" + cont + "-error>" + Util.listToWhere(msglist, ",") + "</file-" + cont + "error>\n"; } } else { response += "<file-" + cont + "-error>zipshp</file-" + cont + "error>\n"; } } else { response += "<file-" + cont + "-error>?</file-" + cont + "error>\n"; } } catch (IOException e) { response += "<file-" + cont + "-error>shpshp??????</file-" + cont + "error>\n"; } catch (InterruptedException e) { response += "<file-" + cont + "-error>??</file-" + cont + "error>\n"; } catch (Exception e) { response += "<file-" + cont + "-error>???</file-" + cont + "error>\n"; } } } } else { response += "<file-" + cont + "-error>???</file-" + cont + "error>\n"; } // / Remove files from session because we have a copy of them removeSessionFileItems(request); // / Send information of the received files to the client. return "<response>\n" + response + "</response>\n"; }
From source file:it.biblio.servlets.Modificapub.java
/** * metodo per gestire l'upload di file e inserimento dati * * @param request//from ww w . j ava2 s . c o m * @param response * @return * @throws IOException */ private boolean upload(HttpServletRequest request) throws IOException, SQLException, Exception { HttpSession s = SecurityLayer.checkSession(request); Map<String, Object> pub = new HashMap<String, Object>(); Map<String, Object> ristampe = new HashMap<String, Object>(); Map<String, Object> keyword = new HashMap<String, Object>(); Map<String, Object> storyboard = new HashMap<String, Object>(); if (ServletFileUpload.isMultipartContent(request)) { FileItemFactory fif = new DiskFileItemFactory(); ServletFileUpload sfo = new ServletFileUpload(fif); List<FileItem> items = sfo.parseRequest(request); for (FileItem item : items) { String fname = item.getFieldName(); if (item.isFormField() && fname.equals("titolo") && !item.getString().isEmpty()) { pub.put("titolo", item.getString()); } else if (item.isFormField() && fname.equals("autore") && !item.getString().isEmpty()) { pub.put("Autore", item.getString()); } else if (item.isFormField() && fname.equals("descrizione") && !item.getString().isEmpty()) { pub.put("descrizione", item.getString()); } else if (item.isFormField() && fname.equals("categoria") && !item.getString().isEmpty()) { pub.put("categoria", item.getString()); } else if (item.isFormField() && fname.equals("ISBN") && !item.getString().isEmpty()) { ristampe.put("isbn", item.getString()); } else if (item.isFormField() && fname.equals("numero_pagine") && !item.getString().isEmpty()) { ristampe.put("numpagine", Integer.parseInt(item.getString())); } else if (item.isFormField() && fname.equals("anno_pub") && !item.getString().isEmpty()) { ristampe.put("datapub", item.getString()); } else if (item.isFormField() && fname.equals("editore") && !item.getString().isEmpty()) { ristampe.put("editore", item.getString()); } else if (item.isFormField() && fname.equals("lingua") && !item.getString().isEmpty()) { ristampe.put("lingua", item.getString()); } else if (item.isFormField() && fname.equals("indice") && !item.getString().isEmpty()) { ristampe.put("indice", item.getString()); } else if (item.isFormField() && fname.equals("keyword") && !item.getString().isEmpty()) { keyword.put("tag1", item.getString()); } else if (item.isFormField() && fname.equals("keyword2") && !item.getString().isEmpty()) { keyword.put("tag2", item.getString()); } else if (item.isFormField() && fname.equals("keyword3") && !item.getString().isEmpty()) { keyword.put("tag3", item.getString()); } else if (item.isFormField() && fname.equals("idkey") && !item.getString().isEmpty()) { keyword.put("id", item.getString()); } else if (item.isFormField() && fname.equals("idpub") && !item.getString().isEmpty()) { pub.put("id", item.getString()); } else if (item.isFormField() && fname.equals("idris") && !item.getString().isEmpty()) { ristampe.put("isbn", item.getString()); } else if (item.isFormField() && fname.equals("modifica") && !item.getString().isEmpty()) { storyboard.put("descrizione_modifica", item.getString()); } else if (!item.isFormField() && fname.equals("PDF")) { String name = item.getName(); long size = item.getSize(); if (size > 0 && !name.isEmpty()) { File target = new File(getServletContext().getRealPath("") + File.separatorChar + "PDF" + File.separatorChar + name); item.write(target); ristampe.put("download", "PDF" + File.separatorChar + name); } } else if (!item.isFormField() && fname.equals("copertina")) { String name = item.getName(); long size = item.getSize(); if (size > 0 && !name.isEmpty()) { File target = new File(getServletContext().getRealPath("") + File.separatorChar + "Copertine" + File.separatorChar + name); item.write(target); ristampe.put("copertina", "Copertine" + File.separatorChar + name); } } } storyboard.put("id_utente", s.getAttribute("userid")); storyboard.put("id_pub", pub.get("id")); if (Database.updateRecord("keyword", keyword, "id=" + keyword.get("id"))) { Database.updateRecord("pubblicazioni", pub, "id=" + pub.get("id")); Database.insertRecord("storyboard", storyboard); Database.updateRecord("ristampe", ristampe, "isbn=" + ristampe.get("isbn")); return true; } else { return false; } } return false; }
From source file:it.infn.ct.ParallelSemanticSearch_portlet.java
public void getInputForm(ActionRequest request, App_Input appInput) { if (PortletFileUpload.isMultipartContent(request)) { try {//from ww w. j a v a 2s . co m FileItemFactory factory = new DiskFileItemFactory(); PortletFileUpload upload = new PortletFileUpload(factory); List items = upload.parseRequest(request); File repositoryPath = new File("/tmp"); DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(repositoryPath); Iterator iter = items.iterator(); String logstring = ""; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); // Prepare a log string with field list logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'"; switch (inputControlsIds.valueOf(fieldName)) { case JobIdentifier: appInput.jobIdentifier = item.getString(); break; default: _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'"); } // switch fieldName } // while iter.hasNext() _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS); } // try catch (Exception e) { _log.info("Caught exception while processing files to upload: '" + e.toString() + "'"); } } // The input form do not use the "multipart/form-data" else { // Retrieve from the input form the given application values appInput.search_word = (String) request.getParameter("search_word"); appInput.jobIdentifier = (String) request.getParameter("JobIdentifier"); appInput.nameSubject = (String) request.getParameter("nameSubject"); appInput.idResouce = (String) request.getParameter("idResource"); appInput.selected_language = (String) request.getParameter("selLanguage"); appInput.numberPage = (String) request.getParameter("numberOfPage"); appInput.numberPageOpenAgris = (String) request.getParameter("numberOfPageOpenAgris"); appInput.numRecordsForPage = (String) request.getParameter("numberOfRecords"); appInput.moreResourceCHAIN = (String) request.getParameter("moreResourceCHAIN"); appInput.moreResourceOpenAgris = (String) request.getParameter("moreResourceOpenAgris"); appInput.idResourceOpenAgris = (String) request.getParameter("idResourceOpenAgris"); appInput.moreInfoOpenAgris = (String) request.getParameter("moreInfoOpenAgris"); appInput.moreInfo = (String) request.getParameter("moreInfo"); appInput.numberPageCulturaItalia = (String) request.getParameter("numberOfPageCulturaItalia"); appInput.moreResourceCulturaItalia = (String) request.getParameter("moreResourceCulturaItalia"); appInput.moreInfoCulturaItalia = (String) request.getParameter("moreInfoCulturaItalia"); appInput.numResource = (String) request.getParameter("numResource"); appInput.numResourceFromDetails = (String) request.getParameter("numResourceFromDetails"); appInput.numResourceOpenAgris = (String) request.getParameter("numResourceOpenAgris"); appInput.numResourceOpenAgrisFromDetails = (String) request .getParameter("numResourceOpenAgrisFromDetails"); appInput.numResourceCulturaItalia = (String) request.getParameter("numResourceCulturaItalia"); appInput.numResourceCulturaItaliaFromDetails = (String) request .getParameter("numResourceCulturaItaliaFromDetails"); appInput.idResourceCulturaItalia = (String) request.getParameter("idResourceCulturaItalia"); appInput.numberPageIsidore = (String) request.getParameter("numberOfPageIsidore"); appInput.moreResourceIsidore = (String) request.getParameter("moreResourceIsidore"); appInput.idResourceIsidore = (String) request.getParameter("idResourceIsidore"); appInput.numResourceIsidore = (String) request.getParameter("numResourceIsidore"); appInput.numResourceIsidoreFromDetails = (String) request.getParameter("numResourceIsidoreFromDetails"); appInput.numberPageIsidore = (String) request.getParameter("numberOfPageIsidore"); appInput.moreInfoIsidore = (String) request.getParameter("moreInfoIsidore"); appInput.idResourceEuropeana = (String) request.getParameter("idResourceEuropeana"); appInput.moreResourceEuropeana = (String) request.getParameter("moreResourceEuropeana"); appInput.numberPageEuropeana = (String) request.getParameter("numberOfPageEuropeana"); appInput.numResourceEuropeana = (String) request.getParameter("numResourceEuropeana"); appInput.numResourceEuropeanaFromDetails = (String) request .getParameter("numResourceEuropeanaFromDetails"); appInput.numberPageEuropeana = (String) request.getParameter("numberOfPageEuropeana"); appInput.moreInfoEuropeana = (String) request.getParameter("moreInfoEuropeana"); appInput.idResourcePubmed = (String) request.getParameter("idResourcePubmed"); appInput.moreResourcePubmed = (String) request.getParameter("moreResourcePubmed"); appInput.numberPagePubmed = (String) request.getParameter("numberOfPagePubmed"); appInput.numResourcePubmed = (String) request.getParameter("numResourcePubmed"); appInput.numResourcePubmedFromDetails = (String) request.getParameter("numResourcePubmedFromDetails"); appInput.moreInfoPubmed = (String) request.getParameter("moreInfoPubmed"); appInput.idResourceEngage = (String) request.getParameter("idResourceEngage"); appInput.moreResourceEngage = (String) request.getParameter("moreResourceEngage"); appInput.numberPageEngage = (String) request.getParameter("numberOfPageEngage"); appInput.numResourceEngage = (String) request.getParameter("numResourceEngage"); appInput.numResourceEngageFromDetails = (String) request.getParameter("numResourceEngageFromDetails"); appInput.moreInfoEngage = (String) request.getParameter("moreInfoEngage"); appInput.title_GS = (String) request.getParameter("title_GS"); } // ! isMultipartContent // Show into the log the taken inputs _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "Search Word: '" + appInput.search_word + "'" + LS + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS + "subject: '" + appInput.nameSubject + "'" + LS + "idResource: '" + appInput.idResouce + "'" + LS + "language selected: '" + appInput.selected_language + "'" + LS + "number page selected: '" + appInput.numberPage + "'" + LS + "number record for page: '" + appInput.numRecordsForPage + "'" + LS + "number page selected OpenAgris: '" + appInput.numberPageOpenAgris + "'" + LS + "moreResourceCHAIN: '" + appInput.moreResourceCHAIN + "'" + LS + "moreInfo: '" + appInput.moreInfo + "'" + LS + "moreResourceOpenAgris: '" + appInput.moreResourceOpenAgris + "'" + LS + "idResourceOpenAgris: '" + appInput.idResourceOpenAgris + "'" + LS + "moreInfoOpenAgris: '" + appInput.moreInfoOpenAgris + "'" + LS + "number page selected CulturaItalia: '" + appInput.numberPageCulturaItalia + "'" + LS + "moreResourceCulturaItalia: '" + appInput.moreResourceCulturaItalia + "'" + LS + "moreInfoCulturaItalia: '" + appInput.moreInfoCulturaItalia + "'" + LS + "NumResource: '" + appInput.numResource + "'" + LS + "NumResourceFromDetails: '" + appInput.numResourceFromDetails + "'" + LS + "NumResourceOpenAgris: '" + appInput.numResourceOpenAgris + "'" + LS + "NumResourceOpenAgrisFromDetails: '" + appInput.numResourceOpenAgrisFromDetails + "'" + LS + "NumResourceCulturaItalia: '" + appInput.numResourceCulturaItalia + "'" + LS + "NumResourceCulturaItaliaFromDetails: '" + appInput.numResourceCulturaItaliaFromDetails + "'" + LS + "idResourceCulturaItalia: '" + appInput.idResourceCulturaItalia + "'" + LS + "moreResourceEuropeana: '" + appInput.moreResourceEuropeana + "'" + LS); }
From source file:com.gtwm.pb.model.manageSchema.DatabaseDefn.java
public void uploadCustomReportTemplate(HttpServletRequest request, BaseReportInfo report, String templateName, List<FileItem> multipartItems) throws DisallowedException, ObjectNotFoundException, CantDoThatException, FileUploadException { if (!(this.authManager.getAuthenticator().loggedInUserAllowedTo(request, PrivilegeType.VIEW_TABLE_DATA, report.getParentTable()))) { throw new DisallowedException(this.authManager.getLoggedInUser(request), PrivilegeType.VIEW_TABLE_DATA, report.getParentTable()); }// www . j a va 2s . c o m if (!FileUpload.isMultipartContent(new ServletRequestContext(request))) { throw new CantDoThatException("To upload a template, the form must be posted as multi-part form data"); } CompanyInfo company = this.getAuthManager().getCompanyForLoggedInUser(request); // strip extension String rinsedFileName = templateName.toLowerCase().replaceAll("\\..*$", ""); rinsedFileName = Helpers.rinseString(rinsedFileName).replace(" ", "_"); String uploadFolderName = this.getDataManagement().getWebAppRoot() + "WEB-INF/templates/uploads/" + company.getInternalCompanyName() + "/" + report.getInternalReportName(); File uploadFolder = new File(uploadFolderName); if (!uploadFolder.exists()) { if (!uploadFolder.mkdirs()) { throw new CantDoThatException("Error creating upload folder " + uploadFolderName); } } for (FileItem item : multipartItems) { // if item is a file if (!item.isFormField()) { long fileSize = item.getSize(); if (fileSize == 0) { throw new CantDoThatException("An empty file was submitted, no upload done"); } String filePath = uploadFolderName + "/" + rinsedFileName + ".vm"; File selectedFile = new File(filePath); try { item.write(selectedFile); } catch (Exception ex) { // Catching a general exception?! This is because the third // party // library throws a raw exception. Not very good throw new FileUploadException("Error writing file: " + ex.getMessage()); } } } }
From source file:com.gtwm.pb.model.manageData.DataManagement.java
/** * Upload a file for a particular field in a particular record. If a file * with the same name already exists, rename the old one to avoid * overwriting. Reset the last modified time of the old one so the rename * doesn't muck this up. Maintaining the file timestamp is useful for * version history//from w ww . ja v a2 s . c o m */ private void uploadFile(HttpServletRequest request, FileField field, FileValue fileValue, int rowId, List<FileItem> multipartItems) throws CantDoThatException, FileUploadException { if (rowId < 0) { throw new CantDoThatException("Row ID " + rowId + " invalid"); } if (!FileUpload.isMultipartContent(new ServletRequestContext(request))) { throw new CantDoThatException("To upload a file, the form must be posted as multi-part form data"); } if (fileValue.toString().contains("/")) { throw new CantDoThatException( "Filename contains a slash character which is not allowed, no upload done"); } if (fileValue.toString().contains("'") || fileValue.toString().contains("\"")) { throw new CantDoThatException("Filename must not contain quote marks"); } // Put the file in a unique folder per row ID. // This is in the format table ID / field ID / row ID String uploadFolderName = this.getWebAppRoot() + "uploads/" + field.getTableContainingField().getInternalTableName() + "/" + field.getInternalFieldName() + "/" + rowId; File uploadFolder = new File(uploadFolderName); if (!uploadFolder.exists()) { if (!uploadFolder.mkdirs()) { throw new CantDoThatException("Error creating upload folder " + uploadFolderName); } } for (FileItem item : multipartItems) { // if item is a file if (!item.isFormField()) { long fileSize = item.getSize(); if (fileSize == 0) { throw new CantDoThatException("An empty file was submitted, no upload done"); } String filePath = uploadFolderName + "/" + fileValue.toString(); File selectedFile = new File(filePath); String extension = ""; if (filePath.contains(".")) { extension = filePath.replaceAll("^.*\\.", "").toLowerCase(); } if (selectedFile.exists()) { // rename the existing file to something else so we don't // overwrite it String basePath = filePath; int fileNum = 1; if (basePath.contains(".")) { basePath = basePath.substring(0, basePath.length() - extension.length() - 1); } String renamedFileName = basePath + "-" + fileNum; if (!extension.equals("")) { renamedFileName += "." + extension; } File renamedFile = new File(renamedFileName); while (renamedFile.exists()) { fileNum++; renamedFileName = basePath + "-" + fileNum; if (!extension.equals("")) { renamedFileName += "." + extension; } renamedFile = new File(renamedFileName); } // Keep the original timestamp long lastModified = selectedFile.lastModified(); if (!selectedFile.renameTo(renamedFile)) { throw new FileUploadException("Rename of existing file from '" + selectedFile + "' to '" + renamedFile + "' failed"); } if (!renamedFile.setLastModified(lastModified)) { throw new FileUploadException("Error setting the last modified date of " + renamedFile); } // I think a File object's name is inviolable but just in // case selectedFile = new File(filePath); } try { item.write(selectedFile); } catch (Exception ex) { // Catching a general exception?! This is because the // library throws a raw exception. Not very good throw new FileUploadException("Error writing file: " + ex.getMessage()); } // Record upload speed long requestStartTime = request.getSession().getLastAccessedTime(); float secondsToUpload = (System.currentTimeMillis() - requestStartTime) / ((float) 1000); if (secondsToUpload > 10) { // Only time reasonably long uploads otherwise we'll amplify // errors float uploadSpeed = ((float) fileSize) / secondsToUpload; this.updateUploadSpeed(uploadSpeed); } if (extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png")) { // image.png -> image.png.40.png String thumb40Path = filePath + "." + 40 + "." + extension; String thumb500Path = filePath + "." + 500 + "." + extension; File thumb40File = new File(thumb40Path); File thumb500File = new File(thumb500Path); int midSize = 500; if (field.getAttachmentType().equals(AttachmentType.PROFILE_PHOTO)) { midSize = 250; } try { BufferedImage originalImage = ImageIO.read(selectedFile); int height = originalImage.getHeight(); int width = originalImage.getWidth(); // Conditional resize if ((height > midSize) || (width > midSize)) { Thumbnails.of(selectedFile).size(midSize, midSize).toFile(thumb500File); } else { FileUtils.copyFile(selectedFile, thumb500File); } // Allow files that are up to 60 px tall as long as the // width is no > 40 px Thumbnails.of(selectedFile).size(40, 60).toFile(thumb40File); } catch (IOException ioex) { throw new FileUploadException("Error generating thumbnail: " + ioex.getMessage()); } } else if (extension.equals("pdf")) { // Convert first page to PNG with imagemagick ConvertCmd convert = new ConvertCmd(); IMOperation op = new IMOperation(); op.addImage(); // Placeholder for input PDF op.resize(500, 500); op.addImage(); // Placeholder for output PNG try { // [0] means convert only first page convert.run(op, new Object[] { filePath + "[0]", filePath + "." + 500 + ".png" }); } catch (IOException ioex) { throw new FileUploadException("IO error while converting PDF to PNG: " + ioex); } catch (InterruptedException iex) { throw new FileUploadException("Interrupted while converting PDF to PNG: " + iex); } catch (IM4JavaException im4jex) { throw new FileUploadException("Problem converting PDF to PNG: " + im4jex); } } } } }
From source file:fr.paris.lutece.plugins.plu.web.PluJspBean.java
/** * Generates a message of confirmation for create a new folder * @param request the Http request/*w w w .j a v a 2 s .c om*/ * @return message */ public String getConfirmCreateFolder(HttpServletRequest request) { if (request.getParameter(PARAMETER_FOLDER_TITLE).equals("")) { return this.getMessageJsp(request, MESSAGE_ERROR_REQUIRED_FIELD, null, "jsp/admin/plugins/plu/folder/CreateFolder.jsp", null); } int nIdPlu = Integer.parseInt(request.getParameter(PARAMETER_PLU_ID)); String folderTitle = request.getParameter(PARAMETER_FOLDER_TITLE); UrlItem url = new UrlItem(JSP_DO_CREATE_FOLDER); url.addParameter(PARAMETER_PLU_ID, nIdPlu); try { url.addParameter(PARAMETER_FOLDER_PARENT_ID, URIUtil.encodeAll(request.getParameter(PARAMETER_FOLDER_PARENT_ID))); url.addParameter(PARAMETER_FOLDER_TITLE, URIUtil.encodeAll(folderTitle)); // url.addParameter( PARAMETER_FOLDER_DESCRIPTION, // URIUtil.encodeAll( request.getParameter( // PARAMETER_FOLDER_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_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[] checkImpression = request.getParameterValues(PARAMETER_FOLDER_HTML_CHECK_IMPRESSION); for (int j = 0; j < checkImpression.length; ++j) { url.addParameter(PARAMETER_FOLDER_HTML_CHECK_IMPRESSION, checkImpression[j]); } } Object[] args = { folderTitle }; Folder folder = _folderServices.findForTestTitle(folderTitle); if (folder != null) { return this.getMessageJsp(request, MESSAGE_ERROR_FOLDER_CREATE, args, "jsp/admin/plugins/plu/folder/CreateFolder.jsp", null); } 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 this.getMessageJsp(request, MESSAGE_ERROR_FOLDER_IMAGE_TYPE, args, "jsp/admin/plugins/plu/folder/CreateFolder.jsp", null); } PhysicalFile physicalFile = new PhysicalFile(); physicalFile.setValue(fileItem.get()); _folderImage.setImg(physicalFile.getValue()); } } return this.getMessageJsp(request, MESSAGE_CONFIRM_CREATE_FOLDER, args, "jsp/admin/plugins/plu/folder/CreateFolder.jsp", url.getUrl()); }
From source file:fr.paris.lutece.plugins.plu.web.PluJspBean.java
/** * Generates a message of confirmation for correct a folder * @param request the Http request/* w w w .ja v a 2s . c o m*/ * @return message */ public String getConfirmCorrectFolder(HttpServletRequest request) { if (request.getParameter(PARAMETER_FOLDER_TITLE).equals("") || request.getParameter(PARAMETER_FOLDER_DESCRIPTION).equals("") || request.getParameter(PARAMETER_HISTORY_DESCRIPTION).equals("")) { return AdminMessageService.getMessageUrl(request, MESSAGE_ERROR_REQUIRED_FIELD, AdminMessage.TYPE_STOP); } int nIdPlu = Integer.parseInt(request.getParameter(PARAMETER_PLU_ID)); String folderTitle = request.getParameter(PARAMETER_FOLDER_TITLE); UrlItem url = new UrlItem(JSP_DO_CORRECT_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)); // url.addParameter( PARAMETER_FOLDER_DESCRIPTION, // URIUtil.encodeAll( request.getParameter( // PARAMETER_FOLDER_DESCRIPTION ) ) ); 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 }; Folder folder = _folderServices.findForTestTitle(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, MESSAGE_CONFIRM_CORRECT_FOLDER, args, url.getUrl(), AdminMessage.TYPE_CONFIRMATION); }