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

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

Introduction

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

Prototype

boolean isEmpty();

Source Link

Document

Return whether the uploaded file is empty, that is, either no file has been chosen in the multipart form or the chosen file has no content.

Usage

From source file:mx.edu.um.mateo.activos.web.ActivoController.java

@RequestMapping("/subeImagen")
public String subeImagen(@RequestParam Long activoId,
        @RequestParam(value = "imagen", required = false) MultipartFile archivo,
        RedirectAttributes redirectAttributes) {
    log.debug("Subiendo imagen para activo {}", activoId);
    try {/*from   w  w w .  j  av  a 2  s.com*/
        if (archivo != null && !archivo.isEmpty()) {
            Usuario usuario = ambiente.obtieneUsuario();
            Activo activo = activoDao.obtiene(activoId);
            Imagen imagen = new Imagen(archivo.getOriginalFilename(), archivo.getContentType(),
                    archivo.getSize(), archivo.getBytes());
            activo.getImagenes().add(imagen);
            activoDao.subeImagen(activo, usuario);
        }
        redirectAttributes.addFlashAttribute("message", "activo.sube.imagen.message");
        redirectAttributes.addFlashAttribute("messageStyle", "alert-success");
    } catch (IOException e) {
        log.error("Hubo un problema al intentar subir la imagen del activo", e);
    }
    return "redirect:/activoFijo/activo/ver/" + activoId;
}

From source file:com.balero.controllers.UploadController.java

/**
 * Upload file on server//from  w w w.j  ava  2  s  .  c  o  m
 *
 * @param file HTML <input type="file"> content
 * @param baleroAdmin Magic cookie
 * @return home view
 */
@RequestMapping(method = RequestMethod.POST)
public String upload(@RequestParam("file") MultipartFile file,
        @CookieValue(value = "baleroAdmin", defaultValue = "init") String baleroAdmin,
        HttpServletRequest request) {

    // Security
    UsersAuth security = new UsersAuth();
    security.setCredentials(baleroAdmin, UsersDAO);
    boolean securityFlag = security.auth(baleroAdmin, security.getLocalUsername(), security.getLocalPassword());
    if (!securityFlag)
        return "hacking";

    String inputFileName = file.getOriginalFilename();

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            //String rootPath = System.getProperty("catalina.home");
            File dir = new File("../webapps/media/uploads");
            if (!dir.exists())
                dir.mkdirs();

            String[] ext = new String[9];
            // Add your extension here
            ext[0] = ".jpg";
            ext[1] = ".png";
            ext[2] = ".bmp";
            ext[3] = ".jpeg";

            for (int i = 0; i < ext.length; i++) {
                int intIndex = inputFileName.indexOf(ext[i]);
                if (intIndex == -1) {
                    System.out.println("File extension is not valid");
                } else {
                    // Create the file on server
                    File serverFile = new File(dir.getAbsolutePath() + File.separator + inputFileName);
                    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                }
            }

            System.out.println("You successfully uploaded file");

        } catch (Exception e) {
            System.out.println("You failed to upload => " + e.getMessage());
        }
    } else {
        System.out.println("You failed to upload because the file was empty.");
    }

    String referer = request.getHeader("Referer");
    return "redirect:" + referer;

}

From source file:org.trpr.platform.batch.impl.spring.web.JobConfigController.java

/**
 * This method handles all the configuration changes:
 *    Uploading of XML File/*from  w  w w  .j a v  a2  s .  c o m*/
 *    Uploading of dependency
 *    Saving the changes in XML File
 */
