List of usage examples for org.springframework.web.multipart MultipartFile isEmpty
boolean isEmpty();
From source file:org.openmrs.module.radiology.legacyui.report.template.web.RadiologyDashboardReportTemplatesTabController.java
/** * Handle request for importing new {@code MrrtReportTemplate}. * /*w w w .ja v a 2 s . co m*/ * @param request the HttpServletRequest to import MrrtReportTemplates * @param templateFile the MrrtReportTemplate file to be imported * @return model and view of the radiology dashboard report templates page with success or failure message in session * attribute * @throws IOException when templateFile could not be read or is invalid * @should give error message when template file is empty * @should set error message in session when mrrt report template validation exception is thrown * @should set error message in session when api exception is thrown * @should set error message in session when io exception is thrown * @should give success message when import was successful */ @RequestMapping(method = RequestMethod.POST, params = "uploadReportTemplate") protected ModelAndView uploadReportTemplate(HttpServletRequest request, @RequestParam MultipartFile templateFile) throws IOException { ModelAndView modelAndView = new ModelAndView(RADIOLOGY_REPORT_TEMPLATES_TAB_VIEW); if (templateFile.isEmpty()) { request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "radiology.MrrtReportTemplate.not.imported.empty"); return modelAndView; } try (InputStream in = templateFile.getInputStream()) { String mrrtTemplate = IOUtils.toString(in); mrrtReportTemplateService.importMrrtReportTemplate(mrrtTemplate); request.getSession().setAttribute(WebConstants.OPENMRS_MSG_ATTR, "radiology.MrrtReportTemplate.imported"); } catch (IOException exception) { request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Failed to import " + templateFile.getOriginalFilename() + " => " + exception.getMessage()); } catch (MrrtReportTemplateValidationException exception) { modelAndView.addObject("mrrtReportTemplateValidationErrors", exception.getValidationResult().getErrors()); request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Failed to import " + templateFile.getOriginalFilename()); } catch (APIException exception) { request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Failed to import " + templateFile.getOriginalFilename() + " => " + exception.getMessage()); } return modelAndView; }
From source file:org.openmrs.module.radiology.legacyui.report.template.web.RadiologyDashboardReportTemplatesTabControllerTest.java
/** * @see RadiologyDashboardReportTemplatesTabController#uploadReportTemplate(HttpServletRequest,MultipartFile) *//*from ww w . jav a 2s . co m*/ @Test public void shouldGiveErrorMessageWhenTemplateFileIsEmpty() throws Exception { MultipartFile emptyFile = mock(MultipartFile.class); when(emptyFile.isEmpty()).thenReturn(true); ModelAndView modelAndView = radiologyDashboardReportTemplatesTabController.uploadReportTemplate(request, emptyFile); verifyZeroInteractions(mrrtReportTemplateService); assertNotNull(modelAndView); assertThat(modelAndView.getViewName(), is(RadiologyDashboardReportTemplatesTabController.RADIOLOGY_REPORT_TEMPLATES_TAB_VIEW)); String message = (String) request.getSession().getAttribute(WebConstants.OPENMRS_ERROR_ATTR); assertThat(message, is("radiology.MrrtReportTemplate.not.imported.empty")); }
From source file:org.openmrs.module.radiology.report.template.web.RadiologyDashboardReportTemplatesTabControllerTest.java
/** * @see RadiologyDashboardReportTemplatesTabController#uploadReportTemplate(HttpServletRequest,MultipartFile) * @verifies give error message when template file is empty */// ww w.ja v a 2 s . c om @Test public void uploadReportTemplate_shouldGiveErrorMessageWhenTemplateFileIsEmpty() throws Exception { MultipartFile emptyFile = mock(MultipartFile.class); when(emptyFile.isEmpty()).thenReturn(true); ModelAndView modelAndView = radiologyDashboardReportTemplatesTabController.uploadReportTemplate(request, emptyFile); verifyZeroInteractions(mrrtReportTemplateService); assertNotNull(modelAndView); assertThat(modelAndView.getViewName(), is(RadiologyDashboardReportTemplatesTabController.RADIOLOGY_REPORT_TEMPLATES_TAB_VIEW)); String message = (String) request.getSession().getAttribute(WebConstants.OPENMRS_ERROR_ATTR); assertThat(message, is("radiology.MrrtReportTemplate.not.imported.empty")); }
From source file:org.openmrs.module.shr.cdahandler.web.controller.CdaImportController.java
@RequestMapping(value = "/module/shr-cdahandler/import", method = RequestMethod.POST) public ModelAndView importPOST(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("document") Document document, @RequestParam(value = "importFile") MultipartFile file) throws Throwable { if (file == null || file.isEmpty()) return new ModelAndView("redirect:import.form"); log.info("User uploaded document " + file.getOriginalFilename()); try {/* w w w . java 2 s. c om*/ Encounter e = Context.getService(cdaAntepartumService.class) .importAntepartumHistoryAndPhysical(file.getInputStream()); log.info("Successfully imported document. Generated encounter with id "); document.transformCDAtoHTML(file.getInputStream()); } catch (DocumentParseException e) { log.warn("Invalid CDA document uploaded", e); } catch (Throwable e) { log.error("", e); throw e; } return new ModelAndView("redirect:import.form"); }
From source file:org.openmrs.module.sync.web.controller.ImportListController.java
@Override protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors) throws Exception { log.info("***********************************************************\n"); log.info("Inside SynchronizationImportListController"); // just fail fast if in the midst of refreshing the context, as this was causing issues, see SYNC-318 if (Context.isRefreshingContext()) { return null; }/* w w w . ja v a 2 s . c om*/ // There are 3 ways to come to this point, so we'll handle all of them: // 1) uploading a file (results in a file attachment as response) // 2) posting data to page (results in pure XML output) // 3) remote connection (with username + password, also posting data) (results in pure XML) // none of these result in user-friendly - so no comfy, user-friendly stuff needed here //outputing statistics: debug only! log.info("HttpServletRequest INFO:"); log.info("ContentType: " + request.getContentType()); log.info("CharacterEncoding: " + request.getCharacterEncoding()); log.info("ContentLength: " + request.getContentLength()); log.info("checksum: " + request.getParameter("checksum")); log.info("syncData: " + request.getParameter("syncData")); log.info("syncDataResponse: " + request.getParameter("syncDataResponse")); long checksum = 0; Integer serverId = 0; boolean isResponse = false; boolean isUpload = false; boolean useCompression = false; String contents = ""; String username = ""; String password = ""; //file-based upload, and multi-part form submission if (request instanceof MultipartHttpServletRequest) { log.info("Processing contents of syncDataFile multipart request parameter"); MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; serverId = ServletRequestUtils.getIntParameter(multipartRequest, "serverId", 0); isResponse = ServletRequestUtils.getBooleanParameter(multipartRequest, "isResponse", false); useCompression = ServletRequestUtils.getBooleanParameter(multipartRequest, "compressed", false); isUpload = ServletRequestUtils.getBooleanParameter(multipartRequest, "upload", false); username = ServletRequestUtils.getStringParameter(multipartRequest, "username", ""); password = ServletRequestUtils.getStringParameter(multipartRequest, "password", ""); log.info("Request class: " + request.getClass()); log.info("serverId: " + serverId); log.info("upload = " + isUpload); log.info("compressed = " + useCompression); log.info("response = " + isResponse); log.info("username = " + username); log.info("Request content length: " + request.getContentLength()); MultipartFile multipartFile = multipartRequest.getFile("syncDataFile"); if (multipartFile != null && !multipartFile.isEmpty()) { InputStream inputStream = null; try { // Decompress content in file ConnectionResponse syncResponse = new ConnectionResponse( new ByteArrayInputStream(multipartFile.getBytes()), useCompression); log.info("Content to decompress: " + multipartFile.getBytes()); log.info("Content received: " + syncResponse.getResponsePayload()); log.info("Decompression Checksum: " + syncResponse.getChecksum()); contents = syncResponse.getResponsePayload(); checksum = syncResponse.getChecksum(); log.info("Final content: " + contents); } catch (Exception e) { log.warn("Unable to read in sync data file", e); } finally { IOUtils.closeQuietly(inputStream); } } } else { log.debug("seems we DO NOT have a file object"); } // prepare to process the input: contents now contains decompressed request ready to be processed SyncTransmissionResponse str = new SyncTransmissionResponse(); str.setErrorMessage(SyncConstants.ERROR_TX_NOT_UNDERSTOOD); str.setFileName(SyncConstants.FILENAME_TX_NOT_UNDERSTOOD); str.setUuid(SyncConstants.UUID_UNKNOWN); str.setSyncSourceUuid(SyncConstants.UUID_UNKNOWN); str.setSyncTargetUuid(SyncConstants.UUID_UNKNOWN); str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD); str.setTimestamp(new Date()); //set the timestamp of the response if (log.isInfoEnabled()) { log.info("CONTENT IN IMPORT CONTROLLER: " + contents); } //if no content, nothing to process just send back response if (contents == null || contents.length() < 0) { log.info("returning from ingest: nothing to process."); this.sendResponse(str, isUpload, response); return null; } // if this is option 3 (posting from remote server), we need to authenticate if (!Context.isAuthenticated()) { try { Context.authenticate(username, password); } catch (Exception e) { } } // Could not authenticate user: send back error if (!Context.isAuthenticated()) { str.setErrorMessage(SyncConstants.ERROR_AUTH_FAILED); str.setFileName(SyncConstants.FILENAME_AUTH_FAILED); str.setState(SyncTransmissionState.AUTH_FAILED); this.sendResponse(str, isUpload, response); return null; } //Fill-in the server uuid for the response: since request was authenticated we can start letting callers //know about us str.setSyncTargetUuid(Context.getService(SyncService.class).getServerUuid()); //Checksum check before doing anything at all: on unreliable networks we can get seemingly //valid HTTP POST but content is messed up, defend against it with custom checksums long checksumReceived = ServletRequestUtils.getLongParameter(request, "checksum", -1); log.info("checksum value received in POST: " + checksumReceived); log.info("checksum value of payload: " + checksum); log.info("SIZE of payload: " + contents.length()); if (checksumReceived > 0 && (checksumReceived != checksum)) { log.error("ERROR: FAILED CHECKSUM!"); str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD); this.sendResponse(str, isUpload, response); return null; } //Test message. Test message was sent (i.e. using 'test connection' button on server screen) //just send empty acknowledgment if (SyncConstants.TEST_MESSAGE.equals(contents)) { str.setErrorMessage(""); str.setState(SyncTransmissionState.OK); str.setUuid(""); str.setFileName(SyncConstants.FILENAME_TEST); this.sendResponse(str, isUpload, response); return null; } if (SyncConstants.CLONE_MESSAGE.equals(contents)) { try { log.info("CLONE MESSAGE RECEIVED, TRYING TO CLONE THE DB"); File file = Context.getService(SyncService.class).generateDataFile(); StringWriter writer = new StringWriter(); IOUtils.copy(new FileInputStream(file), writer); this.sendCloneResponse(writer.toString(), response, false); boolean clonedDBLog = Boolean.parseBoolean(Context.getAdministrationService() .getGlobalProperty(SyncConstants.PROPERTY_SYNC_CLONED_DATABASE_LOG_ENABLED, "true")); if (!clonedDBLog) { file.delete(); } } catch (Exception ex) { log.warn(ex.toString()); ex.printStackTrace(); } return null; } /************************************************************************************************************************* * This is a real transmission: - user was properly authenticated - checksums match - it is * not a test transmission Start processing! 1. Deserialize what was sent; it can be either * SyncTransmssion, or SyncTransmissionResponse 2. If it is a response, *************************************************************************************************************************/ SyncTransmission st = null; if (!isResponse) { //this is not 'response' to something we sent out; thus the contents should contain plan SyncTransmission try { log.info("xml to sync transmission with contents: " + contents); st = SyncDeserializer.xmlToSyncTransmission(contents); } catch (Exception e) { log.error("Unable to deserialize the following: " + contents, e); str.setErrorMessage("Unable to deserialize transmission contents into SyncTansmission."); str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD); this.sendResponse(str, isUpload, response); return null; } } else { log.info("Processing a response, not a transmission"); SyncTransmissionResponse priorResponse = null; try { // this is the confirmation of receipt of previous transmission priorResponse = SyncDeserializer.xmlToSyncTransmissionResponse(contents); log.info("This is a response from a previous transmission. Uuid is: " + priorResponse.getUuid()); } catch (Exception e) { log.error("Unable to deserialize the following: " + contents, e); str.setErrorMessage("Unable to deserialize transmission contents into SyncTransmissionResponse."); str.setState(SyncTransmissionState.TRANSMISSION_NOT_UNDERSTOOD); this.sendResponse(str, isUpload, response); return null; } // figure out where this came from: // for responses, the target ID contains the server that generated the response String sourceUuid = priorResponse.getSyncTargetUuid(); log.info("SyncTransmissionResponse has a sourceUuid of " + sourceUuid); RemoteServer origin = Context.getService(SyncService.class).getRemoteServer(sourceUuid); if (origin == null) { log.error("Source server not registered locally. Unable to find source server by uuid: " + sourceUuid); str.setErrorMessage( "Source server not registered locally. Unable to find source server by uuid " + sourceUuid); str.setState(SyncTransmissionState.INVALID_SERVER); this.sendResponse(str, isUpload, response); return null; } else { log.info("Found source server by uuid: " + sourceUuid + " = " + origin.getNickname()); log.info("Source server is " + origin.getNickname()); } if (priorResponse == null) { } // process response that was sent to us; the sync response normally contains: //a) results of the records that we sent out //b) new records from 'source' to be applied against this server if (priorResponse.getSyncImportRecords() == null) { log.debug("No records to process in response"); } else { // now process each incoming syncImportRecord, this is just status update for (SyncImportRecord importRecord : priorResponse.getSyncImportRecords()) { Context.getService(SyncIngestService.class).processSyncImportRecord(importRecord, origin); } } // now pull out the data that originated on the 'source' server and try to process it st = priorResponse.getSyncTransmission(); } // now process the syncTransmission if one was received if (st != null) { str = SyncUtilTransmission.processSyncTransmission(st, SyncUtil.getGlobalPropetyValueAsInteger(SyncConstants.PROPERTY_NAME_MAX_RECORDS_WEB)); } else log.info("st was null"); //send response this.sendResponse(str, isUpload, response); // never a situation where we want to actually use the model/view - either file download or http request return null; }
From source file:org.openmrs.module.sync.web.CreateChildServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); if (!Context.isAuthenticated()) { reply(response, "Not logged in, please login and retry again", "red"); return;//from ww w . java2s.c o m } if (!Context.hasPrivilege(SyncConstants.PRIV_BACKUP_ENTIRE_DATABASE)) { session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Privilege required: " + SyncConstants.PRIV_BACKUP_ENTIRE_DATABASE); session.setAttribute(WebConstants.OPENMRS_LOGIN_REDIRECT_HTTPSESSION_ATTR, request.getRequestURI() + "?" + request.getQueryString()); response.sendRedirect(request.getContextPath() + "/login.htm"); return; } response.setContentType("text/html"); MultipartHttpServletRequest multipartRequest = multipartResolver.resolveMultipart(request); MultipartFile mf = multipartRequest.getFile("cloneFile"); if (mf != null && !mf.isEmpty()) { try { File dir = SyncUtil.getSyncApplicationDir(); File file = new File(dir, SyncConstants.CLONE_IMPORT_FILE_NAME + SyncConstants.SYNC_FILENAME_MASK.format(new Date()) + ".sql"); IOUtils.copy(mf.getInputStream(), new FileOutputStream(file)); Context.getService(SyncService.class).execGeneratedFile(file); reply(response, "Child database successfully updated", "green"); boolean clonedDBLog = Boolean.parseBoolean(Context.getAdministrationService() .getGlobalProperty(SyncConstants.PROPERTY_SYNC_CLONED_DATABASE_LOG_ENABLED, "true")); if (!clonedDBLog) { file.delete(); } } catch (Exception ex) { log.warn("Unable to read the clone data file", ex); reply(response, "Unable to read the data clonefile" + ex.toString(), "red"); ex.printStackTrace(); } } else { reply(response, "The file sent is null or empty, please select a file to upload", "red"); } }
From source file:org.openmrs.module.web.controller.ModuleListController.java
/** * The onSubmit function receives the form/command object that was modified by the input form * and saves it to the db//from w w w .java2s .co m * * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(HttpServletRequest, * HttpServletResponse, Object, * BindException) */ @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { if (!Context.hasPrivilege(PrivilegeConstants.MANAGE_MODULES)) { throw new APIAuthenticationException("Privilege required: " + PrivilegeConstants.MANAGE_MODULES); } HttpSession httpSession = request.getSession(); String moduleId = ServletRequestUtils.getStringParameter(request, "moduleId", ""); String view = getFormView(); String success = ""; String error = ""; MessageSourceAccessor msa = getMessageSourceAccessor(); String action = ServletRequestUtils.getStringParameter(request, "action", ""); if (ServletRequestUtils.getStringParameter(request, "start.x", null) != null) { action = "start"; } else if (ServletRequestUtils.getStringParameter(request, "stop.x", null) != null) { action = "stop"; } else if (ServletRequestUtils.getStringParameter(request, "unload.x", null) != null) { action = "unload"; } // handle module upload if ("upload".equals(action)) { // double check upload permissions if (!ModuleUtil.allowAdmin()) { error = msa.getMessage("Module.disallowUploads", new String[] { ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN }); } else { InputStream inputStream = null; File moduleFile = null; Module module = null; Boolean updateModule = ServletRequestUtils.getBooleanParameter(request, "update", false); Boolean downloadModule = ServletRequestUtils.getBooleanParameter(request, "download", false); List<Module> dependentModulesStopped = null; try { if (downloadModule) { String downloadURL = request.getParameter("downloadURL"); if (downloadURL == null) { throw new MalformedURLException("Couldn't download module because no url was provided"); } String fileName = downloadURL.substring(downloadURL.lastIndexOf("/") + 1); final URL url = new URL(downloadURL); inputStream = ModuleUtil.getURLStream(url); moduleFile = ModuleUtil.insertModuleFile(inputStream, fileName); } else if (request instanceof MultipartHttpServletRequest) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multipartModuleFile = multipartRequest.getFile("moduleFile"); if (multipartModuleFile != null && !multipartModuleFile.isEmpty()) { String filename = WebUtil.stripFilename(multipartModuleFile.getOriginalFilename()); // if user is using the "upload an update" form instead of the main form if (updateModule) { // parse the module so that we can get the id Module tmpModule = new ModuleFileParser(multipartModuleFile.getInputStream()) .parse(); Module existingModule = ModuleFactory.getModuleById(tmpModule.getModuleId()); if (existingModule != null) { dependentModulesStopped = ModuleFactory.stopModule(existingModule, false, true); // stop the module with these parameters so that mandatory modules can be upgraded for (Module depMod : dependentModulesStopped) { WebModuleUtil.stopModule(depMod, getServletContext()); } WebModuleUtil.stopModule(existingModule, getServletContext()); ModuleFactory.unloadModule(existingModule); } inputStream = new FileInputStream(tmpModule.getFile()); moduleFile = ModuleUtil.insertModuleFile(inputStream, filename); // copy the omod over to the repo folder } else { // not an update, or a download, just copy the module file right to the repo folder inputStream = multipartModuleFile.getInputStream(); moduleFile = ModuleUtil.insertModuleFile(inputStream, filename); } } } module = ModuleFactory.loadModule(moduleFile); } catch (ModuleException me) { log.warn("Unable to load and start module", me); error = me.getMessage(); } finally { // clean up the module repository folder try { if (inputStream != null) { inputStream.close(); } } catch (IOException io) { log.warn("Unable to close temporary input stream", io); } if (module == null && moduleFile != null) { moduleFile.delete(); } } // if we didn't have trouble loading the module, start it if (module != null) { ModuleFactory.startModule(module); WebModuleUtil.startModule(module, getServletContext(), false); if (module.isStarted()) { success = msa.getMessage("Module.loadedAndStarted", new String[] { module.getName() }); if (updateModule && dependentModulesStopped != null) { for (Module depMod : sortStartupOrder(dependentModulesStopped)) { ModuleFactory.startModule(depMod); WebModuleUtil.startModule(depMod, getServletContext(), false); } } } else { success = msa.getMessage("Module.loaded", new String[] { module.getName() }); } } } } else if ("".equals(moduleId)) { if (action.equals(msa.getMessage("Module.startAll"))) { boolean someModuleNeedsARefresh = false; Collection<Module> modules = ModuleFactory.getLoadedModules(); Collection<Module> modulesInOrder = ModuleFactory.getModulesInStartupOrder(modules); for (Module module : modulesInOrder) { if (ModuleFactory.isModuleStarted(module)) { continue; } ModuleFactory.startModule(module); boolean thisModuleCausesRefresh = WebModuleUtil.startModule(module, getServletContext(), true); someModuleNeedsARefresh = someModuleNeedsARefresh || thisModuleCausesRefresh; } if (someModuleNeedsARefresh) { WebModuleUtil.refreshWAC(getServletContext(), false, null); } } else { ModuleUtil.checkForModuleUpdates(); } } else if (action.equals(msa.getMessage("Module.installUpdate"))) { // download and install update if (!ModuleUtil.allowAdmin()) { error = msa.getMessage("Module.disallowAdministration", new String[] { ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN }); } Module mod = ModuleFactory.getModuleById(moduleId); if (mod.getDownloadURL() != null) { ModuleFactory.stopModule(mod, false, true); // stop the module with these parameters so that mandatory modules can be upgraded WebModuleUtil.stopModule(mod, getServletContext()); Module newModule = ModuleFactory.updateModule(mod); WebModuleUtil.startModule(newModule, getServletContext(), false); } } else { // moduleId is not empty if (!ModuleUtil.allowAdmin()) { error = msa.getMessage("Module.disallowAdministration", new String[] { ModuleConstants.RUNTIMEPROPERTY_ALLOW_ADMIN }); } else { log.debug("Module id: " + moduleId); Module mod = ModuleFactory.getModuleById(moduleId); // Argument to pass to the success/error message Object[] args = new Object[] { moduleId }; if (mod == null) { error = msa.getMessage("Module.invalid", args); } else { if ("stop".equals(action)) { mod.clearStartupError(); ModuleFactory.stopModule(mod); WebModuleUtil.stopModule(mod, getServletContext()); success = msa.getMessage("Module.stopped", args); } else if ("start".equals(action)) { ModuleFactory.startModule(mod); WebModuleUtil.startModule(mod, getServletContext(), false); if (mod.isStarted()) { success = msa.getMessage("Module.started", args); } else { error = msa.getMessage("Module.not.started", args); } } else if ("unload".equals(action)) { if (ModuleFactory.isModuleStarted(mod)) { ModuleFactory.stopModule(mod); // stop the module so that when the web stop is done properly WebModuleUtil.stopModule(mod, getServletContext()); } ModuleFactory.unloadModule(mod); success = msa.getMessage("Module.unloaded", args); } } } } view = getSuccessView(); if (!"".equals(success)) { httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, success); } if (!"".equals(error)) { httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, error); } return new ModelAndView(new RedirectView(view)); }
From source file:org.owasp.dependencytrack.dao.LibraryVersionDao.java
public void uploadLicense(int licenseid, MultipartFile file, String editlicensename) { InputStream licenseInputStream = null; try {//from ww w.j av a 2s.com Blob blob; final Query query; if (file.isEmpty()) { query = sessionFactory.getCurrentSession() .createQuery("update License set licensename=:lname " + "where id=:licenseid"); query.setParameter("licenseid", licenseid); query.setParameter("lname", editlicensename); query.executeUpdate(); } else { licenseInputStream = file.getInputStream(); blob = Hibernate.createBlob(licenseInputStream); query = sessionFactory.getCurrentSession() .createQuery("update License set licensename=:lname," + "text=:blobfile," + "filename=:filename," + "contenttype=:contenttype " + "where id=:licenseid"); query.setParameter("licenseid", licenseid); query.setParameter("lname", editlicensename); query.setParameter("blobfile", blob); query.setParameter("filename", file.getOriginalFilename()); query.setParameter("contenttype", file.getContentType()); query.executeUpdate(); } } catch (IOException e) { LOGGER.error("An error occurred while uploading a license"); LOGGER.error(e.getMessage()); } finally { IOUtils.closeQuietly(licenseInputStream); } }
From source file:org.owasp.dependencytrack.dao.LibraryVersionDaoImpl.java
public void uploadLicense(final int licenseid, final MultipartFile file, final String editlicensename) { Session session = getSession();/*from w w w . j a v a 2s.c o m*/ InputStream licenseInputStream = null; try { Blob blob; final Query query; if (file.isEmpty()) { query = session.createQuery("update License set licensename=:lname where id=:licenseid"); query.setParameter("licenseid", licenseid); query.setParameter("lname", editlicensename); query.executeUpdate(); } else { licenseInputStream = file.getInputStream(); String licenceFileContent = new String(IOUtils.toCharArray(licenseInputStream)); blob = Hibernate.getLobCreator(session).createBlob(licenceFileContent.getBytes()); query = session.createQuery("update License set licensename=:lname," + "text=:blobfile," + "filename=:filename," + "contenttype=:contenttype " + "where id=:licenseid"); query.setParameter("licenseid", licenseid); query.setParameter("lname", editlicensename); query.setParameter("blobfile", blob); query.setParameter("filename", file.getOriginalFilename()); query.setParameter("contenttype", file.getContentType()); query.executeUpdate(); } } catch (IOException e) { LOGGER.error("An error occurred while uploading a license"); LOGGER.error(e.getMessage()); } finally { IOUtils.closeQuietly(licenseInputStream); } }
From source file:org.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
public void addMultimedia() { // This code must be read together with the SimplePageItem.MULTIMEDIA // display code in ShowPageProducer.java (To find it search for // multimediaDisplayType) and with the code in show-page.js that // handles the add multimedia dialog (look for #mm-add-item) // historically this code was to display files ,and urls leading to things // like MP4. as backup if we couldn't figure out what to do we'd put something // in an iframe. The one exception is youtube, which we supposed explicitly. // However we now support several ways to embed content. We use the // multimediaDisplayType code to indicate which. The codes are // 1 -- embed code, 2 -- av type, 3 -- oembed, 4 -- iframe // 2 is the original code: MP4, image, and as a special case youtube urls // For all practical purposes type 2 is the same as the old items that don't // have type codes (although iframes are also handled by the old code) // the old code creates ojbects in ContentHosting for both files and URLs. // The new code saves the embed code or URL itself as an atteibute of the item // If I were doing it again, I wouldn't create the ContebtHosting item // Note that IFRAME is only used for something where the far end claims the MIME // type is HTML. For weird stuff like MS Word files I use the file display code, which // ShowPageProducer figures out how to display type 2 (or default) items // on the fly, so we don't have to known here what they are. SecurityAdvisor advisor = null;/*from w w w . j a va 2s . co m*/ try { if (getCurrentPage().getOwner() != null) { advisor = new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { return SecurityAdvice.ALLOWED; } }; securityService.pushAdvisor(advisor); } if (!itemOk(itemId)) return; if (!canEditPage()) return; if (!checkCsrf()) return; if (multipartMap.size() > 0) { // user specified a file, create it for (MultipartFile file : multipartMap.values()) { if (file.isEmpty()) file = null; addMultimediaFile(file); } } } catch (Exception exception) { exception.printStackTrace(); } finally { if (advisor != null) securityService.popAdvisor(); } }