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:org.opentravel.pubs.controllers.AdminController.java

@RequestMapping({ "/DoUploadSpecification.html", "/DoUploadSpecification.htm" })
public String doUploadSpecificationPage(HttpSession session, Model model, RedirectAttributes redirectAttrs,
        @ModelAttribute("specificationForm") SpecificationForm specificationForm,
        @RequestParam(value = "archiveFile", required = false) MultipartFile archiveFile) {
    String targetPage = "uploadSpecification";
    try {//from  ww w .j ava  2s  .  c o  m
        if (specificationForm.isProcessForm()) {
            PublicationType publicationType = resolvePublicationType(specificationForm.getSpecType());
            PublicationState publicationState = (specificationForm.getPubState() == null) ? null
                    : PublicationState.valueOf(specificationForm.getPubState());
            Publication publication = new PublicationBuilder()
                    .setName(StringUtils.trimString(specificationForm.getName())).setType(publicationType)
                    .setState(publicationState).build();

            try {
                if (!archiveFile.isEmpty()) {
                    DAOFactoryManager.getFactory().newPublicationDAO().publishSpecification(publication,
                            archiveFile.getInputStream());

                    model.asMap().clear();
                    redirectAttrs.addAttribute("publication", publication.getName());
                    redirectAttrs.addAttribute("specType", publication.getType());
                    targetPage = "redirect:/admin/ViewSpecification.html";

                } else {
                    ValidationResults vResults = ModelValidator.validate(publication);

                    // An archive file must be provided on initial creation of a publication
                    vResults.add(publication, "archiveFilename", "Archive File is Required");

                    if (vResults.hasViolations()) {
                        throw new ValidationException(vResults);
                    }
                }

            } catch (ValidationException e) {
                addValidationErrors(e, model);

            } catch (Throwable t) {
                log.error("An error occurred while publishing the spec: ", t);
                setErrorMessage(t.getMessage(), model);
            }
        }

    } catch (Throwable t) {
        log.error("Error during publication controller processing.", t);
        setErrorMessage(DEFAULT_ERROR_MESSAGE, model);
    }
    return applyCommonValues(model, targetPage);
}

From source file:org.iti.agrimarket.view.AddOfferController.java

/**
 * Amr upload image and form data//ww  w  .  j  a va 2s. co  m
 *
 */
@RequestMapping(method = RequestMethod.POST, value = "/addoffer")
public String addOffer(@RequestParam("description") String description,
        @RequestParam("quantity") float quantity, @RequestParam("quantityunit") int quantityunit,
        @RequestParam("unitprice") int unitprice, @RequestParam("price") float price,
        @RequestParam("mobile") String mobile, @RequestParam("governerate") String governerate,
        @RequestParam("product") int product, @ModelAttribute("user") User userFromSession,
        @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes,
        HttpServletRequest request, HttpServletResponse response) {

    if (userFromSession == null) {
        return "login";
    } else {

        user = userFromSession;
    }

    System.out.println("save user func ---------");
    System.out.println("full Name :" + description);
    System.out.println("mobile:" + description);

    UserOfferProductFixed userOfferProductFixed = new UserOfferProductFixed();

    userOfferProductFixed.setDescription(description);
    userOfferProductFixed.setPrice(price);
    userOfferProductFixed.setRecommended(Boolean.FALSE);

    userOfferProductFixed.setQuantity(quantity);
    userOfferProductFixed.setProduct(productService.getProduct(product));
    userOfferProductFixed.setUnitByUnitId(unitService.getUnit(quantityunit));
    userOfferProductFixed.setUnitByPricePerUnitId(unitService.getUnit(unitprice));
    userOfferProductFixed.setUser(userService.getUser(user.getId()));
    userOfferProductFixed.setUserLocation(governerate);
    userOfferProductFixed.setUserPhone(mobile);
    userOfferProductFixed.setStartDate(new Date());

    int res = offerService.addOffer(userOfferProductFixed);

    if (!file.isEmpty()) {

        String fileName = userOfferProductFixed.getId() + String.valueOf(new Date().getTime());
        //
        //             
        try {

            System.out.println("fileName   :" + fileName);
            byte[] bytes = file.getBytes();
            MagicMatch match = Magic.getMagicMatch(bytes);
            final String ext = "." + match.getExtension();

            File parentDir = new File(Constants.IMAGE_PATH + Constants.OFFER_PATH);
            if (!parentDir.isDirectory()) {
                parentDir.mkdirs();
            }

            BufferedOutputStream stream = new BufferedOutputStream(
                    new FileOutputStream(new File(Constants.IMAGE_PATH + Constants.OFFER_PATH + fileName)));
            stream.write(bytes);

            stream.close();
            userOfferProductFixed.setImageUrl(Constants.IMAGE_PRE_URL + Constants.OFFER_PATH + fileName + ext);
            offerService.updateOffer(userOfferProductFixed);
        } catch (Exception e) {
            //                  logger.error(e.getMessage());
            offerService.deleteOffer(userOfferProductFixed.getId()); // delete the category if something goes wrong

            redirectAttributes.addFlashAttribute("message", "You failed to upload  because the file was empty");
            return "redirect:/web/addoffer.htm";
        }

    } else {

        userOfferProductFixed.setImageUrl(Constants.IMAGE_PRE_URL + Constants.OFFER_PATH + "default_offer.jpg");

        offerService.updateOffer(userOfferProductFixed);

    }

    User oldUser = (User) request.getSession().getAttribute("user");
    if (oldUser != null) {
        User user = userService.getUserEager(oldUser.getId());
        request.getSession().setAttribute("user", user);
    }
    return "redirect:/web/offers.htm";
}