@RequestMapping(value = "configuration/modify/jobs/{jobName}", method = RequestMethod.POST)
public String editJob(ModelMap model, @RequestParam(value = "jobName") String[] jobNames,
        @RequestParam(defaultValue = "") String XMLFileContents,
        @RequestParam(defaultValue = "0") MultipartFile jobFile,
        @RequestParam(defaultValue = "0") MultipartFile depFile,
        @RequestParam(defaultValue = "0") String identifier) throws Exception {

    List<String> jobNameList = Arrays.asList(jobNames);
    //FOr getter methods, such as getJobdependency, any of the jobNames among the list would do
    String jobName = jobNameList.get(0);
    //Button 1: Upload XML
    if (identifier.equals("Upload file")) {
        String jobFileName = jobFile.getOriginalFilename();
        //Check if file is empty or doesn't have an extension
        if (jobFile.isEmpty() || (jobFileName.lastIndexOf('.') < 0)) {
            model.addAttribute("XMLFileError", "File is Empty or invalid. Only .xml files can be uploaded");
        } else if (!jobFileName.substring(jobFileName.lastIndexOf('.')).equals(".xml")) {//Check if file is .xml
            model.addAttribute("XMLFileError", "Only .xml files can be uploaded");
        } else { //Read file to view
            byte[] buffer = jobFile.getBytes();
            XMLFileContents = new String(buffer);
            model.addAttribute("XMLFileContents", XMLFileContents);
        }
    } else if (identifier.equals("Upload dependency")) {
        //Button 2: Upload dependencies
        String depFileName = depFile.getOriginalFilename();
        if (depFile.isEmpty() || (depFileName.lastIndexOf('.') < 0)) {
            model.addAttribute("DepFileError", "File is Empty or invalid. Only .jar files can be uploaded");
        } else if (!depFileName.substring(depFileName.lastIndexOf('.')).equals(".jar")) { //Check if file is valid
            model.addAttribute("DepFileError", "Only .jar files can be uploaded");
        } else {//Move uploaded file
            //Check if file hasn't been added already
            if (jobConfigService.getJobDependencyList(jobName) != null
                    && jobConfigService.getJobDependencyList(jobName).contains(depFileName)) {
                model.addAttribute("DepFileError", "The filename is already added. Overwriting");
            }
            jobConfigService.addJobDependency(jobNameList, depFile.getOriginalFilename(), depFile.getBytes());
        }
    } else { //Button 3: Save. Overwrite the modified XML File
        LOGGER.info("Request to deploy jobConfig file for: " + jobNameList);
        try {
            //Set XML File
            this.jobConfigService.setJobConfig(jobNameList, new ByteArrayResource(XMLFileContents.getBytes()));
            this.jobConfigService.deployJob(jobNameList);
        } catch (Exception e) {
            LOGGER.info("Error while deploying job", e);
            //View: Add Error and rest of the attributes
            //Get stacktrace as string
            StringWriter errors = new StringWriter();
            e.printStackTrace(new PrintWriter(errors));
            model.addAttribute("LoadingError", errors.toString());
            if (errors.toString() == null) {
                model.addAttribute("LoadingError", "Unexpected error");
            }
            model.addAttribute("XMLFileContents", XMLFileContents.trim());
            model.addAttribute("jobName", jobNameList);
            if (jobConfigService.getJobDependencyList(jobName) != null) {
                model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName));
            }
            model.addAttribute("XMLFileContents", XMLFileContents.trim());
            //Redirect
            return "configuration/modify/jobs/job";
        }
        //Loading worked. Deploy to all hosts
        if (this.jobConfigService.getSyncService() != null)
            this.jobConfigService.getSyncService().deployJobToAllHosts(jobName);
        //Redirect to job configuration page. Load the view details
        model.addAttribute("SuccessMessage", "The job was successfully deployed!");
        model.addAttribute("jobName", jobName);
        //Push jobs to all servers
        if (jobConfigService.getJobDependencyList(jobName) != null) {
            model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName));
        }
        model.addAttribute("XMLFileContents", XMLFileContents.trim());
        String jobDirectory = this.jobConfigService.getJobStoreURI(jobName).getPath();
        model.addAttribute("JobDirectoryName",
                jobDirectory.substring(jobDirectory.lastIndexOf('/') + 1) + "/lib");
        return "configuration/jobs/job";
    }
    //Update the view
    model.addAttribute("jobName", jobNameList);
    if (jobConfigService.getJobDependencyList(jobName) != null) {
        model.addAttribute("dependencies", jobConfigService.getJobDependencyList(jobName));
    }
    model.addAttribute("XMLFileContents", XMLFileContents);
    //Redirect to modify page
    return "configuration/modify/jobs/job";
}

