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:com.ut.healthelink.service.impl.transactionInManagerImpl.java

/**
 * The 'uploadAttachment' function will take in the file and orgName and upload the file to the appropriate file on the file system.
 *
 * @param fileUpload The file to be uploaded
 * @param orgName The organization name that is uploading the file. This will be the folder where to save the file to.
 *///from  w w  w. j  a  v  a  2 s. c  o  m
@Override
public String uploadAttachment(MultipartFile fileUpload, String orgName) throws Exception {

    MultipartFile file = fileUpload;
    String fileName = file.getOriginalFilename();

    InputStream inputStream = null;
    OutputStream outputStream = null;

    try {
        inputStream = file.getInputStream();
        File newFile = null;

        //Set the directory to save the brochures to
        fileSystem dir = new fileSystem();
        dir.setDir(orgName, "attachments");

        newFile = new File(dir.getDir() + fileName);

        if (newFile.exists()) {
            int i = 1;
            while (newFile.exists()) {
                int iDot = fileName.lastIndexOf(".");
                newFile = new File(dir.getDir() + fileName.substring(0, iDot) + "_(" + ++i + ")"
                        + fileName.substring(iDot));
            }
            fileName = newFile.getName();
        } else {
            newFile.createNewFile();
        }

        outputStream = new FileOutputStream(newFile);
        int read = 0;
        byte[] bytes = new byte[1024];

        while ((read = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, read);
        }
        outputStream.close();

        //Save the attachment
    } catch (IOException e) {
        e.printStackTrace();
    }

    return fileName;
}

From source file:com.jd.survey.web.settings.InvitationController.java