From source file:edu.cmu.cs.lti.discoursedb.api.browsing.controller.BrowsingRestController.java

@RequestMapping(value = "/action/database/{databaseName}/uploadLightside", headers = "content-type=multipart/*", method = RequestMethod.POST)
@ResponseBody/*from  ww  w.  j  a v  a 2  s .c  o m*/
PagedResources<Resource<BrowsingLightsideStubsResource>> uploadLightside(
        @RequestParam("file_annotatedFileForUpload") MultipartFile file_annotatedFileForUpload,
        @PathVariable("databaseName") String databaseName, HttpServletRequest hsr, HttpSession session)
        throws IOException {
    registerDb(hsr, session, databaseName);
    String lsDataDirectory = lsDataDirectory();
    logger.info("Someone uploaded something!");
    if (!file_annotatedFileForUpload.isEmpty()) {
        try {
            logger.info("Not even empty!");
            File tempUpload = File.createTempFile("temp-file-name", ".csv");
            BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(tempUpload));
            FileCopyUtils.copy(file_annotatedFileForUpload.getInputStream(), stream);
            stream.close();
            lightsideService.importAnnotatedData(tempUpload.toString());
        } catch (Exception e) {
            logger.error("Error importing to lightside: " + e);
        }
    }
    return lightsideExports(databaseName, hsr, session);
}

From source file:com.prcsteel.platform.order.web.controller.cust.AccountController.java