From source file:service.NoticeService.java

/**
 *  ?  ? /* ww  w .  j a va  2s .  c om*/
 *
 * @param draftId  ,    ??? ??
 * @param branch 
 * @param email 
 * @param subject 
 * @param message ?
 * @param files 
 * @return
 */
public ServiceResult addUserEmailNoticeByDraft(Long draftId, Branch branch, String email, String subject,
        String message, MultipartFile[] files) throws IOException {
    ServiceResult result = new ServiceResult();
    EmailNotice draftNotice = emailNoticeDao.find(draftId);
    draftNotice.setDraft(false);
    draftNotice.setBranch(branch);
    draftNotice.setSubject(subject);
    draftNotice.setMessage(message);
    draftNotice.setEmail(email);
    validateEmailNotice(draftNotice, result);
    if (!result.hasErrors()) {
        emailNoticeDao.update(draftNotice);
        if (files != null) {
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    EmailNoticeFile fileEnt = new EmailNoticeFile();
                    fileEnt.setEmailNotice(draftNotice);
                    saveFile(fileEnt, file);
                }
            }
        }
    }
    return result;
}

From source file:argendata.web.controller.DatasetController.java

@RequestMapping(method = RequestMethod.POST)
public ModelAndView bulkUpload(HttpSession session, BulkUploadForm bulkUploadForm, Errors err) {

    MultipartFile file = null;
    ModelAndView mav = new ModelAndView();

    file = bulkUploadForm.getFile();//from   www .j  a v  a 2s. c o  m

    validatorBulkUpload.validate(bulkUploadForm, err);
    if (err.hasErrors()) {
        return mav;
    }

    String error = null;

    if (file.isEmpty()) {

        logger.error("Escriba una ruta valida!");
        error = "Error. El archivo esta vacio.";
        mav.addObject("error", error);
        return mav;
    }

    int count = 0;

    /*
     * Titulo, Licencia, Tags (Separadas con ;),Calidad de la inforamcin,
     * Modificado, Granularidad Geografica, Granularidad Temporal,
     * Publicante, URL de Acceso, Tamao, Formato, Tipo de Distribucion,
     * locacion, descripcion
     */

    try {
        InputStream inputStream = file.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line;

        while ((line = bufferedReader.readLine()) != null) {
            if (line.isEmpty() || line.startsWith("#")) {
                continue; // es comentario o line en blanco
            }

            String[] attrs = line.split(";");

            if (attrs.length < 12) {
                throw new Exception("Linea " + (count + 1) + " mal formada.");
            }
            /* Titulo */
            String title = attrs[0].trim();

            /* Licence */
            String license = attrs[1].trim();

            /* Tags */
            Set<String> tags = new HashSet<String>();
            String[] items = attrs[2].split(",");
            int cantTags = 0;
            logger.debug(items.length);
            while (cantTags < items.length) {
                tags.add(items[cantTags].trim());
                cantTags++;
            }

            /* Quality of the Information */
            String qualityOfInformation = attrs[3].trim();
            if (!(qualityOfInformation.equals("Baja") || qualityOfInformation.equals("Media")
                    || qualityOfInformation.equals("Alta"))) {
                throw new Exception("Linea " + (count + 1) + " mal formada, calidad de informacion invalida");
            }

            /* Modify */
            String[] sels = attrs[4].split("-");

            if (sels.length < 3) {
                throw new Exception("Fecha invalidad en la linea " + (count + 1));
            }

            String yearModify = sels[0];
            String monthModify = sels[1];
            String dayModify = sels[2];

            dayModify = dayModify.length() == 1 ? "0" + dayModify : dayModify;
            monthModify = monthModify.length() == 1 ? "0" + monthModify : monthModify;

            /*
             * Date fechaModificado = Date.valueOf(anioModificado + "-" +
             * mesModificado + "-" + diaModificado);
             */
            // String fechaModificado = diaModificado + "-" + mesModificado
            // + "-" + anioModificado;
            String dateModify = yearModify + "-" + monthModify + "-" + dayModify + "T23:59:59Z";
            // String fechaModificado = "1995-12-31T23:59:59Z";
            /* Granularidad Geografica */
            String granuGeogra = attrs[5].trim();

            /* Granularidad Temporal */
            String granuTemporal = attrs[6].trim();

            /* Publicante */
            String publicante = attrs[7].trim();
            Organization miPublicante = new Organization();
            miPublicante.setName(publicante);
            miPublicante.setNameId(Parsing.withoutSpecialCharacters(publicante));

            /* URL de Acceso */
            String url = attrs[8].trim();

            /* Tamao */
            String tamanio = attrs[9].trim();

            /* Formato */
            String formato = attrs[10].trim();

            /* Tipo de Distribucion */
            Distribution distribution;

            String tipoDistribucion = attrs[11].trim();
            if (tipoDistribucion.equals("Feed")) {
                distribution = new Feed();
            } else if (tipoDistribucion.equals("Download")) {
                distribution = new Download();
            } else if (tipoDistribucion.equals("Web Service")) {
                distribution = new WebService();
            } else {
                throw new Exception("Linea " + (count + 1) + " mal formada, tipo informacion invalida");
            }
            distribution.setAccessURL(url);
            distribution.setFormat(formato);
            distribution.setSize(new Integer(tamanio));

            /* Locacion */
            String location = attrs[12].trim();
            if (location.equals("")) {
                location = "Desconocida";
            }

            /* Descripcion */
            String description = "";
            for (int i = 13; i < attrs.length; i++) {
                description = description + attrs[i];
                if (i != attrs.length - 1) {
                    description = description + "; ";
                }
            }

            Dataset aDataset = new Dataset(title, description, license, tags, qualityOfInformation, dateModify,
                    granuGeogra, granuTemporal, location, miPublicante, distribution,
                    Parsing.withoutSpecialCharacters(title));

            if (!datasetService.existApprovedDataset(title)) {
                datasetService.store(aDataset);
                count++;
            }
        }
    } catch (Exception a) {
        logger.error("Error en la carga masiva.");
        logger.error(a.getMessage(), a);
        error = a.getMessage();
        count = 0;
        mav.addObject("error", error);

    }

    if (count > 0) {
        mav.addObject("info", "Agrego " + count + " dataset's exitosamente.");
    }

    if (count == 0) {
        mav.addObject("info", "No haba datasets nuevos para agregar.");
    }
    return mav;
}