/**
 * Sends email invitations to the list of invitees from csv file.  
 * @param file/*from   w w w . j  a v  a 2s  .c  om*/
 * @param surveyDefinitionId
 * @param proceed
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@SuppressWarnings("unchecked")
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html")
public String sendInvitations(@RequestParam("file") MultipartFile file,
        @RequestParam("id") Long surveyDefinitionId,
        @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    try {
        short firstNameFieldIndex = 0;
        short middleNameFieldIndex = 1;
        short lastNameFieldIndex = 2;
        short emailNameFieldIndex = 3;

        if (proceed != null) {
            //prepare the base url links
            String emailSubject = messageSource.getMessage(INVITATION_EMAIL_TITLE, null,
                    LocaleContextHolder.getLocale());
            //String surveyLink =messageSource.getMessage(EXTERNAL_SITE_BASE_URL, null, LocaleContextHolder.getLocale());
            String surveyLink = externalBaseUrl;
            //String trackingImageLink =messageSource.getMessage(INTERNAL_SITE_BASE_URL, null, LocaleContextHolder.getLocale());
            String trackingImageLink = internalBaseUrl;

            SurveyDefinition surveyDefinition = surveySettingsService
                    .surveyDefinition_findById(surveyDefinitionId);

            User user = userService.user_findByLogin(principal.getName());
            Set<SurveyDefinition> surveyDefinitions = surveySettingsService
                    .surveyDefinition_findAllCompletedInternal(user);
            //Check if the user is authorized
            if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
                log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                        + " attempted by user login:" + principal.getName() + "from IP:"
                        + httpServletRequest.getLocalAddr());
                return "accessDenied";
            }

            if (trackingImageLink.endsWith("/")) {
                trackingImageLink = trackingImageLink + "public/w/";
            } else {
                trackingImageLink = trackingImageLink + "/public/w/";
            }

            if (surveyDefinition.getIsPublic()) {
                if (surveyLink.endsWith("/")) {
                    surveyLink = surveyLink + "open/";
                } else {
                    surveyLink = surveyLink + "/open/";
                }
            } else {
                if (surveyLink.endsWith("/")) {
                    surveyLink = surveyLink + "private/";
                } else {
                    surveyLink = surveyLink + "/private/";
                }
            }

            String emailContent;

            if (!file.isEmpty() && ((file.getContentType().equalsIgnoreCase("application/vnd.ms-excel"))
                    || (file.getContentType().equalsIgnoreCase("text/csv"))
                    || (file.getContentType().equalsIgnoreCase("text/plain")))) {
                CSVReader csvReader = new CSVReader(new InputStreamReader(file.getInputStream()));
                String[] nextLine;
                nextLine = csvReader.readNext(); //skip the first row the continue on with loop

                while ((nextLine = csvReader.readNext()) != null) {
                    emailContent = "";
                    StringWriter sw = new StringWriter();

                    // Prevents IndexOutOfBoundException by skipping line if there are not enough elements in the array nextLine. 
                    if (nextLine.length < 4) {
                        //Continues if a blank line is present without setting an error message (if a new line character is present CSVReader will return and array with one empty string at index 0).
                        if (nextLine.length == 1 && nextLine[0].isEmpty()) {
                            continue;
                        }
                        uiModel.addAttribute("fileContentError", true);
                        continue;
                    }
                    //Prevents exception from attempting to send an email with an empty string for an email address.
                    if (nextLine[3].isEmpty()) {
                        uiModel.addAttribute("fileContentError", true);
                        continue;
                    }
                    //creating the Invitation
                    Invitation invitation = new Invitation(nextLine[firstNameFieldIndex].trim(),
                            nextLine[middleNameFieldIndex].trim(), nextLine[lastNameFieldIndex].trim(),
                            nextLine[emailNameFieldIndex].trim(), surveyDefinition);

                    Map model = new HashMap();
                    //survey name
                    model.put(messageSource.getMessage(SURVEY_NAME, null, LocaleContextHolder.getLocale())
                            .replace("${", "").replace("}", ""), surveyDefinition.getName());
                    //full name
                    model.put(
                            messageSource.getMessage(INVITEE_FULLNAME_PARAMETER_NAME, null,
                                    LocaleContextHolder.getLocale()).replace("${", "").replace("}", ""),
                            invitation.getFullName());
                    //survey link
                    model.put(
                            messageSource.getMessage(INVITE_FILL_SURVEY_LINK_PARAMETER_NAME, null,
                                    LocaleContextHolder.getLocale()).replace("${", "").replace("}", ""),
                            "<a href='" + surveyLink + surveyDefinition.getId() + "?list'>"
                                    + messageSource.getMessage(INVITE_FILL_SURVEY_LINK_LABEL, null,
                                            LocaleContextHolder.getLocale())
                                    + "</a>");

                    VelocityContext velocityContext = new VelocityContext(model);
                    Velocity.evaluate(velocityContext, sw, "velocity-log",
                            surveyDefinition.getEmailInvitationTemplate());
                    emailContent = sw.toString().trim();

                    if (emailContent.length() > 14 && emailContent.substring(emailContent.length() - 14)
                            .toUpperCase().equalsIgnoreCase("</BODY></HTML>")) {
                        emailContent = emailContent.substring(0, emailContent.length() - 14) + "<img src='"
                                + trackingImageLink + invitation.getUuid() + "'/></BODY></HTML>";
                        emailContent = "<BODY><HTML>" + emailContent;
                    } else {
                        // template is incorrect or not html do not include tracking white gif
                        emailContent = emailContent + "<img src='" + trackingImageLink + invitation.getUuid()
                                + "'/></BODY></HTML>";

                    }

                    surveySettingsService.invitation_send(invitation, emailSubject, emailContent);
                }

                return "redirect:/settings/invitations/list?id="
                        + encodeUrlPathSegment(surveyDefinitionId.toString(), httpServletRequest);
            } else {
                uiModel.addAttribute("surveyDefinitions", surveyDefinitions);
                uiModel.addAttribute("surveyDefinition", surveyDefinition);
                uiModel.addAttribute("emptyFileError", true);
                return "settings/invitations/upload";
            }
        } else {
            return "redirect:/settings/invitations/list?id="
                    + encodeUrlPathSegment(surveyDefinitionId.toString(), httpServletRequest);
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:fr.univrouen.poste.web.candidat.MyPosteCandidatureController.java

@RequestMapping(value = "/{id}/addFile", method = RequestMethod.POST, produces = "text/html")
@PreAuthorize("hasPermission(#id, 'manage')")
public String addFile(@PathVariable("id") Long id, @Valid PosteCandidatureFile posteCandidatureFile,
        BindingResult bindingResult, Model uiModel, HttpServletRequest request) throws IOException {
    if (bindingResult.hasErrors()) {
        logger.warn(bindingResult.getAllErrors());
        return "redirect:/postecandidatures/" + id.toString();
    }/*  ww w .  ja  v  a  2 s.  c om*/
    uiModel.asMap().clear();

    // get PosteCandidature from id
    PosteCandidature posteCandidature = PosteCandidature.findPosteCandidature(id);

    // upload file
    MultipartFile file = posteCandidatureFile.getFile();

    // sometimes file is null here, but I don't know how to reproduce this issue ... maybe that can occur only with some specifics browsers ?
    if (file != null) {
        String filename = file.getOriginalFilename();

        boolean filenameAlreadyUsed = false;
        for (PosteCandidatureFile pcFile : posteCandidature.getCandidatureFiles()) {
            if (pcFile.getFilename().equals(filename)) {
                filenameAlreadyUsed = true;
                break;
            }
        }

        if (filenameAlreadyUsed) {
            uiModel.addAttribute("filename_already_used", filename);
            logger.warn("Upload Restriction sur '" + filename
                    + "' un fichier de mme nom existe dj pour une candidature de "
                    + posteCandidature.getCandidat().getEmailAddress());
        } else {

            Long fileSize = file.getSize();

            if (fileSize != 0) {
                String contentType = file.getContentType();
                // cf https://github.com/EsupPortail/esup-dematec/issues/8 - workaround pour viter mimetype erron comme application/text-plain:formatted
                contentType = contentType.replaceAll(":.*", "");

                logger.info("Try to upload file '" + filename + "' with size=" + fileSize + " and contentType="
                        + contentType);

                Long maxFileMoSize = posteCandidatureFile.getFileType().getCandidatureFileMoSizeMax();
                Long maxFileSize = maxFileMoSize * 1024 * 1024;
                String mimeTypeRegexp = posteCandidatureFile.getFileType()
                        .getCandidatureContentTypeRestrictionRegexp();
                String filenameRegexp = posteCandidatureFile.getFileType()
                        .getCandidatureFilenameRestrictionRegexp();

                boolean sizeRestriction = maxFileSize > 0 && fileSize > maxFileSize;
                boolean contentTypeRestriction = !contentType.matches(mimeTypeRegexp);
                boolean filenameRestriction = !filename.matches(filenameRegexp);

                if (sizeRestriction || contentTypeRestriction || filenameRestriction) {
                    String restriction = sizeRestriction ? "SizeRestriction" : "";
                    restriction = contentTypeRestriction || filenameRestriction
                            ? restriction + "ContentTypeRestriction"
                            : restriction;
                    uiModel.addAttribute("upload_restricion_size_contentype", restriction);
                    logger.info("addFile - upload restriction sur " + filename + "' avec taille=" + fileSize
                            + " et contentType=" + contentType + " pour une candidature de "
                            + posteCandidature.getCandidat().getEmailAddress());
                } else {
                    InputStream inputStream = file.getInputStream();
                    //byte[] bytes = IOUtils.toByteArray(inputStream);

                    posteCandidatureFile.setFilename(filename);
                    posteCandidatureFile.setFileSize(fileSize);
                    posteCandidatureFile.setContentType(contentType);
                    logger.info("Upload and set file in DB with filesize = " + fileSize);
                    posteCandidatureFile.getBigFile().setBinaryFileStream(inputStream, fileSize);
                    posteCandidatureFile.getBigFile().persist();

                    Calendar cal = Calendar.getInstance();
                    Date currentTime = cal.getTime();
                    posteCandidatureFile.setSendTime(currentTime);

                    posteCandidature.getCandidatureFiles().add(posteCandidatureFile);

                    posteCandidature.setModification(currentTime);

                    posteCandidature.persist();

                    logService.logActionFile(LogService.UPLOAD_ACTION, posteCandidature, posteCandidatureFile,
                            request, currentTime);
                    returnReceiptService.logActionFile(LogService.UPLOAD_ACTION, posteCandidature,
                            posteCandidatureFile, request, currentTime);

                    pdfService.updateNbPages(posteCandidatureFile.getId());
                }
            }
        }
    } else {
        String userId = SecurityContextHolder.getContext().getAuthentication().getName();
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        logger.warn(userId + "[" + ip + "] tried to add a 'null file' ... his userAgent is : " + userAgent);
    }

    return "redirect:/postecandidatures/" + id.toString();
}

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

/**
 * {@inheritDoc}//  w  w  w .j  a  v a 2 s.c om
 */
@Override
@RequestMapping(value = "/insertUpdateCommentEssay", method = RequestMethod.POST)
public ResponseEntity<Response> insertUpdateCommentEssay(
        @RequestParam(required = false) final MultipartFile file, @RequestParam final long essayId,
        @RequestParam final long mentorId, @RequestParam(required = false) final Long studentId,
        @RequestParam final String comment, @RequestParam(required = false) final Long commentId,
        @RequestParam(required = false) final String fileOld, @RequestParam final boolean isUpdate) {
    SimpleResponse reponse = null;
    TransactionStatus status = null;
    try {
        if (comment != null && comment.length() > 1000) {
            reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay",
                    "Content can not longer than 1000 characters");
        } else {
            boolean flag = false;
            Object[] params = null;
            TransactionDefinition def = new DefaultTransactionDefinition();
            status = transactionManager.getTransaction(def);
            String statusMsg = validateEssay(file);
            if (statusMsg.equals("Error Format")) {
                reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay",
                        "Your file is not valid.");
            } else if (statusMsg.equals("File over 10M")) {
                reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay",
                        "Your file is lager than 10MB.");
            } else if (statusMsg.equals("File name is not valid")) {
                reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay",
                        "File name is not valid.");
            } else {
                // Word filter content
                List<Map<String, String>> allWordFilter = cachedDao.getAllWordFilter();
                String strContent = CommonUtil.filterWord(comment, allWordFilter);
                String strFileName = CommonUtil.filterWord((file != null) ? file.getOriginalFilename() : null,
                        allWordFilter);

                if (!isUpdate) {
                    params = new Object[] { "", mentorId, strContent };
                    long cid = dao.insertObject(SibConstants.SqlMapper.SQL_SIB_ADD_COMMENT, params);
                    params = new Object[] { essayId, cid };
                    flag = dao.insertUpdateObject(SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_FK,
                            params);
                    if (StringUtil.isNull(statusMsg)) {
                        params = new Object[] { mentorId, file.getInputStream(), file.getSize(), strFileName,
                                essayId };
                        flag = dao.insertUpdateObject(
                                SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_WITH_FILE, params);
                    } else {
                        params = new Object[] { mentorId, essayId };
                        flag = dao.insertUpdateObject(
                                SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_WITHOUT_FILE, params);
                    }
                    if (flag) {
                        String contentNofi = strContent;
                        if (!StringUtil.isNull(strContent)
                                && strContent.length() > Parameters.MAX_LENGTH_TO_NOFICATION) {
                            contentNofi = strContent.substring(0, Parameters.MAX_LENGTH_TO_NOFICATION);
                        }
                        Object[] queryParamsIns3 = { mentorId, studentId,
                                SibConstants.NOTIFICATION_TYPE_REPLY_ESSAY,
                                SibConstants.NOTIFICATION_TITLE_REPLY_ESSAY, contentNofi, null, essayId };
                        dao.insertUpdateObject(SibConstants.SqlMapper.SQL_CREATE_NOTIFICATION, queryParamsIns3);

                        // send message fire base
                        String toTokenId = userservice.getTokenUser(String.valueOf(studentId));
                        if (!StringUtil.isNull(toTokenId)) {

                            fireBaseNotification.sendMessage(toTokenId,
                                    SibConstants.NOTIFICATION_TITLE_REPLY_ESSAY, SibConstants.TYPE_VIDEO,
                                    String.valueOf(essayId), contentNofi, SibConstants.NOTIFICATION_ICON,
                                    SibConstants.NOTIFICATION_PRIPORITY_HIGH);
                        }
                        activiLogService.insertActivityLog(new ActivityLogData(SibConstants.TYPE_ESSAY, "C",
                                "You replied an essay", String.valueOf(mentorId), String.valueOf(essayId)));
                    } else {
                        transactionManager.rollback(status);
                        reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertComstrContentay",
                                "Failed");
                    }
                } else {
                    params = new Object[] { strContent, commentId };
                    dao.insertUpdateObject(SibConstants.SqlMapper.SQL_SIB_EDIT_COMMENT, params);

                    if (StringUtil.isNull(statusMsg)) {
                        params = new Object[] { mentorId, file.getInputStream(), file.getSize(), strFileName,
                                essayId };
                        dao.insertUpdateObject(SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_WITH_FILE,
                                params);
                    } else {
                        if (fileOld == null || fileOld.equals("null")) {
                            params = new Object[] { mentorId, essayId };
                            flag = dao.insertUpdateObject(
                                    SibConstants.SqlMapperBROT163.SQL_INSERT_COMMENT_ESSAY_WITHOUT_FILE,
                                    params);
                        }
                    }
                }
                transactionManager.commit(status);
                reponse = new SimpleResponse(SibConstants.SUCCESS, "essay", "insertCommentEssay", "Success");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (status != null) {
            transactionManager.rollback(status);
        }
        reponse = new SimpleResponse(SibConstants.FAILURE, "essay", "insertCommentEssay", e.getMessage());
    }
    return new ResponseEntity<Response>(reponse, HttpStatus.OK);
}