@OpLog(OpType.SaveAccount)
@OpParam("account")
@RequestMapping(value = "/save", method = RequestMethod.POST)
@ResponseBody//ww w . j  av  a 2s .co m
public HashMap<String, Object> saveAccount(ModelMap out, MultipartHttpServletRequest request, Account account) {
    HashMap<String, Object> result = new HashMap<String, Object>();
    if (account.getName() != null)
        account.setName(account.getName().replaceAll(" ", ""));
    if (account.getTaxCode().length() > 20) {
        result.put("data", "?20??");
        return result;
    }
    try {
        AccountType.valueOf(account.getType());
    } catch (Exception e) {
        result.put("data", "??");
        return result;
    }

    if (account.getId() == null) {
        if ("".equals(account.getName().replaceAll(" ", ""))) {
            result.put("data", "?");
            return result;
        } else {
            account.setName(account.getName().replaceAll(" ", ""));
        }
        if (accountService.selectAccountByName(account.getName().replaceAll(" ", "")) != null) {
            result.put("data", "?" + account.getName().replaceAll(" ", "")
                    + "??????");
            return result;
        }
    }
    AccountDto dto = new AccountDto();
    MultipartFile license = request.getFile("pic_license");
    MultipartFile orgCode = request.getFile("pic_org_code");
    MultipartFile taxReg = request.getFile("pic_tax_reg");
    MultipartFile taxpayerEvidence = request.getFile("pic_taxpayer_evidence");
    MultipartFile invoiceData = request.getFile("pic_invoice_data");
    MultipartFile legalID = request.getFile("pic_legal_ID");
    MultipartFile paymentData = request.getFile("pic_payment_data");
    List<MultipartFile> consignContract = request.getFiles("pic_consign_contract");
    MultipartFile enterpriseSurvey = request.getFile("pic_enterprise_survey");
    MultipartFile openAccountLicense = request.getFile("pic_open_account_license");

    List<MultipartFile> attachmentList = new ArrayList<MultipartFile>();
    if (license != null && !license.isEmpty()) {
        if (!checkUploadAttachment(license, result, attachmentList)) {
            return result;
        }
    }
    if (orgCode != null && !orgCode.isEmpty()) {
        if (!checkUploadAttachment(orgCode, result, attachmentList)) {
            return result;
        }
    }
    if (taxpayerEvidence != null && !taxpayerEvidence.isEmpty()) {
        if (!checkUploadAttachment(taxpayerEvidence, result, attachmentList)) {
            return result;
        }
    }
    if (taxReg != null && !taxReg.isEmpty()) {
        if (!checkUploadAttachment(taxReg, result, attachmentList)) {
            return result;
        }
    }
    if (invoiceData != null && !invoiceData.isEmpty()) {
        if (!checkUploadAttachment(invoiceData, result, attachmentList)) {
            return result;
        }
    }
    if (legalID != null && !legalID.isEmpty()) {
        if (!checkUploadAttachment(legalID, result, attachmentList)) {
            return result;
        }
    }
    if (paymentData != null && !paymentData.isEmpty()) {
        if (!checkUploadAttachment(paymentData, result, attachmentList)) {
            return result;
        }
    }
    if (consignContract != null && !consignContract.isEmpty()) {
        // ?????
        for (MultipartFile file : consignContract) {
            if (!checkUploadAttachment(file, result, attachmentList)) {
                return result;
            }
        }
        account.setConsignType("consign");// ??
    } else {
        if (account.getId() == null) {
            account.setConsignType("temp");// 
        }
    }
    if (enterpriseSurvey != null && !enterpriseSurvey.isEmpty()) {
        if (!checkUploadAttachment(enterpriseSurvey, result, attachmentList)) {
            return result;
        }
    }
    if (openAccountLicense != null && !openAccountLicense.isEmpty()) {
        if (!checkUploadAttachment(openAccountLicense, result, attachmentList)) {
            return result;
        }
    }
    dto.setManager(getLoginUser());
    account.setLicenseCode(StringToReplace.toReplaceAll(account.getLicenseCode()));
    account.setRegAddress(StringToReplace.toReplaceAll(account.getRegAddress()));
    account.setOrgCode(StringToReplace.toReplaceAll(account.getOrgCode()));
    account.setBankCode(StringToReplace.toReplaceAll(account.getBankCode()));
    account.setBankNameMain(StringToReplace.toReplaceAll(account.getBankNameMain()));
    account.setBankNameBranch(StringToReplace.toReplaceAll(account.getBankNameBranch()));
    account.setAccountCode(StringToReplace.toReplaceAll(account.getAccountCode()));
    account.setTaxCode(StringToReplace.toReplaceAll(account.getTaxCode()));

    account.setName(Tools.toDBC(account.getName()));//???? modify by wangxianjun
    dto.setAccount(account);
    // 
    try {
        AccountContact contact = null;
        if (account.getId() == null || account.getType().equals(AccountType.both.toString())) {
            contact = new AccountContact();
            contact.setIsMain(Integer.valueOf(Constant.YES));
            // contact.setAccountId(account.getId());
            contact.setManager(getLoginUser().getId());
            contact.setStatus(Integer.valueOf(Constant.YES));
            if (account.getId() == null) {
                contact.setType(account.getType());
            } else {
                contact.setType(AccountType.seller.toString());
            }
            contact.setName(request.getParameter("contactName").toString());
            contact.setTel(request.getParameter("contactTel").toString());
            contact.setDeptName(StringUtils.isBlank(request.getParameter("contactDeptName").toString()) ? null
                    : request.getParameter("contactDeptName").toString());
            contact.setEmail(StringUtils.isBlank(request.getParameter("contactEmail").toString()) ? null
                    : request.getParameter("contactEmail").toString());
            contact.setQq(StringUtils.isBlank(request.getParameter("contactQq").toString()) ? null
                    : request.getParameter("contactQq").toString());
            contact.setNote(StringUtils.isBlank(request.getParameter("contactNote").toString()) ? null
                    : request.getParameter("contactNote").toString());
        }
        if (account.getId() == null) {
            result.put("success", true);
            result = accountService.insert(dto, attachmentList, contact);
        } else {
            result = accountService.updateByPrimaryKeySelective(dto, attachmentList, contact);
        }
    } catch (BusinessException e) {
        result.put("success", false);
        result.put("data", e.getMsg());
    }

    return result;
}