From source file:de.appsolve.padelcampus.admin.controller.general.AdminGeneralDesignController.java

@RequestMapping(method = POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ModelAndView postIndex(HttpServletRequest request,
        @RequestParam("backgroundImage") MultipartFile backgroundImage,
        @RequestParam(value = "backgroundImageRepeat", required = false, defaultValue = "false") Boolean backgroundImageRepeat,
        @RequestParam(value = "backgroundSizeCover", required = false, defaultValue = "false") Boolean backgroundSizeCover,
        @RequestParam(value = "loaderOpacity", required = false, defaultValue = "false") Boolean loaderOpacity,
        @RequestParam("companyLogo") MultipartFile companyLogo,
        @RequestParam("touchIcon") MultipartFile touchIcon) throws Exception {
    List<CssAttribute> atts = htmlResourceUtil.getCssAttributes();
    for (CssAttribute att : atts) {
        switch (att.getName()) {
        case "backgroundImage":
            if (!backgroundImage.isEmpty()) {
                StringBuilder sb = new StringBuilder("url(data:");
                sb.append(backgroundImage.getContentType());
                sb.append(";base64,");
                sb.append(Base64.encodeBase64String(backgroundImage.getBytes()));
                sb.append(")");
                att.setCssValue(sb.toString());
            }//from   ww  w. ja  va2s .c o m
            break;
        case "backgroundRepeat":
            if (backgroundImageRepeat) {
                att.setCssValue("repeat");
            } else {
                att.setCssValue("no-repeat");
            }
            break;
        case "backgroundSize":
            if (backgroundSizeCover) {
                att.setCssValue("cover");
            } else {
                att.setCssValue("inherit");
            }
            break;
        case "loaderOpacity":
            if (loaderOpacity) {
                att.setCssValue("@loaderOpacity: 1");
            } else {
                att.setCssValue("@loaderOpacity: 0");
            }
            break;
        default:
            att.setCssValue(request.getParameter(att.getName() + ""));
        }
        cssAttributeDAO.saveOrUpdate(att);
    }
    Customer customer = (Customer) sessionUtil.getCustomer(request);
    if (!companyLogo.isEmpty()) {

        //delete old picture from FS if it exists. will be removed from DB automatically due to orphanRemoval=true
        deleteImage(customer.getCompanyLogo());
        customer.setCompanyLogo(null);
        customerDAO.saveOrUpdate(customer);

        Image newImage = imageUtil.saveImage(companyLogo.getContentType(), companyLogo.getBytes(),
                ImageCategory.companyIcon);
        customer.setCompanyLogo(newImage);
        customer = customerDAO.saveOrUpdate(customer);
        sessionUtil.setCustomer(request, customer);
    }
    if (!touchIcon.isEmpty()) {
        //delete old picture from FS
        deleteImage(customer.getTouchIcon());
        customer.setTouchIcon(null);
        customerDAO.saveOrUpdate(customer);

        Image image = imageUtil.saveImage(touchIcon.getContentType(), touchIcon.getBytes(),
                Constants.TOUCH_ICON_WIDTH, Constants.TOUCH_ICON_HEIGHT, ImageCategory.touchIcon);
        customer.setTouchIcon(image);
        customer = customerDAO.saveOrUpdate(customer);
        sessionUtil.setCustomer(request, customer);
    }

    htmlResourceUtil.updateCss(request.getServletContext(), customer);
    return getIndexView(atts);
}

From source file:service.NoticeService.java

/**
 *  email-?//from www  .  j  a  v a2 s  .  co m
 *
 * @param notice ?
 * @param files 
 * @return
 * @throws IOException
 */
public ServiceResult addUserEmailNotice(EmailNotice notice, MultipartFile[] files) throws IOException {
    notice.setNoticeType(Notice.NoticeType.USER);
    notice.setNoticeDate(new Date());
    ServiceResult result = new ServiceResult();
    validateEmailNotice(notice, result);
    if (!result.hasErrors()) {
        saveUserNotice(notice, result);
        if (!result.hasErrors()) {
            if (files != null) {
                for (MultipartFile file : files) {
                    if (file != null && !file.isEmpty()) {
                        EmailNoticeFile fileEntity = new EmailNoticeFile();
                        fileEntity.setEmailNotice(notice);
                        saveFile(fileEntity, file);
                    }
                }
            }
        }
    }
    return result;
}

From source file:com.orchestra.portale.controller.NewDeepeningPageController.java

@RequestMapping(value = "/savedpage", method = RequestMethod.POST)
public ModelAndView savedpage(HttpServletRequest request, @RequestParam Map<String, String> params,
        @RequestParam("cover") MultipartFile cover, @RequestParam("file") MultipartFile[] files)
        throws InterruptedException {
    ModelAndView model = new ModelAndView("okpageadmin");

    DeepeningPage dp = new DeepeningPage();
    dp.setName(params.get("name"));
    System.out.println(params.get("name"));

    int i = 1;/*w w w .ja va  2  s .c  o  m*/
    ArrayList<String> categories = new ArrayList<String>();
    while (params.containsKey("category" + i)) {

        categories.add(params.get("category" + i));

        i = i + 1;
    }
    dp.setCategories(categories);

    ArrayList<AbstractPoiComponent> listComponent = new ArrayList<AbstractPoiComponent>();

    //componente cover
    if (!cover.isEmpty()) {
        CoverImgComponent coverimg = new CoverImgComponent();
        coverimg.setLink("cover.jpg");
        listComponent.add(coverimg);
    }
    //componente galleria immagini
    ArrayList<ImgGallery> links = new ArrayList<ImgGallery>();
    if (files.length > 0) {
        ImgGalleryComponent img_gallery = new ImgGalleryComponent();

        i = 0;
        while (i < files.length) {
            ImgGallery img = new ImgGallery();

            Thread.sleep(100);
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhmmssSSa");
            String currentTimestamp = sdf.format(date);
            img.setLink("img_" + currentTimestamp + ".jpg");
            if (params.containsKey("credit" + (i + 1))) {
                img.setCredit(params.get("credit" + (i + 1)));
            }

            i = i + 1;
            links.add(img);
        }
        img_gallery.setLinks(links);
        listComponent.add(img_gallery);
    }
    //DESCRIPTION COMPONENT
    i = 1;
    if (params.containsKey("par" + i)) {
        ArrayList<Section> list = new ArrayList<Section>();

        while (params.containsKey("par" + i)) {
            Section section = new Section();
            if (params.containsKey("titolo" + i)) {
                section.setTitle(params.get("titolo" + i));
            }
            section.setDescription(params.get("par" + i));
            list.add(section);
            i = i + 1;

        }
        DescriptionComponent description_component = new DescriptionComponent();
        description_component.setSectionsList(list);
        listComponent.add(description_component);
    }
    dp.setComponents(listComponent);

    pm.saveDeepeningPage(dp);

    DeepeningPage poi2 = pm.findDeepeningPageByName(dp.getName());

    for (int z = 0; z < files.length; z++) {
        MultipartFile file = files[z];

        try {
            byte[] bytes = file.getBytes();

            // Creating the directory to store file
            HttpSession session = request.getSession();
            ServletContext sc = session.getServletContext();

            File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                    + File.separator + poi2.getId());
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create the file on server
            File serverFile = new File(dir.getAbsolutePath() + File.separator + links.get(z).getLink());
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
            stream.write(bytes);
            stream.close();

        } catch (Exception e) {

            model.addObject("mess", "ERRORE!");
            return model;
        }
    }
    MultipartFile file = cover;

    try {
        byte[] bytes = file.getBytes();

        // Creating the directory to store file
        HttpSession session = request.getSession();
        ServletContext sc = session.getServletContext();

        File dir = new File(sc.getRealPath("/") + "dist" + File.separator + "dpage" + File.separator + "img"
                + File.separator + poi2.getId());
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // Create the file on server
        File serverFile = new File(dir.getAbsolutePath() + File.separator + "cover.jpg");
        BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
        stream.write(bytes);
        stream.close();

    } catch (Exception e) {

    }
    model.addObject("mess", "PAGINA INSERITA CORRETTAMENTE!");
    return model;
}