From source file:com.prcsteel.platform.account.service.impl.AccountServiceImpl.java

@Override
@Transactional//ww  w . j a v a 2  s .c  om
public HashMap<String, Object> updateByPrimaryKeySelective(AccountDto record, List<MultipartFile> attachments,
        AccountContact contact) throws BusinessException {
    HashMap<String, Object> result = new HashMap<String, Object>();
    Account account = record.getAccount();
    User user = record.getManager();
    String accountCode = account.getAccountCode();
    if (accountCode != null && !"".equals(accountCode.replaceAll(" ", ""))) {
        // ??
        AccountBank accountBank = accountBankDao.selectByAccountCode(StringToReplace.toReplaceAll(accountCode));
        // ???
        if (accountBank != null && !accountBank.getAccountId().equals(account.getId())) {
            result.put("success", false);
            result.put("data",
                    "???"
                            + accountDao.selectByPrimaryKey(accountBank.getAccountId()).getName()
                            + "??");
            return result;
        }
    }
    Long accountId = account.getId();
    String bankCode = account.getBankCode(); // ?
    // ??????? modify by kongbinheng 20150803
    if (accountCode != null && !"".equals(accountCode.replaceAll(" ", ""))) {
        AccountBank accountBank = accountBankDao.selectByAccountCode(accountCode.replaceAll(" ", ""));
        if (accountBank == null) {
            accountBank = new AccountBank();
            accountBank.setAccountId(accountId); // ?ID
            accountBank.setBankCode(StringToReplace.toReplaceAll(bankCode)); // ?
            accountBank.setBankName(StringToReplace.toReplaceAll(account.getBankNameMain())); // 
            accountBank.setBankNameBranch(StringToReplace.toReplaceAll(account.getBankNameBranch())); // 
            accountBank.setBankProvinceId(account.getBankProvinceId());
            accountBank.setBankCityId(account.getBankCityId());
            if (account.getBankProvinceId() != null)
                accountBank.setBankProvinceName(
                        provinceDao.selectByPrimaryKey(account.getBankProvinceId()).getName());
            if (account.getBankCityId() != null)
                accountBank.setBankCityName(cityDao.selectByPrimaryKey(account.getBankCityId()).getName());
            accountBank.setBankAccountCode(StringToReplace.toReplaceAll(accountCode)); // ?
            accountBank.setCreated(new Date());
            accountBank.setCreatedBy(user.getLoginId());
            accountBank.setLastUpdated(new Date());
            accountBank.setLastUpdatedBy(user.getLoginId());
            accountBank.setModificationNumber(0);
            accountBankDao.insertSelective(accountBank);
        } else {
            // if(accountId.equals(accountBank.getAccountId())){
            accountBank.setBankCode(StringToReplace.toReplaceAll(bankCode)); // ?
            accountBank.setBankName(StringToReplace.toReplaceAll(account.getBankNameMain())); // 
            accountBank.setBankNameBranch(StringToReplace.toReplaceAll(account.getBankNameBranch())); // 
            accountBankDao.updateByPrimaryKeySelective(accountBank);
            // }else{
            // //ID?
            // }
        }
    }

    account.setCode(null);// ?? ????
    account.setName(null);// ?? ????
    if (StringUtils.isEmpty(account.getBusinessType())) {
        account.setBusinessType(null);
    }

    Account tempAccount = accountDao.selectByPrimaryKey(account.getId());

    if (!StringUtils.isBlank(tempAccount.getAccountCode())
            && Constant.FROMBANKTRANSACTIONJOB.equals(account.getRowId())) { // ??????
        account.setBankCode(null);
        account.setBankNameMain(null);
        account.setAccountCode(null);
    }
    // ???????
    if (!AccountType.both.toString().equals(account.getType())) {
        account.setType(tempAccount.getType());
    }

    account.setLastUpdated(new Date());
    account.setLastUpdatedBy(user.getLoginId());
    account.setModificationNumber(tempAccount.getModificationNumber() + 1);

    accountDao.updateByPrimaryKeySelectiveExcludeBankInfo(account);
    // String basePath = rootPath + ATTACHMENTSAVEPATH + old.getCode()
    // + File.separator;

    boolean taxRegChanged = false;
    boolean invoiceDataChange = false;
    boolean paymentDataChanged = false;//
    boolean openAccountLicenseChanged = false;//??
    // ??????
    if (attachmentsContainConsignContract(attachments)) {
        aamDao.deleteByAccountIdAndType(accountId, AttachmentType.pic_consign_contract.getCode());
    }
    if (attachments != null) {
        for (MultipartFile file : attachments) {
            if ("pic_tax_reg".equals(file.getName())) {
                taxRegChanged = true;
            } else if ("pic_invoice_data".equals(file.getName())) {
                invoiceDataChange = true;
            } else if ("pic_payment_data".equals(file.getName())) {
                paymentDataChanged = true;
            } else if ("pic_open_account_license".equals(file.getName())) {
                openAccountLicenseChanged = true;
            }
            AttachmentType type = AttachmentType.valueOf(file.getName());

            AccountAttachment accountAttachment = null;
            if (!AttachmentType.pic_consign_contract.equals(type)) {
                List<AccountAttachment> list = accountAttachmentDao.selectByAccountIdAndType(accountId,
                        type.getCode());
                if (list != null && list.size() > 0) {
                    accountAttachment = list.get(0);
                }
            }
            // String savePath = basePath + type.getCode() + "."
            // + FileUtil.getFileSuffix(file.getOriginalFilename());
            if (accountAttachment == null) {
                accountAttachment = new AccountAttachment();
                accountAttachment.setAccountId(accountId);
                accountAttachment.setType(type.getCode());
                accountAttachment.setCreated(new Date());
                accountAttachment.setCreatedBy(user.getLoginId());
                // accountAttachment.setLastUpdatedBy(user.getLoginId());
            }
            accountAttachment.setLastUpdated(new Date());
            accountAttachment.setLastUpdatedBy(user.getLoginId());
            String saveKey = "";
            try {
                saveKey = fileService.saveFile(file.getInputStream(),
                        ATTACHMENTSAVEPATH + tempAccount.getCode() + File.separator + type.getCode() + "."
                                + FileUtil.getFileSuffix(file.getOriginalFilename()));
            } catch (IOException e) {
                BusinessException be = new BusinessException(Constant.EXCEPTIONCODE_BUSINESS,
                        "?" + AttachmentType.valueOf(file.getName()) + "");
                throw be;
            }
            accountAttachment.setUrl(saveKey);
            if (accountAttachment.getId() == null || type.equals(AttachmentType.pic_consign_contract)) {
                aamDao.insertSelective(accountAttachment);
            } else {
                aamDao.updateByPrimaryKeySelective(accountAttachment);
            }
        }
    }

    // ? 
    if (!account.getType().equals(AccountType.seller)
            && !(((StringUtils.isEmpty(account.getTaxCode()) && StringUtils.isEmpty(tempAccount.getTaxCode()))
                    || (account.getTaxCode() != null && account.getTaxCode().equals(tempAccount.getTaxCode())))
                    && ((StringUtils.isEmpty(account.getAddr()) && StringUtils.isEmpty(tempAccount.getAddr()))
                            || (account.getAddr() != null && account.getAddr().equals(tempAccount.getAddr())))
                    && ((StringUtils.isEmpty(account.getTel()) && StringUtils.isEmpty(tempAccount.getTel()))
                            || (account.getTel() != null && account.getTel().equals(tempAccount.getTel())))
                    && ((StringUtils.isEmpty(account.getBankNameMain())
                            && StringUtils.isEmpty(tempAccount.getBankNameMain()))
                            || (account.getBankNameMain() != null
                                    && account.getBankNameMain().equals(tempAccount.getBankNameMain())))
                    && ((StringUtils.isEmpty(account.getBankNameBranch())
                            && StringUtils.isEmpty(tempAccount.getBankNameBranch()))
                            || (account.getBankNameBranch() != null
                                    && account.getBankNameBranch().equals(tempAccount.getBankNameBranch())))
                    && ((StringUtils.isEmpty(account.getAccountCode())
                            && StringUtils.isEmpty(tempAccount.getAccountCode()))
                            || (account.getAccountCode() != null
                                    && account.getAccountCode().equals(tempAccount.getAccountCode())))
                    && ((StringUtils.isEmpty(account.getInvoiceType())
                            && StringUtils.isEmpty(tempAccount.getInvoiceType()))
                            || (account.getInvoiceType() != null
                                    && account.getInvoiceType().equals(tempAccount.getInvoiceType())))
                    && !taxRegChanged && !invoiceDataChange)) {
        // ???????????
        if (!(InvoiceDataStatus.Insufficient.getCode().equals(tempAccount.getInvoiceDataStatus())
                && !taxRegChanged && !invoiceDataChange)) {
            accountDao.updateInvoiceDataStatusByPrimaryKey(account.getId(),
                    InvoiceDataStatus.Requested.getCode(), null, user.getLoginId());
        }

    }

    // modify kongbinheng 2015-11-20
    // ???????????
    if (!(((StringUtils.isEmpty(account.getBankNameMain())
            && StringUtils.isEmpty(tempAccount.getBankNameMain()))
            || (account.getBankNameMain() != null
                    && account.getBankNameMain().equals(tempAccount.getBankNameMain())))
            && ((StringUtils.isEmpty(account.getBankNameBranch())
                    && StringUtils.isEmpty(tempAccount.getBankNameBranch()))
                    || (account.getBankNameBranch() != null
                            && account.getBankNameBranch().equals(tempAccount.getBankNameBranch())))
            && ((StringUtils.isEmpty(String.valueOf(account.getBankProvinceId()))
                    && StringUtils.isEmpty(String.valueOf(tempAccount.getBankProvinceId())))
                    || (account.getBankProvinceId() != null
                            && account.getBankProvinceId().equals(tempAccount.getBankProvinceId())))
            && ((StringUtils.isEmpty(String.valueOf(account.getBankCityId()))
                    && StringUtils.isEmpty(String.valueOf(tempAccount.getBankCityId())))
                    || (account.getBankCityId() != null
                            && account.getBankCityId().equals(tempAccount.getBankCityId())))
            && ((StringUtils.isEmpty(account.getAccountCode())
                    && StringUtils.isEmpty(tempAccount.getAccountCode()))
                    || (account.getAccountCode() != null
                            && account.getAccountCode().equals(tempAccount.getAccountCode())))
            && ((StringUtils.isEmpty(account.getBankCode()) && StringUtils.isEmpty(tempAccount.getBankCode()))
                    || (account.getBankCode() != null
                            && account.getBankCode().equals(tempAccount.getBankCode())))
            && !paymentDataChanged && !openAccountLicenseChanged)) {
        // ????????????
        if (!(AccountBankDataStatus.Insufficient.getCode().equals(tempAccount.getBankDataStatus())
                && !paymentDataChanged && !openAccountLicenseChanged)) {
            accountDao.updateBankDataStatusByPrimaryKey(account.getId(),
                    AccountBankDataStatus.Requested.getCode(), null, null, user.getLoginId());
        }
    }

    if (contact != null) {
        AccountContact oldContact = accountcontactDao.queryByTel(contact.getTel());
        if (oldContact != null) {
            if (!oldContact.getName().equals(contact.getName())) {
                throw new BusinessException(Constant.EXCEPTIONCODE_BUSINESS,
                        "????");
            } else if (!oldContact.getAccountId().equals(account.getId())) {
                throw new BusinessException(Constant.EXCEPTIONCODE_BUSINESS,
                        "???");
            } else {
                if (oldContact.getIsMain() != Integer.parseInt(Constant.YES.toString())) { // ????
                    Map<String, Object> map = new HashMap<>();
                    map.put("accountId", account.getId());
                    map.put("isMain", Constant.YES.toString());
                    map.put("type", AccountType.buyer.toString());
                    List<AccountContactDto> list = accountcontactDao.queryByAccountId(map); // ??
                    for (AccountContact temp : list) {
                        temp.setIsMain(Integer.parseInt(Constant.NO.toString()));
                        temp.setLastUpdated(new Date());
                        temp.setLastUpdatedBy(user.getLoginId());
                        temp.setModificationNumber(temp.getModificationNumber() + 1);
                        if (accountcontactDao.updateAccountContactById(temp) != 1) {
                            throw new BusinessException(Constant.EXCEPTIONCODE_BUSINESS,
                                    "?");
                        }
                    }
                }
                contact.setId(oldContact.getId());
                contact.setIsMain(Integer.parseInt(Constant.YES.toString()));
                contact.setType(AccountType.both.toString());
                contact.setLastUpdated(new Date());
                contact.setLastUpdatedBy(user.getLoginId());
                contact.setModificationNumber(tempAccount.getModificationNumber() + 1);
                if (accountcontactDao.updateAccountContactById(contact) != 1) {
                    throw new BusinessException(Constant.EXCEPTIONCODE_BUSINESS, "?");
                }
            }
        } else {
            insertAccountContact(contact, accountId, user);
        }
    }

    result.put("success", true);
    result.put("data", account.getId());
    return result;

}