From source file:org.opentravel.pubs.controllers.AdminController.java

@RequestMapping({ "/DoUpdateCodeList.html", "/DoUpdateCodeList.htm" })
public String doUpdateCodeListPage(HttpSession session, Model model, RedirectAttributes redirectAttrs,
        @ModelAttribute("codeListForm") CodeListForm codeListForm,
        @RequestParam(value = "archiveFile", required = false) MultipartFile archiveFile) {
    String targetPage = "updateSpecification";
    try {/*from w  w w.ja  va2s .  c  o m*/
        if (codeListForm.isProcessForm()) {
            CodeListDAO cDao = DAOFactoryManager.getFactory().newCodeListDAO();
            CodeList codeList = cDao.getCodeList(codeListForm.getCodeListId());

            try {
                codeList.setReleaseDate(CodeList.labelFormat.parse(codeListForm.getReleaseDateLabel()));

                ValidationResults vResults = ModelValidator.validate(codeList);

                // Before we try to update the contents of the spefication, validate the
                // publication object to see if there are any errors.
                if (vResults.hasViolations()) {
                    throw new ValidationException(vResults);
                }

                if (!archiveFile.isEmpty()) {
                    cDao.updateCodeList(codeList, archiveFile.getInputStream());
                }
                model.asMap().clear();
                redirectAttrs.addAttribute("releaseDate", codeList.getReleaseDateLabel());
                targetPage = "redirect:/admin/ViewCodeList.html";

            } catch (ParseException e) {
                ValidationResults vResult = new ValidationResults();

                vResult.add(codeList, "releaseDate", "Invalid release date");
                addValidationErrors(vResult, model);

            } catch (ValidationException e) {
                addValidationErrors(e, model);

            } catch (Throwable t) {
                log.error("An error occurred while updating the spec: ", t);
                setErrorMessage(t.getMessage(), model);
            }
        }

    } catch (Throwable t) {
        log.error("Error during publication controller processing.", t);
        setErrorMessage(DEFAULT_ERROR_MESSAGE, model);
    }
    return applyCommonValues(model, targetPage);
}

From source file:eu.scidipes.toolkits.pawebapp.web.ItemsController.java

@RequestMapping(value = { "/edit", "/{formID}/edit", "/new" }, method = RequestMethod.POST)
public String saveItem(@ModelAttribute final SaveAction saveAction, @ModelAttribute final Form form,
        final BindingResult result, final SessionStatus status, final RedirectAttributes redirectAttrs,
        @RequestPart(value = "dataHolder", required = false) final MultipartFile dataFile,
        @MatrixVariable(value = "fn", required = false, pathVar = "datasetName") final String formName) {

    formValidator.validate(form, result);
    if (result.hasErrors()) {
        boolean fixErrors = true;

        final List<FieldError> dataHolderErrors = result.getFieldErrors("dataHolder");

        /*//from ww w.j  av a 2 s .c  om
         * Only ignore errors under very specific conditions, i.e. when there is a single no-file-supplied error and
         * a current file exists
         */
        if (result.getErrorCount() == 1 && dataHolderErrors != null && dataHolderErrors.size() == 1) {

            final FieldError dataHolderError = dataHolderErrors.get(0);
            if (FormValidator.FILE_REQ_ERR_CODE.equals(dataHolderError.getCode())
                    && !form.getDataHolderMetadata().isEmpty() && form.getDataHolderType() == BYTESTREAM) {
                fixErrors = false;
            }

        }

        if (fixErrors) {
            return "datasets/items/edit";
        }
    }

    /* Ensure that the dataHolder field is not overwritten when its an empty upload (i.e. re-save) */
    if (form.getDataHolderType() == BYTESTREAM && dataFile != null && !dataFile.isEmpty()) {
        LOG.debug("incoming dataFile: {}", dataFile);
        form.getDataHolderMetadata().put(FILE_NAME, dataFile.getOriginalFilename());
        form.getDataHolderMetadata().put(FILE_SIZE, String.valueOf(dataFile.getSize()));
        form.getDataHolderMetadata().put(FILE_MIMETYPE, dataFile.getContentType());
    } else if (form.getDataHolderType() == URI && !StringUtils.isEmpty(form.getDataHolder())) {
        LOG.debug("incoming dataHolder: {}", form.getDataHolder());
        form.getDataHolderMetadata().clear();
    }

    final FormsBundleImpl dataset = datasetRepo.findOne(form.getParentBundle().getDatasetName());

    if (saveAction == ADD_NEW) {
        dataset.addForm(form);
    } else {
        dataset.setForm(form);
    }

    final FormsBundle savedDataset = datasetRepo.save(dataset);
    final Form savedForm = savedDataset.getForms().get(savedDataset.getForms().indexOf(form));

    status.setComplete();
    redirectAttrs.addFlashAttribute("msgKey", "items.edit.messages.savesuccess");

    final String formNameMatrixVar = StringUtils.isEmpty(formName) ? "" : ";fn=" + formName;
    return "redirect:/datasets/" + savedDataset.getDatasetName() + formNameMatrixVar + "/items/"
            + savedForm.getFormID() + "/edit";
}

