List of usage examples for org.apache.commons.fileupload FileItem get
byte[] get();
From source file:fr.paris.lutece.plugins.directory.service.upload.DirectoryAsynchronousUploadHandler.java
/** * Reinit the map with the default files stored in database and blobstore * @param request the HTTP request//www .ja v a 2 s . c o m * @param map the map <idEntry, RecordFields> * @param plugin the plugin */ public void reinitMap(HttpServletRequest request, Map<String, List<RecordField>> map, Plugin plugin) { HttpSession session = request.getSession(); removeSessionFiles(session.getId()); if ((map != null) && !map.isEmpty()) { for (java.util.Map.Entry<String, List<RecordField>> param : map.entrySet()) { for (RecordField recordField : param.getValue()) { if (recordField != null) { IEntry entry = recordField.getEntry(); if ((recordField.getFile() != null) && (recordField.getFile().getPhysicalFile() != null) && !recordField.isLittleThumbnail() && !recordField.isBigThumbnail()) { // The little thumbnail and the big thumbnail should not be stored in the session File file = recordField.getFile(); PhysicalFile physicalFile = PhysicalFileHome .findByPrimaryKey(file.getPhysicalFile().getIdPhysicalFile(), plugin); FileItem fileItem = new DirectoryFileItem(physicalFile.getValue(), file.getTitle()); // Add the file item to the map addFileItemToUploadedFile(fileItem, Integer.toString(entry.getIdEntry()), session); } else if (recordField.getEntry() instanceof EntryTypeDownloadUrl && isBlobStoreClientServiceAvailable()) { // Different behaviour if the entry is an EntryTypeDownloadUrl FileItem fileItem; try { fileItem = doDownloadFile(recordField.getValue()); FileItem directoryFileItem = new DirectoryFileItem(fileItem.get(), fileItem.getName()); // Add the file item to the map addFileItemToUploadedFile(directoryFileItem, Integer.toString(entry.getIdEntry()), session); } catch (BlobStoreClientException e) { AppLogService.error(DirectoryAsynchronousUploadHandler.class.getName() + " - Error when reinit map. Cause : " + e.getMessage()); } } } } } } }
From source file:net.cbtltd.server.UploadFileService.java
/** * Handles upload file requests is in a page submitted by a HTTP POST method. * Form field values are extracted into a parameter list to set an associated Text instance. * 'File' type merely saves file and creates associated db record having code = file name. * Files may be rendered by reference in a browser if the browser is capable of the file type. * 'Image' type creates and saves thumbnail and full size jpg images and creates associated * text record having code = full size file name. The images may be viewed by reference in a browser. * 'Blob' type saves file and creates associated text instance having code = full size file name * and a byte array data value equal to the binary contents of the file. * * @param request the HTTP upload request. * @param response the HTTP response.//from w w w. ja va 2 s . c o m * @throws ServletException signals that an HTTP exception has occurred. * @throws IOException signals that an I/O exception has occurred. */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletRequestContext ctx = new ServletRequestContext(request); if (ServletFileUpload.isMultipartContent(ctx) == false) { sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The servlet can only handle multipart requests.")); return; } LOG.debug("UploadFileService doPost request " + request); FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); LOG.debug("\n doPost upload " + upload); SqlSession sqlSession = RazorServer.openSession(); try { HashMap<String, String> params = new HashMap<String, String>(); for (FileItem item : (List<FileItem>) upload.parseRequest(request)) { if (item.isFormField()) { // add for field value to parameter list String param = item.getFieldName(); String value = item.getString(); params.put(param, value); } else if (item.getSize() > 0) { // process uploaded file // String fn = RazorServer.ROOT_DIRECTORY + item.getFieldName(); // input file path String fn = RazorConfig.getImageURL() + item.getFieldName(); // input file path LOG.debug("doPost fn " + fn); byte[] data = item.get(); String mimeType = item.getContentType(); String productId = item.getFieldName(); Pattern p = Pattern.compile("\\d+"); Matcher m = p.matcher(productId); while (m.find()) { productId = m.group(); LOG.debug("Image uploaded for Product ID: " + productId); break; } // TO DO - convert content type to mime..also check if uploaded type is image // getMagicMatch accepts Files or byte[], // which is nice if you want to test streams MagicMatch match = null; try { match = parser.getMagicMatch(data, false); LOG.debug("Mime type of image: " + match.getMimeType()); } catch (MagicParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MagicMatchNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MagicException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (match != null) { mimeType = match.getMimeType(); } // image processor logic needs to know about the format of the image String contentType = RazorConfig.getMimeExtension(mimeType); if (StringUtils.isNotEmpty(contentType)) { ImageService.uploadImages(sqlSession, productId, item.getFieldName(), params.get(Text.FILE_NOTES), data, contentType); LOG.debug("doPost commit params " + params); sqlSession.commit(); } else { // unknown content/mime type...do not upload the file sendResponse(response, new FormResponse(HttpServletResponse.SC_BAD_REQUEST, "File type - " + contentType + " is not supported")); } // File file = new File(fn); // output file name // File tempf = File.createTempFile(Text.TEMP_FILE, ""); // item.write(tempf); // file.delete(); // tempf.renameTo(file); // int fullsizepixels = Integer.valueOf(params.get(Text.FULLSIZE_PIXELS)); // if (fullsizepixels <= 0) {fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;} // int thumbnailpixels = Integer.valueOf(params.get(Text.THUMBNAIL_PIXELS)); // if (thumbnailpixels <= 0) {thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;} // // setText(sqlSession, file, fn, params.get(Text.FILE_NAME), params.get(Text.FILE_TYPE), params.get(Text.FILE_NOTES), Language.EN, fullsizepixels, thumbnailpixels); } } sendResponse(response, new FormResponse(HttpServletResponse.SC_ACCEPTED, "OK")); } catch (Throwable x) { sqlSession.rollback(); sendResponse(response, new FormResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage())); LOG.error("doPost error " + x.getMessage()); } finally { sqlSession.close(); } }
From source file:fr.paris.lutece.plugins.jasper.web.JasperJspBean.java
/** * * @param report// www . jav a 2 s . c o m * @param fileItem * @param strReportName * @param bUpdateJasper * @throws IOException */ private void localTemplateFile(JasperReport report, FileItem fileItem, String strReportName, boolean bUpdateJasper) throws IOException { String strFileName = fileItem.getName(); File file = new File(strFileName); if (!file.getName().equals("") && !strReportName.equals(null)) { String strNameFile = file.getName(); String strDirectoryPath = AppPropertiesService.getProperty(PROPERTY_FILES_PATH); String strFolderPath = AppPathService.getWebAppPath() + strDirectoryPath + strReportName; File folder = new File(strFolderPath); try { if (!folder.exists()) { folder.mkdir(); } } catch (Exception e) { AppLogService.error(e); } String filePath = AppPathService.getWebAppPath() + strDirectoryPath + strReportName + "/" + strNameFile; if (!new File(filePath).isDirectory() && bUpdateJasper) { file = new File(filePath); if (file.exists()) { file.delete(); } FileOutputStream fosFile = new FileOutputStream(file); fosFile.flush(); fosFile.write(fileItem.get()); fosFile.close(); report.setUrl(strReportName + "/" + strNameFile); } } else { report.setUrl(""); } }
From source file:axiom.servlet.AbstractServletClient.java
protected List parseUploads(ServletRequestContext reqcx, RequestTrans reqtrans, final UploadStatus uploadStatus, String encoding) throws FileUploadException, UnsupportedEncodingException { List uploads = null;//from ww w .jav a2 s. co m Context cx = Context.enter(); ImporterTopLevel scope = new ImporterTopLevel(cx, true); try { // handle file upload DiskFileItemFactory factory = new DiskFileItemFactory(); FileUpload upload = new FileUpload(factory); // use upload limit for individual file size, but also set a limit on overall size upload.setFileSizeMax(uploadLimit * 1024); upload.setSizeMax(totalUploadLimit * 1024); // register upload tracker with user's session if (uploadStatus != null) { upload.setProgressListener(new ProgressListener() { public void update(long bytesRead, long contentLength, int itemsRead) { uploadStatus.update(bytesRead, contentLength, itemsRead); } }); } uploads = upload.parseRequest(reqcx); Iterator it = uploads.iterator(); while (it.hasNext()) { FileItem item = (FileItem) it.next(); String name = item.getFieldName(); Object value = null; // check if this is an ordinary HTML form element or a file upload if (item.isFormField()) { value = item.getString(encoding); } else { String itemName = item.getName().trim(); if (itemName == null || itemName.equals("")) { continue; } value = new MimePart(itemName, item.get(), item.getContentType()); value = new NativeJavaObject(scope, value, value.getClass()); } item.delete(); // if multiple values exist for this name, append to _array // reqtrans.addPostParam(name, value); ???? Object ret = reqtrans.get(name); if (ret != null && ret != Scriptable.NOT_FOUND) { appendFormValue(reqtrans, name, value); } else { reqtrans.set(name, value); } } } finally { Context.exit(); } return uploads; }
From source file:fr.paris.lutece.plugins.directory.business.EntryTypeImg.java
/** * {@inheritDoc}// w w w . ja v a2 s. c o m */ @Override public void getRecordFieldData(Record record, HttpServletRequest request, boolean bTestDirectoryError, boolean bAddNewValue, List<RecordField> listRecordField, Locale locale) throws DirectoryErrorException { if (request instanceof MultipartHttpServletRequest) { List<FileItem> fileItems = getFileSources(request); //if asynchronous file items is empty get the file in the multipart request if (CollectionUtils.isEmpty(fileItems)) { FileItem fileItem = ((MultipartHttpServletRequest) request) .getFile(PREFIX_ENTRY_ID + this.getIdEntry()); if (fileItem != null) { fileItems = new ArrayList<FileItem>(); fileItems.add(fileItem); } } if ((fileItems != null) && !fileItems.isEmpty()) { // Checks if (bTestDirectoryError) { this.checkRecordFieldData(fileItems, locale); } // The index is used to distinguish the thumbnails of one image from another int nIndex = 0; for (FileItem fileItem : fileItems) { String strFilename = (fileItem != null) ? FileUploadService.getFileNameOnly(fileItem) : StringUtils.EMPTY; if ((fileItem != null) && (fileItem.get() != null) && (fileItem.getSize() < Integer.MAX_VALUE)) { PhysicalFile physicalFile = new PhysicalFile(); physicalFile.setValue(fileItem.get()); File file = new File(); file.setPhysicalFile(physicalFile); file.setTitle(strFilename); file.setSize((int) fileItem.getSize()); file.setMimeType(FileSystemUtil.getMIMEType(strFilename)); //Add the image to the record fields list RecordField recordField = new RecordField(); recordField.setEntry(this); recordField.setValue(FIELD_IMAGE + DirectoryUtils.CONSTANT_UNDERSCORE + nIndex); recordField.setFile(file); Field fullsizedField = FieldHome.findByValue(this.getIdEntry(), FIELD_IMAGE, PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME)); if (fullsizedField != null) { recordField.setField(fullsizedField); } listRecordField.add(recordField); //Create thumbnails records File imageFile = recordField.getFile(); Field thumbnailField = FieldHome.findByValue(this.getIdEntry(), FIELD_THUMBNAIL, PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME)); if (thumbnailField != null) { byte[] resizedImage = ImageUtil.resizeImage(imageFile.getPhysicalFile().getValue(), String.valueOf(thumbnailField.getWidth()), String.valueOf(thumbnailField.getHeight()), INTEGER_QUALITY_MAXIMUM); RecordField thbnailRecordField = new RecordField(); thbnailRecordField.setEntry(this); PhysicalFile thbnailPhysicalFile = new PhysicalFile(); thbnailPhysicalFile.setValue(resizedImage); File thbnailFile = new File(); thbnailFile.setTitle(imageFile.getTitle()); thbnailFile.setExtension(imageFile.getExtension()); if ((imageFile.getExtension() != null) && (imageFile.getTitle() != null)) { thbnailFile.setMimeType(FileSystemUtil.getMIMEType(imageFile.getTitle())); } thbnailFile.setPhysicalFile(thbnailPhysicalFile); thbnailFile.setSize(resizedImage.length); thbnailRecordField.setFile(thbnailFile); thbnailRecordField.setRecord(record); thbnailRecordField .setValue(FIELD_THUMBNAIL + DirectoryUtils.CONSTANT_UNDERSCORE + nIndex); thbnailRecordField.setField(thumbnailField); listRecordField.add(thbnailRecordField); } Field bigThumbnailField = FieldHome.findByValue(this.getIdEntry(), FIELD_BIG_THUMBNAIL, PluginService.getPlugin(DirectoryPlugin.PLUGIN_NAME)); if (bigThumbnailField != null) { byte[] resizedImage = ImageUtil.resizeImage(imageFile.getPhysicalFile().getValue(), String.valueOf(bigThumbnailField.getWidth()), String.valueOf(bigThumbnailField.getHeight()), INTEGER_QUALITY_MAXIMUM); RecordField bigThbnailRecordField = new RecordField(); bigThbnailRecordField.setEntry(this); PhysicalFile thbnailPhysicalFile = new PhysicalFile(); thbnailPhysicalFile.setValue(resizedImage); File thbnailFile = new File(); thbnailFile.setTitle(imageFile.getTitle()); thbnailFile.setExtension(imageFile.getExtension()); if ((imageFile.getExtension() != null) && (imageFile.getTitle() != null)) { thbnailFile.setMimeType(FileSystemUtil.getMIMEType(imageFile.getTitle())); } thbnailFile.setPhysicalFile(thbnailPhysicalFile); thbnailFile.setSize(resizedImage.length); bigThbnailRecordField.setFile(thbnailFile); bigThbnailRecordField.setRecord(record); bigThbnailRecordField .setValue(FIELD_BIG_THUMBNAIL + DirectoryUtils.CONSTANT_UNDERSCORE + nIndex); bigThbnailRecordField.setField(bigThumbnailField); listRecordField.add(bigThbnailRecordField); } } nIndex++; } } if (bTestDirectoryError && this.isMandatory() && ((fileItems == null) || fileItems.isEmpty())) { RecordField recordField = new RecordField(); recordField.setEntry(this); recordField.setValue(FIELD_IMAGE); listRecordField.add(recordField); throw new DirectoryErrorException(this.getTitle()); } } else if (bTestDirectoryError) { throw new DirectoryErrorException(this.getTitle()); } }
From source file:ca.qc.cegepoutaouais.tge.pige.server.UserImportService.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { hasError = Boolean.FALSE;/*from w w w . j a v a 2 s .c o m*/ writer = resp.getWriter(); logger.info("Rception de la requte HTTP pour l'imporation d'usagers."); DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(SIZE_THRESHOLD); ServletFileUpload uploadHandler = new ServletFileUpload(factory); try { List<FileItem> items = uploadHandler.parseRequest(req); if (items.size() == 0) { logger.error("Le message ne contient pas de fichier " + "d'importation. Le processus ne pourra donc pas " + "continuer."); writer.println("Erreur: Aucun fichier prsent dans le message"); return; } Charset cs = null; for (FileItem item : items) { if (item.getFieldName().equalsIgnoreCase("importFileEncoding-hidden")) { String encoding = item.getString(); if (encoding == null || encoding.isEmpty()) { logger.error("Le message ne contient pas l'encodage utilis " + "dans le fichier d'importation. Le processus ne pourra " + "donc pas continuer."); writer.println("Erreur: Aucun encodage trouv dans les " + "paramtres du message."); return; } cs = Charset.forName(encoding); if (cs == null) { logger.error("L'encodage spcifi n'existe pas (" + encoding + "). " + "Le processus ne pourra donc pas continuer."); writer.println("Erreur: Aucun encodage trouv portant le " + "nom '" + encoding + "'."); return; } } } for (FileItem item : items) { if (item.getFieldName().equalsIgnoreCase("usersImportFile")) { logger.info("Extraction du fichier d'importation partir " + "du message."); BufferedReader reader = new BufferedReader( new InputStreamReader(new ByteArrayInputStream(item.get()), cs)); doUsersImport(reader, req); break; } } if (!hasError) { logger.info("L'importation des usagers s'est termine avec succs."); writer.println("Importation russie!"); } else { logger.info("L'importation des usagers s'est termine avec des erreurs."); writer.println("L'importation s'est termine avec des erreurs."); } } catch (FileUploadException fuex) { fuex.printStackTrace(); logger.error(fuex); } catch (Exception ex) { ex.printStackTrace(); logger.error(ex); } }
From source file:it.eng.spagobi.analiticalmodel.document.utils.DetBIObjModHelper.java
/** * Recover bi obj template details.// www .jav a 2s. co m * * @return the obj template * * @throws Exception the exception */ public ObjTemplate recoverBIObjTemplateDetails() throws Exception { // GET THE USER PROFILE SessionContainer session = reqCont.getSessionContainer(); SessionContainer permanentSession = session.getPermanentContainer(); IEngUserProfile profile = (IEngUserProfile) permanentSession.getAttribute(IEngUserProfile.ENG_USER_PROFILE); //String userId=(String)profile.getUserUniqueIdentifier(); String userId = (String) ((UserProfile) profile).getUserId(); ObjTemplate templ = null; FileItem uploaded = (FileItem) request.getAttribute("UPLOADED_FILE"); if (uploaded != null) { String fileName = GeneralUtilities.getRelativeFileNames(uploaded.getName()); if (fileName != null && !fileName.trim().equals("")) { if (uploaded.getSize() == 0) { EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "201"); this.respCont.getErrorHandler().addError(error); return null; } int maxSize = GeneralUtilities.getTemplateMaxSize(); if (uploaded.getSize() > maxSize) { EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "202"); this.respCont.getErrorHandler().addError(error); return null; } templ = new ObjTemplate(); templ.setActive(new Boolean(true)); templ.setCreationUser(userId); templ.setDimension(Long.toString(uploaded.getSize() / 1000) + " KByte"); templ.setName(fileName); byte[] uplCont = uploaded.get(); templ.setContent(uplCont); } } // UploadedFile uploaded = (UploadedFile) request.getAttribute("UPLOADED_FILE"); // if (uploaded != null) { // String fileName = uploaded.getFileName(); // if (fileName != null && !fileName.trim().equals("")) { // templ = new ObjTemplate(); // templ.setActive(new Boolean(true)); // templ.setCreationUser(userId); // templ.setDimension(Long.toString(uploaded.getSizeInBytes()/1000)+" KByte"); // templ.setName(fileName); // byte[] uplCont = uploaded.getFileContent(); // templ.setContent(uplCont); // } // } return templ; }
From source file:it.eng.spagobi.engines.dossier.modules.DossierManagementModule.java
private void loadProcessDefinitionFileHandler(SourceBean request, SourceBean response) throws SourceBeanException, EMFUserError { logger.debug("IN"); try {/*from ww w .j a v a 2 s .c om*/ String tempFolder = (String) request.getAttribute(DossierConstants.DOSSIER_TEMP_FOLDER); IDossierDAO dossierDao = new DossierDAOHibImpl(); FileItem upFile = (FileItem) request.getAttribute("UPLOADED_FILE"); if (upFile != null) { String fileName = GeneralUtilities.getRelativeFileNames(upFile.getName()); if (upFile.getSize() == 0) { EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "201"); getErrorHandler().addError(error); return; } int maxSize = GeneralUtilities.getTemplateMaxSize(); if (upFile.getSize() > maxSize) { EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "202"); getErrorHandler().addError(error); return; } if (!fileName.toUpperCase().endsWith(".XML")) { List params = new ArrayList(); params.add("xml"); EMFUserError error = new EMFValidationError(EMFErrorSeverity.ERROR, "UPLOADED_FILE", "107", params, null, "component_dossier_messages"); getErrorHandler().addError(error); } else { byte[] fileContent = upFile.get(); dossierDao.storeProcessDefinitionFile(fileName, fileContent, tempFolder); } } else { logger.warn("Upload file was null!!!"); } // UploadedFile upFile = (UploadedFile) request.getAttribute("UPLOADED_FILE"); // if (upFile != null) { // String fileName = upFile.getFileName(); // if (!fileName.toUpperCase().endsWith(".XML")) { // List params = new ArrayList(); // params.add("xml"); // EMFUserError error = new EMFValidationError(EMFErrorSeverity.ERROR, "UPLOADED_FILE", "107", params, null, "component_dossier_messages"); // getErrorHandler().addError(error); // } else { // byte[] fileContent = upFile.getFileContent(); // dossierDao.storeProcessDefinitionFile(fileName, fileContent, tempFolder); // } // } else { // logger.warn("Upload file was null!!!"); // } response.setAttribute(DossierConstants.PUBLISHER_NAME, "DossierLoopbackDossierDetail"); } finally { logger.debug("OUT"); } }
From source file:it.eng.spagobi.engines.dossier.modules.DossierManagementModule.java
private void loadPresentationTemplateHandler(SourceBean request, SourceBean response) throws SourceBeanException, EMFUserError { logger.debug("IN"); try {//from w w w .j a v a 2s .c o m String tempFolder = (String) request.getAttribute(DossierConstants.DOSSIER_TEMP_FOLDER); IDossierDAO dossierDao = new DossierDAOHibImpl(); FileItem upFile = (FileItem) request.getAttribute("UPLOADED_FILE"); if (upFile != null) { String fileName = GeneralUtilities.getRelativeFileNames(upFile.getName()); if (upFile.getSize() == 0) { EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "201"); getErrorHandler().addError(error); return; } int maxSize = GeneralUtilities.getTemplateMaxSize(); if (upFile.getSize() > maxSize) { EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "202"); getErrorHandler().addError(error); return; } if (!fileName.toUpperCase().endsWith(".PPT")) { List params = new ArrayList(); params.add("ppt"); EMFUserError error = new EMFValidationError(EMFErrorSeverity.ERROR, "UPLOADED_FILE", "107", params, null, "component_dossier_messages"); getErrorHandler().addError(error); } else { byte[] fileContent = upFile.get(); dossierDao.storePresentationTemplateFile(fileName, fileContent, tempFolder); } } else { logger.warn("Upload file was null!!!"); } // UploadedFile upFile = (UploadedFile) request.getAttribute("UPLOADED_FILE"); // if (upFile != null) { // String fileName = upFile.getFileName(); // if (!fileName.toUpperCase().endsWith(".PPT")) { // List params = new ArrayList(); // params.add("ppt"); // EMFUserError error = new EMFValidationError(EMFErrorSeverity.ERROR, "UPLOADED_FILE", "107", params, null, "component_dossier_messages"); // getErrorHandler().addError(error); // } else { // byte[] fileContent = upFile.getFileContent(); // dossierDao.storePresentationTemplateFile(fileName, fileContent, tempFolder); // } // } else { // logger.warn("Upload file was null!!!"); // } response.setAttribute(DossierConstants.PUBLISHER_NAME, "DossierLoopbackDossierDetail"); } finally { logger.debug("OUT"); } }
From source file:it.eng.spagobi.tools.importexport.services.ManageImpExpAssAction.java
private void uploadAssHandler(SourceBean sbrequest) { logger.debug("IN"); try {//from ww w . j a v a 2 s . co m String modality = "MANAGE"; String name = (String) sbrequest.getAttribute("NAME"); if (name == null || name.trim().equals("")) { String msg = msgBuild.getMessage("Sbi.saving.nameNotSpecified", "component_impexp_messages", locale); httpResponse.getOutputStream().write(msg.getBytes()); httpResponse.getOutputStream().flush(); return; } String description = (String) sbrequest.getAttribute("DESCRIPTION"); if (description == null) description = ""; // UploadedFile uplFile = (UploadedFile)sbrequest.getAttribute("UPLOADED_FILE"); FileItem uplFile = (FileItem) sbrequest.getAttribute("UPLOADED_FILE"); byte[] content = null; if (uplFile == null || uplFile.getName().trim().equals("")) { String msg = msgBuild.getMessage("Sbi.saving.associationFileNotSpecified", "component_impexp_messages", locale); httpResponse.getOutputStream().write(msg.getBytes()); httpResponse.getOutputStream().flush(); return; } else { if (uplFile.getSize() == 0) { String msg = msgBuild.getMessage("201", "component_impexp_messages", locale); httpResponse.getOutputStream().write(msg.getBytes()); httpResponse.getOutputStream().flush(); return; } int maxSize = GeneralUtilities.getTemplateMaxSize(); if (uplFile.getSize() > maxSize) { String msg = msgBuild.getMessage("202", "component_impexp_messages", locale); httpResponse.getOutputStream().write(msg.getBytes()); httpResponse.getOutputStream().flush(); return; } content = uplFile.get(); if (!AssociationFile.isValidContent(content)) { String msg = msgBuild.getMessage("Sbi.saving.associationFileNotValid", "component_impexp_messages", locale); httpResponse.getOutputStream().write(msg.getBytes()); httpResponse.getOutputStream().flush(); return; } } String overwriteStr = (String) sbrequest.getAttribute("OVERWRITE"); boolean overwrite = (overwriteStr == null || overwriteStr.trim().equals("")) ? false : Boolean.parseBoolean(overwriteStr); AssociationFile assFile = new AssociationFile(); assFile.setDescription(description); assFile.setName(name); assFile.setDateCreation(new Date().getTime()); assFile.setId(name); IAssociationFileDAO assfiledao = new AssociationFileDAO(); if (assfiledao.exists(assFile.getId())) { if (overwrite) { assfiledao.deleteAssociationFile(assFile); assfiledao.saveAssociationFile(assFile, content); } else { logger.warn("Overwrite parameter is false: association file with id=[" + assFile.getId() + "] " + "and name=[" + assFile.getName() + "] will not be saved."); } } else { assfiledao.saveAssociationFile(assFile, content); } List assFiles = assfiledao.getAssociationFiles(); String html = generateHtmlJsCss(); html += "<br/>"; html += generateHtmlForInsertNewForm(); html += "<br/>"; html += generateHtmlForList(assFiles, modality); httpResponse.getOutputStream().write(html.getBytes()); httpResponse.getOutputStream().flush(); } catch (Exception e) { logger.error("Error while saving the association file, ", e); } finally { logger.debug("OUT"); } }