Example usage for org.springframework.web.multipart MultipartFile getInputStream

List of usage examples for org.springframework.web.multipart MultipartFile getInputStream

Introduction

In this page you can find the example usage for org.springframework.web.multipart MultipartFile getInputStream.

Prototype

@Override
InputStream getInputStream() throws IOException;

Source Link

Document

Return an InputStream to read the contents of the file from.

Usage

From source file:org.openmrs.module.radiology.legacyui.report.template.web.RadiologyDashboardReportTemplatesTabController.java

/**
 * Handle request for importing new {@code MrrtReportTemplate}.
 * /*from   ww w . java  2 s .c o 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.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 {//from  w ww. j a  v  a 2s . co  m
        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.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;//  ww w  . j  a va 2 s.  co 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/*w ww.  j a  v  a2s. c o 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.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_9.ClobDatatypeStorageController.java

@RequestMapping(method = RequestMethod.POST)
@ResponseBody/*from w w w.j  a va  2 s .co m*/
public String create(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    ClobDatatypeStorage clobData = new ClobDatatypeStorage();
    String encoding = request.getHeader("Content-Encoding");
    clobData.setValue(IOUtils.toString(file.getInputStream(), encoding));
    clobData = datatypeService.saveClobDatatypeStorage(clobData);
    response.setStatus(HttpServletResponse.SC_CREATED);
    return clobData.getUuid();
}

From source file:org.openremote.modeler.action.FileUploadController.java

/**
 * upload an image.<br />/* www.  j a  v a  2s.  c om*/
 * your action should be : fileUploadController.htm?method=uploadImage&uploadFieldName=<b>your
 * upload Field Name</b> .
 * 
 * @param request
 * @param response
 * @throws IOException
 */
public void uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uploadFieldName = request.getParameter("uploadFieldName");

    if (uploadFieldName == null || uploadFieldName.trim().length() == 0) {
        LOGGER.error("The action must have a parameter 'uploadFieldName'");
        return;
    }

    long maxImageSize = 1024 * 1024 * 5;
    MultipartFile multipartFile = MultipartFileUtil.getMultipartFileFromRequest(request, uploadFieldName);
    if (multipartFile.getSize() == 0 || multipartFile.getSize() > maxImageSize) {
        return;
    }

    File file = resourceService.uploadImage(multipartFile.getInputStream(),
            multipartFile.getOriginalFilename());
    String delimiter = "";
    String escapedChar = "[ \\+\\-\\*%\\!\\(\\\"')_#;/?:&;=$,#<>]";
    String fileName = file.getName();
    fileName = fileName.replaceAll(escapedChar, delimiter);
    String extension = FilenameUtils.getExtension(fileName);
    fileName = fileName.replace("." + extension, "");
    fileName += System.currentTimeMillis();
    fileName += "." + extension;

    File newFile = new File(file.getParent() + File.separator + fileName);
    file.renameTo(newFile);

    if (("panelImage".equals(uploadFieldName) || "tabbarImage".equals(uploadFieldName)) && newFile.exists()) {
        rotateBackgroud(newFile);
        BufferedImage buff = ImageIO.read(newFile);
        response.getWriter()
                .print("{\"name\": \""
                        + resourceService.getRelativeResourcePathByCurrentAccount(newFile.getName())
                        + "\",\"width\":" + buff.getWidth() + ",\"height\":" + buff.getHeight() + "}");
    } else {
        response.getWriter().print(resourceService.getRelativeResourcePathByCurrentAccount(newFile.getName()));
    }
}

From source file:org.opentestsystem.delivery.testreg.rest.FileUploadDataController.java

/**
 * Upload File.//from  w  ww .j a  va 2  s  .  co  m
 *
 * @param testRegFile
 *        to be saved.
 * @returns response FileUploadResponse.
 */
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST, produces = {
        MediaType.APPLICATION_JSON_VALUE })
@Secured({ "ROLE_Accommodations Upload", "ROLE_Student Upload", "ROLE_Entity Upload",
        "ROLE_StudentGroup Upload", "ROLE_User Upload", "ROLE_ExplicitEligibility Upload" })