From source file:com.elecnor.ecosystem.serviceimpl.LicenseDirectoryServiceImpl.java

public HashMap<String, Object> uploadLocalLicFile(MultipartFile fileUploaded, HttpSession session,
        int confirmLocalLicUploadId) throws Exception {

    HashMap<String, Object> resultMap = new HashMap<String, Object>();
    Utility util = new Utility();
    ArrayList<ExcelErrorDetails> errorList = new ArrayList<ExcelErrorDetails>();
    ArrayList<LicenseDirectory> localLicenseList = new ArrayList<LicenseDirectory>();
    UploadFileUtility upUltil = new UploadFileUtility();
    LocalLicenseHelper LocalLicenseDirectoryHelper = new LocalLicenseHelper();

    boolean hasErrorOccured = false;
    boolean isValidSchema;
    int i;/*from   www . j  a  va  2 s  . c  o m*/

    UserDetail userDetail = (UserDetail) session.getAttribute("selectedUser");

    if (!fileUploaded.isEmpty()) {

        Workbook workBook = upUltil.readExcelFileFromMultipart(fileUploaded);
        if (workBook == null) {
            return upUltil.getErrorMessage(ConstantUtil.ERROR_FILE_READING_ERROR);
        }

        if (confirmLocalLicUploadId != 1) {
            isValidSchema = upUltil.isSchemaValid(workBook, ConstantUtil.LOCAL_LICENSE_SHEETNUM,
                    ConstantUtil.LOCAL_LICENSE_HEADER_ROWNUM, ConstantUtil.LOCAL_LICENSE_EXCEL_FORMAT);
            if (!isValidSchema) {
                return upUltil.getErrorMessage(ConstantUtil.ERROR_HEADER_VALIDATION_ERROR);
            }
        }
        Sheet sheet = workBook.getSheetAt(ConstantUtil.LOCAL_LICENSE_SHEETNUM);
        for (i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            if (row == null) {
                continue;
            }

            Map<String, Object> rowValidationResult = new HashMap<String, Object>();
            //if (confirmUploadId != 1) {
            rowValidationResult = LocalLicenseDirectoryHelper.validateRowDataAndFetchBean(row, userDetail);
            if (rowValidationResult.get("licenseDirectoryBean") == null) {
                errorList
                        .addAll((Collection<? extends ExcelErrorDetails>) rowValidationResult.get("errorList"));
                hasErrorOccured = true;
            } else {
                localLicenseList.add((LicenseDirectory) rowValidationResult.get("licenseDirectoryBean"));
            }
            //}
        }
        if ((confirmLocalLicUploadId == 1) || (confirmLocalLicUploadId != 1 && !hasErrorOccured)) {
            errorList = saveLocalLicenseList(localLicenseList);
            if (errorList.isEmpty()) {
                errorList = null;
            }
            return util.responseBuilder(errorList);

        } else {

            return util.responseBuilder(errorList);
        }

    }
    //         Workbook workBook = null;
    //         try {
    //            workBook = new XSSFWorkbook(fileUploaded.getInputStream());
    //         } catch (Exception e) {
    //            try {
    //               workBook = new HSSFWorkbook(fileUploaded.getInputStream());
    //            } catch (IOException e1) {
    //            }
    //         }
    //         if (workBook == null) {
    //            localLicErrorList.add(getExcelErrorDetails(0, 0, "Wrong File Type"));
    //            resultMap.put("ajaxResult", "error");
    //            resultMap.put("reason", localLicErrorList);
    //            return resultMap;
    //         }
    //         // Schema Validation - Checks Whether Row header name is same as we
    //         // specified.
    //         isValidSchema = getLocalSchemaValidation(workBook);
    //         if (isValidSchema != 1) {
    //            hasErrorOccured = true;
    //            localLicErrorList.add(getExcelErrorDetails(0, 0, "Header Validation Failed"));
    //            resultMap.put("ajaxResult", "error");
    //            resultMap.put("reason", localLicErrorList);
    //            return resultMap;
    //         }
    //         // Schema Validation Ends
    //
    //         // Data Validation Starts
    //         sheetStart = readFromLocalHeader(null, stringSheetStart);
    //         Sheet sheet = workBook.getSheetAt(sheetStart);
    //         for (i = 1; i <= sheet.getLastRowNum(); i++) {
    //            Row row = sheet.getRow(i);
    //            if (row == null) {
    //               continue;
    //            }
    //            if (confirmLocalLicUploadId != 1) {
    //               ArrayList<ExcelErrorDetails> rowErrorDetailList = new ArrayList<ExcelErrorDetails>();
    //               rowErrorDetailList = validateLocalRowData(row);
    //               if (rowErrorDetailList != null) {
    //                  localLicErrorList.addAll(rowErrorDetailList);
    //                  hasErrorOccured = true;
    //               }
    //            }
    //            if ((confirmLocalLicUploadId != 1 && !hasErrorOccured) || confirmLocalLicUploadId == 1) {
    //               localLicenseList.add(getLocalLicenseDetails(row, domainDetail, userDetail));
    //            }
    //         }
    //         if ((confirmLocalLicUploadId == 1) || (confirmLocalLicUploadId != 1 && !hasErrorOccured)) {
    //            localLicErrorList = saveLocalLicenseList(localLicenseList);
    //            if (localLicErrorList.isEmpty()) {
    //               resultMap.put("ajaxResult", "success");
    //               resultMap.put("reason", null);
    //            } else {
    //               resultMap.put("ajaxResult", "error");
    //               resultMap.put("reason", localLicErrorList);
    //            }
    //         } else {
    //            resultMap.put("ajaxResult", "error");
    //            resultMap.put("reason", localLicErrorList);
    //
    //         }
    //
    //      } else {
    //         resultMap.put("ajaxResult", "error");
    //         resultMap
    //               .put("reason",
    //                     "Cannot Find the excel file. Please refresh the page and try again. If this problem persists report it to Dev. Team.");
    //
    //      }
    return resultMap;
}