From source file:com.ephesoft.dcma.webservice.util.WebServiceHelper.java

/**
 * This method is used to get the input xml file.
 * /* w w w .j  a  v  a 2 s . c  o m*/
 * @param workingDir {@link String} the working directory created for web service execution.
 * @param multiPartRequest {@link DefaultMultipartHttpServletRequest} request to get the multipart from request.
 * @param fileMap {@link MultiValueMap} this map contains the input files.
 * @return string
 * @throws IOException
 * @throws FileNotFoundException
 */
public static String getXMLFile(final String workingDir,
        final DefaultMultipartHttpServletRequest multiPartRequest,
        final MultiValueMap<String, MultipartFile> fileMap) throws IOException {
    InputStream instream = null;
    OutputStream outStream = null;
    String xmlFileName = WebServiceConstants.EMPTY_STRING;
    LOGGER.info("Checking for input file.");
    for (final String fileName : fileMap.keySet()) {
        try {
            if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                xmlFileName = fileName;
            }
            final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
            instream = multiPartFile.getInputStream();
            final File file = new File(workingDir + File.separator + fileName);
            outStream = new FileOutputStream(file);
            final byte[] buf = new byte[WebServiceUtil.bufferSize];
            int len;
            while ((len = instream.read(buf)) > 0) {
                outStream.write(buf, 0, len);
            }
        } finally {
            IOUtils.closeQuietly(instream);
            IOUtils.closeQuietly(outStream);
        }
    }
    return xmlFileName;
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To run Reporting.//w  ww. j  a  v  a2 s .c  o m
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/runReporting", method = RequestMethod.POST)
@ResponseBody
public void runReporting(final HttpServletRequest req, final HttpServletResponse resp) {
    LOGGER.info("Start processing the run reporting web service");
    String respStr = WebServiceUtil.EMPTY_STRING;
    try {
        if (req instanceof DefaultMultipartHttpServletRequest) {

            InputStream instream = null;
            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            for (final String fileName : fileMap.keySet()) {
                final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                instream = multiPartFile.getInputStream();
                final Source source = XMLUtil.createSourceFromStream(instream);
                final ReportingOptions option = (ReportingOptions) batchSchemaDao.getJAXB2Template()
                        .getJaxb2Marshaller().unmarshal(source);
                final String installerPath = option.getInstallerPath();
                if (installerPath == null || installerPath.isEmpty()
                        || !installerPath.toLowerCase(Locale.getDefault()).contains(WebServiceUtil.BUILD_XML)) {
                    respStr = "Improper input to server. Installer path not specified or it does not contain the build.xml path.";
                } else {
                    LOGGER.info("synchronizing the database");
                    reportingService.syncDatabase(installerPath);
                    break;
                }
            }

        } else {
            respStr = IMPROPER_INPUT_TO_SERVER;
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        }
    } catch (final XmlMappingException xmle) {
        respStr = ERROR_IN_MAPPING_INPUT + xmle;
        LOGGER.error(SERVER_ERROR_MSG + respStr);
    } catch (final Exception e) {
        respStr = INTERNAL_SERVER_ERROR + e;
        LOGGER.error(SERVER_ERROR_MSG + respStr);
    }

    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
        }
    }
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