From source file:com.newline.view.company.controller.CompanyController.java

/**
 * //from   w w w  .j  av a 2 s.  c o m
 * ???
 * @param company
 * @param file
 * @return
 * @see 
 * @author  2015-9-15?11:17:34
 * @since 1.0
 */
@RequestMapping(value = "/saveOrUpdateCompanyBaseInfo", method = RequestMethod.POST)
public String saveOrUpdateCompanyBaseInfo(HttpServletRequest request,
        @RequestParam(value = "mylicense", required = false) MultipartFile file) {
    NlMemberEntity member = getMember(request);
    if (member != null) {
        NlCompanyEntity company = companyService.getCompanyByMemberid(member.getId());
        updateCompany(request, company);
        if (!file.isEmpty()) {
            String newfileName = QiNiuUtils.uploadImg(file);
            if (StringUtils.isNotBlank(company.getLicense())) {
                QiNiuUtils.delete(company.getLicense());
            }
            company.setLicense(newfileName);
        }
        companyService.updateCompany(company);
    } else {
        log.error("???.");
    }
    return "redirect:/company/goCompanyMainPage?type=baseinfo";
}

From source file:com.teasoft.teavote.controller.ElectionInfoController.java

@RequestMapping(value = "api/teavote/election-info", method = RequestMethod.POST)
@ResponseBody//from w w  w. j  a v a2s  .  c om
public JSONResponse saveElectionInfo(@RequestParam("logo") MultipartFile file,
        @RequestParam("commissioner") String commissioner, @RequestParam("orgName") String orgName,
        @RequestParam("electionDate") String electionDate, @RequestParam("startTime") String startTime,
        @RequestParam("endTime") String endTime, @RequestParam("pollingStation") String pollingStation,
        @RequestParam("startTimeInMillis") String startTimeInMillis,
        @RequestParam("endTimeInMillis") String endTimeInMillis, HttpServletRequest request) throws Exception {

    JSONResponse jSONResponse = new JSONResponse();
    //Candidate candidate = new Candidate();
    Map<String, String> errorMessages = new HashMap<>();

    if (!file.isEmpty()) {
        BufferedImage image = ImageIO.read(file.getInputStream());
        Integer width = image.getWidth();
        Integer height = image.getHeight();

        if (Math.abs(width - height) > MAX_IMAGE_DIM_DIFF) {
            errorMessages.put("image", "Invalid Image Dimension - Max abs(Width - height) must be 50 or less");
        } else {
            //Resize image
            BufferedImage originalImage = ImageIO.read(file.getInputStream());
            int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();

            BufferedImage resizeImagePng = resizeImage(originalImage, type);
            ConfigLocation configLocation = new ConfigLocation();
            //String rootPath = request.getSession().getServletContext().getRealPath("/");
            File serverFile = new File(configLocation.getConfigPath() + File.separator + "teavote-logo.jpg");

            switch (file.getContentType()) {
            case "image/png":
                ImageIO.write(resizeImagePng, "png", serverFile);
                break;
            case "image/jpeg":
                ImageIO.write(resizeImagePng, "jpg", serverFile);
                break;
            default:
                ImageIO.write(resizeImagePng, "png", serverFile);
                break;
            }
        }
    } else {
        //            errorMessages.put("image", "File Empty");
    }

    //Load properties
    Properties prop = appProp.getProperties();
    ConfigLocation configLocation = new ConfigLocation();
    prop.load(configLocation.getExternalProperties());

    prop.setProperty("teavote.orgName", orgName);
    prop.setProperty("teavote.commissioner", commissioner);
    prop.setProperty("teavote.electionDate", electionDate);
    prop.setProperty("teavote.startTime", startTime);
    prop.setProperty("teavote.endTime", endTime);
    prop.setProperty("teavote.pollingStation", pollingStation);
    prop.setProperty("teavote.startTimeInMillis", startTimeInMillis);
    prop.setProperty("teavote.endTimeInMillis", endTimeInMillis);

    File f = new File(configLocation.getConfigPath() + File.separator + "application.properties");
    OutputStream out = new FileOutputStream(f);
    DefaultPropertiesPersister p = new DefaultPropertiesPersister();
    p.store(prop, out, "Header Comment");

    if (errorMessages.isEmpty()) {
        return new JSONResponse(true, 0, null, Enums.JSONResponseMessage.SUCCESS.toString());
    }

    return new JSONResponse(false, 0, errorMessages, Enums.JSONResponseMessage.SERVER_ERROR.toString());
}