From source file:com.elecnor.ecosystem.serviceimpl.LicenseDirectoryServiceImpl.java

@SuppressWarnings("unchecked")
public HashMap<String, Object> uploadStateLicFile(MultipartFile fileUploaded, HttpSession session,
        int confirmStateLicUploadId) throws Exception {

    HashMap<String, Object> resultMap = new HashMap<String, Object>();
    ArrayList<ExcelErrorDetails> stateLicErrorList = new ArrayList<ExcelErrorDetails>();
    ArrayList<LicenseDirectory> stateLicenseList = new ArrayList<LicenseDirectory>();
    UploadFileUtility upUltil = new UploadFileUtility();
    StateLicenseHelper stateLicenseHelper = new StateLicenseHelper();
    boolean hasErrorOccured = false;
    boolean isValidSchema;
    int i;//from   ww  w .j  av a 2 s  . com

    Utility util = new Utility();
    UserDetail userDetail = (UserDetail) session.getAttribute("selectedUser");

    try {
        if (!fileUploaded.isEmpty()) {

            Workbook workBook = upUltil.readExcelFileFromMultipart(fileUploaded);
            if (workBook == null) {
                return upUltil.getErrorMessage(ConstantUtil.ERROR_FILE_READING_ERROR);
            }
            if (confirmStateLicUploadId != 1) {
                isValidSchema = upUltil.isSchemaValid(workBook, ConstantUtil.STATE_LICENSE_SHEETNUM,
                        ConstantUtil.STATE_LICENSE_HEADER_ROWNUM, ConstantUtil.STATE_LICENSE_EXCEL_FORMAT);
                if (!isValidSchema) {
                    return upUltil.getErrorMessage(ConstantUtil.ERROR_HEADER_VALIDATION_ERROR);
                }
            }
            Sheet sheet = null;
            try {
                sheet = workBook.getSheetAt(ConstantUtil.STATE_LICENSE_SHEETNUM);
            } catch (Exception e) {
                e.printStackTrace();
            }
            for (i = 1; i <= sheet.getLastRowNum(); i++) {
                System.out.println(i);
                Row row = sheet.getRow(i);
                if (row == null) {
                    continue;
                }
                Map<String, Object> rowValidationResult = new HashMap<String, Object>();
                //if (confirmUploadId != 1) {
                rowValidationResult = stateLicenseHelper.validateRowDataAndFetchBean(row, userDetail);
                if (rowValidationResult.get("licenseDirectoryBean") == null) {
                    stateLicErrorList.addAll(
                            (Collection<? extends ExcelErrorDetails>) rowValidationResult.get("errorList"));
                    hasErrorOccured = true;
                } else {
                    stateLicenseList.add((LicenseDirectory) rowValidationResult.get("licenseDirectoryBean"));
                }
            }

            if ((confirmStateLicUploadId == 1) || (confirmStateLicUploadId != 1 && !hasErrorOccured)) {
                stateLicErrorList = saveStateLicenseList(stateLicenseList);
                if (stateLicErrorList.isEmpty()) {
                    stateLicErrorList = null;
                }
                return util.responseBuilder(stateLicErrorList);

            } else {

                return util.responseBuilder(stateLicErrorList);
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw e;
    }
    return resultMap;
    //         try {
    //            workBook = new XSSFWorkbook(fileUploaded.getInputStream());
    //         } catch (Exception e) {
    //            try {
    //               workBook = new HSSFWorkbook(fileUploaded.getInputStream());
    //            } catch (IOException e1) {
    //            }
    //         }
    //         if (workBook == null) {
    //            stateLicErrorList.add(getExcelErrorDetails(0, 0, "Wrong File Type"));
    //            resultMap.put("ajaxResult", "error");
    //            resultMap.put("reason", stateLicErrorList);
    //            return resultMap;
    //         }
    //         // Schema Validation - Checks Whether Row header name is same as we
    //         // specified.
    //         isValidSchema = getSchemaValidation(workBook);
    //         if (isValidSchema != 1) {
    //            hasErrorOccured = true;
    //            stateLicErrorList.add(getExcelErrorDetails(0, 0, "Header Validation Failed"));
    //            resultMap.put("ajaxResult", "error");
    //            resultMap.put("reason", stateLicErrorList);
    //            return resultMap;
    //         }
    //
    //         // Schema Validation Ends
    //
    //         // Data Validation Starts
    //         sheetStart = readFromHeader(null, stringSheetStart);
    //         Sheet sheet = workBook.getSheetAt(sheetStart);
    //         for (i = 1; i <= sheet.getLastRowNum(); i++) {
    //            Row row = sheet.getRow(i);
    //            if (row == null) {
    //               continue;
    //            }
    //            if (confirmStateLicUploadId != 1) {
    //               ArrayList<ExcelErrorDetails> rowErrorDetailList = new ArrayList<ExcelErrorDetails>();
    //               rowErrorDetailList = validateRowData(row);
    //               if (rowErrorDetailList != null) {
    //                  stateLicErrorList.addAll(rowErrorDetailList);
    //                  hasErrorOccured = true;
    //               }
    //            }
    //            if ((confirmStateLicUploadId != 1 && !hasErrorOccured) || confirmStateLicUploadId == 1) {
    //               stateLicenseList.add(getStateLicenseDetails(row, domainDetail, userDetail));
    //            }
    //         }
    //         if ((confirmStateLicUploadId == 1) || (confirmStateLicUploadId != 1 && !hasErrorOccured)) {
    //            stateLicErrorList = saveStateLicenseList(stateLicenseList);
    //            if (stateLicErrorList.isEmpty()) {
    //               resultMap.put("ajaxResult", "success");
    //               resultMap.put("reason", null);
    //            } else {
    //               resultMap.put("ajaxResult", "error");
    //               resultMap.put("reason", stateLicErrorList);
    //            }
    //         } else {
    //            resultMap.put("ajaxResult", "error");
    //            resultMap.put("reason", stateLicErrorList);
    //
    //         }
    //
    //      } else {
    //         resultMap.put("ajaxResult", "error");
    //         resultMap
    //               .put("reason",
    //                     "Cannot Find the excel file. Please refresh the page and try again. If this problem persists report it to Dev. Team.");
    //
    //      }
    //      return resultMap;
}

From source file:org.openmrs.module.dhisconnector.api.impl.DHISConnectorServiceImpl.java

@Override
public String uploadDHIS2APIBackup(MultipartFile dhis2APIBackup) {
    String msg = "";
    String outputFolder = OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_TEMP_FOLDER;
    File temp = new File(outputFolder);
    File dhis2APIBackupRootDir = new File(
            OpenmrsUtil.getApplicationDataDirectory() + DHISCONNECTOR_DHIS2BACKUP_FOLDER);

    if (!temp.exists()) {
        temp.mkdirs();/*from   w ww  .  j  av a 2 s  .co  m*/
    }

    File dest = new File(outputFolder + File.separator + dhis2APIBackup.getOriginalFilename());

    if (!dhis2APIBackup.isEmpty() && dhis2APIBackup.getOriginalFilename().endsWith(".zip")) {
        try {
            dhis2APIBackup.transferTo(dest);

            if (dest.exists() && dest.isFile()) {
                File unzippedAt = new File(outputFolder + File.separator + "api");
                File api = new File(dhis2APIBackupRootDir.getPath() + File.separator + "api");

                unZipDHIS2APIBackupToTemp(dest.getCanonicalPath());
                if ((new File(outputFolder)).list().length > 0 && unzippedAt.exists()) {
                    if (!dhis2APIBackupRootDir.exists()) {
                        dhis2APIBackupRootDir.mkdirs();
                    }

                    if (FileUtils.sizeOfDirectory(dhis2APIBackupRootDir) > 0 && unzippedAt.exists()
                            && unzippedAt.isDirectory()) {
                        if (checkIfDirContainsFile(dhis2APIBackupRootDir, "api")) {

                            FileUtils.deleteDirectory(api);
                            api.mkdir();
                            msg = Context.getMessageSourceService()
                                    .getMessage("dhisconnector.dhis2backup.replaceSuccess");
                        } else {
                            msg = Context.getMessageSourceService()
                                    .getMessage("dhisconnector.dhis2backup.import.success");
                        }
                        FileUtils.copyDirectory(unzippedAt, api);
                        FileUtils.deleteDirectory(temp);
                    }
                }
            }
        } catch (IllegalStateException e) {
            msg = Context.getMessageSourceService().getMessage("dhisconnector.dhis2backup.failure");
            e.printStackTrace();
        } catch (IOException e) {
            msg = Context.getMessageSourceService().getMessage("dhisconnector.dhis2backup.failure");
            e.printStackTrace();
        }
    } else {
        msg = Context.getMessageSourceService().getMessage("dhisconnector.dhis2backup.failure");
    }

    return msg;
}

From source file:com.siblinks.ws.service.impl.UploadEssayServiceImpl.java

/**
 * {@inheritDoc}// ww  w  . j a v  a  2s  .com
 */
@Override
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity<Response> upload(@RequestParam("name") final String name,
        @RequestParam("userId") final String userId, @RequestParam("userType") final String userType,
        @RequestParam("file") final MultipartFile file) {
    SimpleResponse simpleResponse = null;
    boolean status = true;
    String statusMessage = null;
    try {

        if (!AuthenticationFilter.isAuthed(context)) {
            simpleResponse = new SimpleResponse(SibConstants.FAILURE, "Authentication required.");
            return new ResponseEntity<Response>(simpleResponse, HttpStatus.FORBIDDEN);
        }

        if (!file.isEmpty()) {
            ResponseEntity<Response> msg = uploadFile(file);

            String urlFile = (String) msg.getBody().getRequest_data_result();
            String review = env.getProperty("directoryReviewDefaultUploadEssay");

            if (msg.getBody().getStatus() == "true") {

                boolean msgs = true;
                if ("S".equalsIgnoreCase(userType)) {
                    Object[] queryParams = { userId, name, file.getOriginalFilename(), "" + file.getSize(),
                            file.getContentType(), urlFile, review };
                    msgs = dao.upload(SibConstants.SqlMapper.SQL_STUDENT_UPLOAD, queryParams, file);
                } else if ("M".equalsIgnoreCase(userType)) {
                    Object[] queryParamsM = { "" + userId, file.getSize() };
                    dao.upload(SibConstants.SqlMapper.SQL_MENTOR_UPLOAD, queryParamsM, file);
                }
                if (msgs) {
                    statusMessage = "Done";
                } else {
                    status = false;
                    statusMessage = "You failed to upload ";
                }
            } else {
                status = false;
                statusMessage = (String) msg.getBody().getRequest_data_result();
            }
        } else {
            status = false;
            statusMessage = "You failed to upload " + name + " because the file was empty.";
        }
    } catch (Exception e) {
        e.printStackTrace();
        status = false;
        statusMessage = "You failed to upload " + name + " => " + e.getMessage();
        logger.error(e.getMessage(), e.getCause());
    }

    simpleResponse = new SimpleResponse("" + status, "essay", "upload", statusMessage);
    return new ResponseEntity<Response>(simpleResponse, HttpStatus.OK);
}