@ResponseBody
public FileUploadResponse uploadFile(@RequestParam("uploadFile") final MultipartFile testRegFile,
        @RequestParam final String formatType) throws Exception {
    FileUploadResponse response;
    final long start = System.currentTimeMillis();
    if (!FileType.isValidType(testRegFile.getOriginalFilename())) {
        throw new LocalizedException("file.invalid.fileextension",
                new String[] { FilenameUtils.getExtension(testRegFile.getOriginalFilename()),
                        Arrays.toString(FileType.values()) });
    } else {
        /*
         * Following line inserts FormatType of the file as first row in the file.
         */
        // InputStream inputStream = fileFormatTypeAppender.forFile(testRegFile).insert(formatType);
        final long middle = System.currentTimeMillis();
        this.metricClient.sendPerformanceMetricToMna("upload begin (ms)", middle - start);
        response = this.fileUploadService.saveFile(testRegFile.getOriginalFilename(),
                testRegFile.getInputStream(), formatType);
        this.metricClient.sendPerformanceMetricToMna(
                buildMetricMessage(response.getFileGridFsId(), "upload end"),
                System.currentTimeMillis() - middle);
        this.alertBeacon.sendAlert(MnaSeverity.INFO,
                "ART_" + FormatType.valueOf(formatType).getFormatName() + "_UPLOAD", response.getMessage());
    }
    return response;
}

From source file:org.owasp.dependencytrack.dao.LibraryVersionDao.java

/**
 * Add a Library + LibraryVersion.//  ww  w. j a  v a  2  s  .c  o  m
 *
 * @param libraryname    The name of the Library
 * @param libraryversion The version of the Library
 * @param vendor         The vendor of the Library
 * @param license        The license the Library is licensed under
 * @param file           The license file
 * @param language       The programming language the library was written in
 */
public void addLibraries(String libraryname, String libraryversion, String vendor, String license,
        MultipartFile file, String language) {
    LibraryVendor libraryVendor;
    License licenses;
    Library library;
    final Session session = sessionFactory.openSession();
    session.beginTransaction();

    Query query = session.createQuery("from LibraryVendor where upper(vendor) =upper(:vendor) ");
    query.setParameter("vendor", vendor);

    if (query.list().isEmpty()) {
        libraryVendor = new LibraryVendor();
        libraryVendor.setVendor(vendor);
        session.save(libraryVendor);
    } else {
        libraryVendor = (LibraryVendor) query.list().get(0);
    }

    query = session.createQuery("from License where upper(licensename) =upper(:license) ");
    query.setParameter("license", license);

    if (query.list().isEmpty()) {
        licenses = new License();

        InputStream licenseInputStream = null;
        try {
            licenseInputStream = file.getInputStream();
            final Blob blob = Hibernate.createBlob(licenseInputStream);

            licenses.setFilename(file.getOriginalFilename());
            licenses.setContenttype(file.getContentType());
            licenses.setLicensename(license);
            licenses.setText(blob);
            session.save(licenses);

        } catch (IOException e) {
            LOGGER.error("An error occurred while adding a library with library version");
            LOGGER.error(e.getMessage());
        } finally {
            IOUtils.closeQuietly(licenseInputStream);
        }

    } else {
        licenses = (License) query.list().get(0);
    }

    query = session.createQuery(
            "from Library as lib where upper(lib.libraryname) =upper(:libraryname) and lib.libraryVendor=:vendor ");
    query.setParameter("libraryname", libraryname);
    query.setParameter("vendor", libraryVendor);

    if (query.list().isEmpty()) {
        library = new Library();
        library.setLibraryname(libraryname);
        library.setLibraryVendor(libraryVendor);
        library.setLicense(licenses);

        library.setLanguage(language);
        session.save(library);
    } else {
        library = (Library) query.list().get(0);
    }

    query = session.createQuery("from LibraryVersion as libver where libver.library =:library "
            + "and libver.library.libraryVendor=:vendor and libver.libraryversion =:libver ");
    query.setParameter("library", library);
    query.setParameter("vendor", libraryVendor);
    query.setParameter("libver", libraryversion);

    if (query.list().isEmpty()) {
        final LibraryVersion libVersion = new LibraryVersion();
        libVersion.setLibrary(library);
        libVersion.setLibraryversion(libraryversion);
        libVersion.setUuid(UUID.randomUUID().toString());
        session.save(libVersion);
    }
    session.getTransaction().commit();

    query = session.createQuery("from LibraryVersion as libver where libver.library =:library "
            + "and libver.library.libraryVendor=:vendor and libver.libraryversion =:libver ");
    query.setParameter("library", library);
    query.setParameter("vendor", libraryVendor);
    query.setParameter("libver", libraryversion);
    final List<LibraryVersion> libraryVersions = query.list();

    session.close();

    this.eventPublisher.publishEvent(new DependencyCheckAnalysisRequestEvent(libraryVersions));
}