private String validateInputAndPerformExtraction(final HttpServletRequest req, final HttpServletResponse resp,
        final String respStr, final String workingDir,
        final DefaultMultipartHttpServletRequest multiPartRequest, final Set<String> fileNameSet,
        final String batchClassIdentifier, final String documentType, final String hocrFileName)
        throws IOException, FileNotFoundException, DCMAException {
    InputStream instream;//from w ww. j  ava2s  . co  m
    OutputStream outStream;
    String respStrLocal = respStr;
    try {
        BatchClass batchClass = bcService.getBatchClassByIdentifier(batchClassIdentifier);
        if (batchClass == null) {
            respStrLocal = "Please enter valid batch class identifier";
        } else {
            Set<String> loggedInUserRole = getUserRoles(req);
            if (!isBatchClassViewableToUser(batchClassIdentifier, loggedInUserRole, isSuperAdmin(req))) {
                respStrLocal = USER_NOT_AUTHORIZED_TO_VIEW_THE_BATCH_CLASS + batchClassIdentifier;
                LOGGER.error(SERVER_ERROR_MSG + respStrLocal);
            } else {
                BatchPlugin regularRegexPlugin = batchClassPPService.getPluginProperties(batchClassIdentifier,
                        "REGULAR_REGEX_EXTRACTION");
                if (regularRegexPlugin == null || regularRegexPlugin.getPropertiesSize() == 0) {
                    respStrLocal = "Fuzzy DB plugin is not configured for batch class : " + batchClassIdentifier
                            + " . Please select proper batch class";
                    LOGGER.error(SERVER_ERROR_MSG + respStrLocal);
                }
                for (final String fileName : fileNameSet) {
                    if (fileName.equalsIgnoreCase(hocrFileName)) {
                        LOGGER.info("hocr file name found : " + hocrFileName);
                        final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                        instream = multiPartFile.getInputStream();
                        final File file = new File(workingDir + File.separator + fileName);
                        outStream = new FileOutputStream(file);
                        final byte[] buf = new byte[WebServiceUtil.bufferSize];
                        int len = instream.read(buf);
                        while (len > 0) {
                            outStream.write(buf, 0, len);
                            len = instream.read(buf);
                        }
                        break;
                    }
                }
                final File hocrFile = new File(workingDir + File.separator + hocrFileName);
                if (hocrFile.exists()) {
                    respStrLocal = performRegexExtraction(resp, workingDir, hocrFile.getAbsolutePath(),
                            batchClassIdentifier, documentType);
                }
            }
        }
    } catch (Exception exception) {
        LOGGER.error("Error occurred while extracting fields using regular regex extarction.");
        throw new DCMAException(exception.getMessage(), exception);
    }
    return respStrLocal;
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To import Batch Class./*from   w  ww  . j  a v a2 s .c o m*/
 * @param req {@link HttpServletRequest}
 * @param resp {@link HttpServletResponse}
 */
@RequestMapping(value = "/importBatchClass", method = RequestMethod.POST)
@ResponseBody
public void importBatchClass(final HttpServletRequest req, final HttpServletResponse resp) {
    String respStr = WebServiceUtil.EMPTY_STRING;
    LOGGER.info("Start processing import batch class web service");
    String workingDir = WebServiceUtil.EMPTY_STRING;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        InputStream instream = null;
        OutputStream outStream = null;
        final String webServiceFolderPath = bsService.getWebServicesFolderPath();
        LOGGER.info("web Service Folder Path" + webServiceFolderPath);
        final DefaultMultipartHttpServletRequest mPartReq = (DefaultMultipartHttpServletRequest) req;
        final MultiValueMap<String, MultipartFile> fileMap = mPartReq.getMultiFileMap();

        if (fileMap.size() == 2) {
            try {
                workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
                LOGGER.info("Created the web service working directory successfully  :" + workingDir);
                ImportBatchClassOptions option = null;
                String zipFilePath = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    try {
                        final MultipartFile multiPartFile = mPartReq.getFile(fileName);
                        instream = multiPartFile.getInputStream();
                        if (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.XML.getExtension().toLowerCase()) > -1) {
                            final Source source = XMLUtil.createSourceFromStream(instream);
                            option = (ImportBatchClassOptions) batchSchemaDao.getJAXB2Template()
                                    .getJaxb2Marshaller().unmarshal(source);
                            continue;
                        } else if (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.ZIP.getExtension().toLowerCase()) > -1) {
                            zipFilePath = workingDir + File.separator + fileName;
                            LOGGER.info("Zip file is using for importing batch class is " + zipFilePath);
                            final File file = new File(zipFilePath);
                            outStream = new FileOutputStream(file);
                            final byte[] buf = new byte[WebServiceUtil.bufferSize];
                            int len = instream.read(buf);
                            while (len > 0) {
                                outStream.write(buf, 0, len);
                                len = instream.read(buf);
                            }
                            continue;
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }
                }

                respStr = importBatchClassInternal(resp, respStr, workingDir, option, zipFilePath);

            } catch (final XmlMappingException xmle) {
                respStr = ERROR_IN_MAPPING_INPUT + xmle;
            } catch (final Exception e) {
                respStr = INTERNAL_SERVER_ERROR + e.getMessage();
            } finally {

                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        } else {
            respStr = "Improper input to server. Expected two files: zip and xml file. Returning without processing the results.";
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        }
    } else {
        respStr = IMPROPER_INPUT_TO_SERVER;
        LOGGER.error(SERVER_ERROR_MSG + respStr);
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.error("Error while sending error reponse.");
        }
    }
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