From source file:org.owasp.dependencytrack.dao.LibraryVersionDao.java

public void uploadLicense(int licenseid, MultipartFile file, String editlicensename) {
    InputStream licenseInputStream = null;
    try {//from   w  ww  . ja  v a 2  s  .co m
        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

/**
 * Add a Library + LibraryVersion./*  w  w  w  .  j  a v  a 2  s.co  m*/
 *
 * @param libraryname    The name of the Library
 * @param libraryversion The version of the Library
 * @param vendor         The vendor of the Library
 * @param license        The license the Library is licensed under
 * @param file           The license file
 * @param language       The programming language the library was written in
 */
@SuppressWarnings("unchecked")
public void addLibraries(final String libraryname, final String libraryversion, final String vendor,
        final String license, final MultipartFile file, final String language) {
    final Session session = getSession();
    session.beginTransaction();
    LibraryVendor libraryVendor;
    License licenses;
    Library library;

    Query query = session.createQuery("from LibraryVendor where upper(vendor) =upper(:vendor) ");
    query.setParameter("vendor", vendor);

    if (query.list().isEmpty()) {
        libraryVendor = new LibraryVendor();
        libraryVendor.setVendor(vendor);
        session.save(libraryVendor);
    } else {
        libraryVendor = (LibraryVendor) query.list().get(0);
    }

    query = session.createQuery("from License where upper(licensename) =upper(:license) ");
    query.setParameter("license", license);

    if (query.list().isEmpty()) {
        licenses = new License();

        InputStream licenseInputStream = null;
        try {
            licenseInputStream = file.getInputStream();
            String licenceFileContent = new String(IOUtils.toCharArray(licenseInputStream));
            final Blob blob = Hibernate.getLobCreator(session).createBlob(licenceFileContent.getBytes());

            licenses.setFilename(file.getOriginalFilename());
            licenses.setContenttype(file.getContentType());
            licenses.setLicensename(license);
            licenses.setText(blob);
            session.save(licenses);

        } catch (IOException e) {
            LOGGER.error("An error occurred while adding a library with library version");
            LOGGER.error(e.getMessage());
        } finally {
            IOUtils.closeQuietly(licenseInputStream);
        }

    } else {
        licenses = (License) query.list().get(0);
    }

    query = session.createQuery(
            "from Library as lib where upper(lib.libraryname) =upper(:libraryname) and lib.libraryVendor=:vendor ");
    query.setParameter("libraryname", libraryname);
    query.setParameter("vendor", libraryVendor);

    if (query.list().isEmpty()) {
        library = new Library();
        library.setLibraryname(libraryname);
        library.setLibraryVendor(libraryVendor);
        library.setLicense(licenses);

        library.setLanguage(language);
        session.save(library);
    } else {
        library = (Library) query.list().get(0);
    }

    query = session.createQuery("from LibraryVersion as libver where libver.library =:library "
            + "and libver.library.libraryVendor=:vendor and libver.libraryversion =:libver ");
    query.setParameter("library", library);
    query.setParameter("vendor", libraryVendor);
    query.setParameter("libver", libraryversion);

    if (query.list().isEmpty()) {
        final LibraryVersion libVersion = new LibraryVersion();
        libVersion.setLibrary(library);
        libVersion.setLibraryversion(libraryversion);
        libVersion.setUuid(UUID.randomUUID().toString());
        session.save(libVersion);
    }
    session.getTransaction().commit();

    query = session.createQuery("from LibraryVersion as libver where libver.library =:library "
            + "and libver.library.libraryVendor=:vendor and libver.libraryversion =:libver ");
    query.setParameter("library", library);
    query.setParameter("vendor", libraryVendor);
    query.setParameter("libver", libraryversion);
    final List<LibraryVersion> libraryVersions = query.list();

    applicationEventPublisher.publishEvent(new DependencyCheckAnalysisRequestEvent(this, libraryVersions));
}