private void processKVExtraction(final HttpServletRequest req, final HttpServletResponse resp) {
    String respStr = WebServiceUtil.EMPTY_STRING;
    LOGGER.info("Processing key value extraction using web service.");
    String workingDir = WebServiceUtil.EMPTY_STRING;

    if (req instanceof DefaultMultipartHttpServletRequest) {
        InputStream instream = null;
        OutputStream outStream = null;
        final String webServiceFolderPath = bsService.getWebServicesFolderPath();
        LOGGER.info("Web Service Folder Path:" + webServiceFolderPath);
        final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;
        final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();

        if (fileMap.size() == 2) {
            try {
                workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
                LOGGER.info("Created web service working directory:" + workingDir + "successfully");
                ExtractKVParams params = null;
                String filePath = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    try {
                        final MultipartFile multipartFile = multiPartRequest.getFile(fileName);
                        instream = multipartFile.getInputStream();
                        if (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.XML.getExtension().toLowerCase()) > -1) {
                            final Source source = XMLUtil.createSourceFromStream(instream);
                            params = (ExtractKVParams) batchSchemaDao.getJAXB2Template().getJaxb2Marshaller()
                                    .unmarshal(source);
                            continue;
                        } else if (fileName.toLowerCase(Locale.getDefault())
                                .indexOf(FileType.HTML.getExtension().toLowerCase()) > -1) {
                            filePath = workingDir + File.separator + fileName;
                            LOGGER.info("HTML file for processing is " + filePath);
                            final File file = new File(filePath);
                            outStream = new FileOutputStream(file);
                            final byte[] buf = new byte[WebServiceUtil.bufferSize];
                            int len = instream.read(buf);
                            while (len > 0) {
                                outStream.write(buf, 0, len);
                                len = instream.read(buf);
                            }/* w w  w.j ava2s  .  c  o m*/
                            continue;
                        }
                    } finally {
                        IOUtils.closeQuietly(instream);
                        IOUtils.closeQuietly(outStream);
                    }
                }

                respStr = validateExtractKV(respStr, params, filePath);
                if (respStr.isEmpty()) {
                    respStr = performExtractKVInternal(resp, respStr, workingDir, params, filePath);
                }

            } catch (final XmlMappingException xmle) {
                respStr = "Error in mapping input XML or the hocr file in the desired format. Please send it in the specified format. Detailed exception is "
                        + xmle;
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            } catch (final DCMAException dcmae) {
                respStr = ERROR_PROCESSING_REQUEST + dcmae;
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            } catch (final Exception e) {
                respStr = "Internal Server error.Please check logs for further details." + e;
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            } finally {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        } else {
            respStr = "Improper input to server. Expected two files: hocr and xml parameter file. Returning without processing the results.";
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        }
    } else {
        respStr = IMPROPER_INPUT_TO_SERVER;
        LOGGER.error(SERVER_ERROR_MSG + respStr);
    }

    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.info(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
        }
    }
}