Sample Spring MVC Controller

package com.mohh.nehr.Hello.Hello.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import org.springframework.web.portlet.bind.annotation.ResourceMapping;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.model.RoleConstants;
import com.liferay.portal.kernel.servlet.ServletResponseUtil;
import com.liferay.portal.kernel.theme.ThemeDisplay;
import com.liferay.portal.kernel.util.Constants;
import com.liferay.portal.kernel.util.ContentTypes;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.mohh.nehr.bean.TranslatedSearchTerm;
import com.mohh.nehr.binding.eHello.PerformCheckEligibilityForUpdateDeleteResponse.PerformCheckEligibilityForUpdateDeleteResult;
import com.mohh.nehr.binding.eHello.PerformCreateUpdateEHelloResponse.PerformCreateUpdateEHelloResult;
import com.mohh.nehr.builder.common.constants.EHelloStatus;
import com.mohh.nehr.builder.service.exception.NoSuchSampleMVCExampleSubmissionException;
import com.mohh.nehr.builder.service.model.SampleMVCExample;
import com.mohh.nehr.builder.service.model.SampleMVCExampleSubmission;
import com.mohh.nehr.builder.service.service.SampleMVCExampleSubmissionLocalServiceUtil;
import com.mohh.nehr.Hello.Hello.form.HelloForm;
import com.mohh.nehr.Hello.Hello.form.HelloFormuildDirector;
import com.mohh.nehr.Hello.Hello.form.HelloFormuilderImpl;
import com.mohh.nehr.Hello.common.IDType;
import com.mohh.nehr.Hello.common.util.HelloActionUtil;
import com.mohh.nehr.Hello.common.util.HelloRenderUtil;
import com.mohh.nehr.Hello.common.util.HelloCommonUtil;
import com.mohh.nehr.Hello.common.util.HelloFormValidator;
import com.mohh.nehr.Hello.common.util.DeathConstants;
import com.mohh.nehr.common.util.exception.NEHRPortalException;
import com.mohh.nehr.common.util.log.NEHRLogUtil;
import com.mohh.nehr.commonUtil.criteria.SearchCriteria;
import com.mohh.nehr.commonUtil.form.PatientForm;
import com.mohh.nehr.commonUtil.json.BaseJsonResponse;
import com.mohh.nehr.commonUtil.json.Status;
import com.mohh.nehr.commonUtil.obj.UserObject;
import com.mohh.nehr.commonUtil.util.CommonConstants;
import com.mohh.nehr.commonUtil.util.JsonUtil;
import com.mohh.nehr.commonUtil.util.NEHRRoleUtil;
import com.mohh.nehr.commonUtil.util.NEHRSessionUtil;
import com.mohh.nehr.commonUtil.util.NEHRStringUtil;
import com.mohh.nehr.commonUtil.util.OnlineHelpUtil;
import com.mohh.nehr.commonUtil.util.SearchCriteriaUtil;
import com.mohh.nehr.form.req.SearchForm;
import com.mohh.nehr.form.req.SearchformWrapper;
import com.mohh.nehr.form.resp.MasterSearchForm;
//CR564
import com.mohh.nehr.service.eHello.service.EHelloService;
import com.mohh.nehr.service.eHello.util.HelloConstants;

@Controller("HelloPortletController")
@RequestMapping("VIEW")
public class HelloPortletController {

@Autowired
private HelloActionUtil HelloActionUtil;

@Autowired
private HelloRenderUtil HelloRenderUtil;

@Autowired
private HelloCommonUtil HelloCommonUtil;

@Autowired
private EHelloService eHelloService;

@Autowired
private HelloFormValidator HelloFormValidator;

    private static final NEHRLogUtil LOG = NEHRLogUtil.getInstance(HelloPortletController.class.getName());

@RenderMapping
public ModelAndView renderCOODHistory(RenderRequest renderRequest, RenderResponse renderResponse) throws NEHRPortalException {
String sessionDetails = HelloCommonUtil.sessionLogging(renderRequest);
LOG.debug(sessionDetails + "rendering page");
ModelAndView modelAndView = null;
String renderJSP = ParamUtil.getString(renderRequest, DeathConstants.STR_JSP);
HelloForm HelloForm = null;
LOG.debug(sessionDetails + "renderJSP: " + renderJSP);
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy HH:mm");

if (Validator.isNotNull(renderJSP) && !renderJSP.equalsIgnoreCase(DeathConstants.JSP_Hello_HISTORY)) {

if (renderJSP.equalsIgnoreCase(DeathConstants.JSP_Hello_PREVIEW)
|| renderJSP.equalsIgnoreCase(DeathConstants.JSP_Hello_SUCCESS_PRINT)
|| renderJSP.equalsIgnoreCase(DeathConstants.JSP_EDIT_Hello_FORM)) {


long HelloSubmissionId = Long.parseLong(renderRequest.getParameter(DeathConstants.PARAM_Hello_SUBMISSION_ID));
Boolean isWebServiceError = Boolean.valueOf(renderRequest.getParameter(DeathConstants.WS_ERROR));
HelloForm = HelloRenderUtil.getHelloForm(renderRequest, HelloSubmissionId, renderJSP);

if (null != HelloForm) {

modelAndView = new ModelAndView(renderJSP, DeathConstants.PARAM_Hello_FORM_OBJ, HelloForm);
modelAndView.addObject(DeathConstants.WS_ERROR, isWebServiceError);
}


if (renderJSP.equalsIgnoreCase(DeathConstants.JSP_EDIT_Hello_FORM) && (HelloForm != null)) {
modelAndView.addObject(DeathConstants.PARAM_SAVE_SUCCESS, DeathConstants.STR_SAVED);
}

} else {
modelAndView = new ModelAndView(renderJSP);
}

} else {
SampleMVCExampleSubmission SampleMVCExampleSubmission = null;
try {
// retrieve PatientForm
PatientForm patientForm = NEHRSessionUtil.getCurrentPatient(renderRequest);
// retrieve list of id
List<String> mrnList = HelloCommonUtil.getPatientIDList(patientForm, IDType.MRN);
List<String> rootIdList = HelloCommonUtil.getPatientIDList(patientForm, IDType.ROOT);
List<String> sourceSystemList = HelloCommonUtil.getPatientIDList(patientForm, IDType.SOURCE);

// retrieve latest Hello submission record
SampleMVCExampleSubmission = HelloActionUtil.getLatestVersion(rootIdList, mrnList, sourceSystemList);
} catch(NEHRPortalException e) {
LOG.error("NEHRPortalException occurred in renderCOODHistory:", e);
}

modelAndView = new ModelAndView(DeathConstants.JSP_Hello_HISTORY,
DeathConstants.PARAM_Hello_SUBMISSION_HISTORY_ITEM, SampleMVCExampleSubmission);
            if(SampleMVCExampleSubmission != null) {
                String modifiedDateString = simpleDateFormat.format(SampleMVCExampleSubmission.getModifiedDate());
                modelAndView.addObject(DeathConstants.Hello_HISTORY_MODIFIED_DATE_STRING, modifiedDateString);
            }
}

return modelAndView;

}

@RenderMapping(params = "render=addHelloView")
public ModelAndView addHello(RenderRequest renderRequest, RenderResponse renderResponse) throws NEHRPortalException {

HelloForm HelloForm = HelloRenderUtil.getHelloForm(renderRequest, 0, DeathConstants.JSP_EDIT_Hello_FORM);

return new ModelAndView(DeathConstants.JSP_EDIT_Hello_FORM,
DeathConstants.PARAM_Hello_FORM_OBJ, HelloForm);

}
 
@RenderMapping(params = "render=viewSuccessPrint")
public ModelAndView viewSuccessPrint(RenderRequest renderRequest, RenderResponse renderResponse) throws NEHRPortalException {

HelloForm HelloForm = HelloRenderUtil.getHelloForm(renderRequest, 0, DeathConstants.JSP_FROMB_SUCCESS_PRINT);

return new ModelAndView(DeathConstants.JSP_FROMB_SUCCESS_PRINT,
DeathConstants.PARAM_Hello_FORM_OBJ, HelloForm);

}

@ResourceMapping(value = "getAutoCompleteListValues")
public BaseJsonResponse getAutoCompleteListValues(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws NEHRPortalException {

String HelloingSchemeName = ParamUtil.getString(resourceRequest, DeathConstants.PARAM_HelloING_SCHEME_NAME);
String searchText = ParamUtil.getString(resourceRequest, DeathConstants.PARAM_SEARCH_TEXT);
String sessionDetails = HelloCommonUtil.sessionLogging(resourceRequest);

LOG.debug(sessionDetails + "getAutoCompleteListValues: HelloingSchemeName > " + HelloingSchemeName + " | searchText > " + searchText);

return HelloRenderUtil.getAutoCompleteListValues(HelloingSchemeName, searchText);
}

@ActionMapping(params = "action=saveHello")
public void saveHello(ActionRequest actionRequest, ActionResponse actionResponse) throws NEHRPortalException {

HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(actionResponse);
String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
SampleMVCExampleSubmission SampleMVCExampleSubmissionResp = null;
SampleMVCExampleSubmission SampleMVCExampleSubmission = HelloActionUtil.createSampleMVCExampleSubmission(actionRequest);
List<SampleMVCExample> SampleMVCExampleList = HelloActionUtil.createSampleMVCExampleList(actionRequest);
Status status = new Status();
String sessionDetails = HelloCommonUtil.sessionLogging(actionRequest);

if (("proceed").equalsIgnoreCase(cmd)) {
LOG.debug(sessionDetails + "HelloPortletController - saveHello : PROCEED TO PREVIEW PAGE");

// M001 - unauthorize saving of record in proceed
// check if user has NEHR_FORMS_ICA_Hello_WRITE role, if not send error message to UI
if (!NEHRRoleUtil.checkRole(actionRequest, NEHRRoleUtil.RoleNames.NEHR_FORMS_ICA_Hello_WRITE.name())) {
LOG.debug(DeathConstants.USER_INSUFFICIENT_ROLE);
// return error message to UI
status.setHelloe(String.valueOf(EHelloStatus.FAILED_VALIDATED_DRAFT.getStatus()));
status.setErrorMessage(EHelloStatus.OTHER_ERROR.getMeaning());
sendResponse(SampleMVCExampleSubmission, status, new BaseJsonResponse(), httpServletResponse);
return;
}

// Added for CR564 validation
HelloFormuilderImpl HelloFormuilderImpl = new HelloFormuilderImpl(HelloCommonUtil, HelloRenderUtil);
HelloFormuildDirector HelloFormuildDirector = new HelloFormuildDirector(HelloFormuilderImpl);
HelloForm HelloForm = null;
try{
// construct HelloForm from request
HelloForm = HelloFormuildDirector.constructHelloFormFromRequest(actionRequest, HelloCommonUtil.getLoginUser(actionRequest));
} catch(NEHRPortalException e){
LOG.error("Exception occured in persisting SampleMVCExampleSubmission", e);
sendResponse(SampleMVCExampleSubmission, status, EHelloStatus.OTHER_ERROR.getAlertMessage(), new BaseJsonResponse(), httpServletResponse);

}

if (HelloForm == null) {
// return error message to UI
sendResponse(SampleMVCExampleSubmission, status, EHelloStatus.OTHER_ERROR.getAlertMessage(), new BaseJsonResponse(), httpServletResponse);
return;
}
LOG.debug(sessionDetails + "HelloPortletController - saveHello : HelloForm > " + HelloForm);
// validate SampleMVCExample if it is a valid Type A Hello
if (!HelloFormValidator.checkHelloType(HelloForm.getCauseDescriptionForms())) {
LOG.info(sessionDetails + "HelloPortletController - saveHello : Invalid Cause of Death Type");
status.setHelloe(String.valueOf(EHelloStatus.INVALID_ICD10_DIAGNOSIS_HelloE_TYPE.getStatus()));
status.setErrorMessage(HelloCommonUtil.getDBPropertyValue(DeathConstants.INVALID_Hello_TYPE_ERR_MSG));
// return invalid Hello Type error message to UI
    sendResponse(SampleMVCExampleSubmission, status, new BaseJsonResponse(), httpServletResponse);
    return;
}

DataBinder binder = new DataBinder(HelloForm);
    // get BindingResult that includes any validation errors
    BindingResult results = binder.getBindingResult();
    // invoke validator

   
    // validate result
LOG.info(sessionDetails + "HelloPortletController - saveHello : Validate result");
    if(results.hasErrors()) {
    LOG.info(sessionDetails + "HelloPortletController - saveHello : Validation error occured in saveHello");
    status.setHelloe(String.valueOf(EHelloStatus.FAILED_VALIDATED_DRAFT.getStatus()));
status.setErrorMessage(HelloCommonUtil.getDBPropertyValue(DeathConstants.VALIDATION_ERROR));
// return validation error message to UI
    sendResponse(SampleMVCExampleSubmission, status, new BaseJsonResponse(), httpServletResponse);
    return;
    }
    actionResponse.setRenderParameter(DeathConstants.STR_JSP, DeathConstants.JSP_Hello_PREVIEW);
} else if (("saveDraft").equalsIgnoreCase(cmd)) {
LOG.info(sessionDetails + "HelloPortletController - saveHello : SAVE DRAFT");

// M001 - unauthorize saving of record in save as draft
// check if user has NEHR_FORMS_ICA_Hello_WRITE role, if not send error message to UI


if (!NEHRRoleUtil.checkRole(actionRequest, NEHRRoleUtil.RoleNames.NEHR_FORMS_ICA_Hello_WRITE.name())) {
LOG.debug(sessionDetails + DeathConstants.USER_INSUFFICIENT_ROLE);
throw new NEHRPortalException(EHelloStatus.OTHER_ERROR.getMeaning());
}
LOG.info(sessionDetails + "Role is sufficient");
actionResponse.setRenderParameter(DeathConstants.STR_JSP, DeathConstants.JSP_EDIT_Hello_FORM);
}

try {
LOG.debug(sessionDetails + "SampleMVCExampleSubmission>>>>" + SampleMVCExampleSubmission);
SampleMVCExampleSubmissionResp = getSampleMVCExampleSubmission(SampleMVCExampleSubmission, SampleMVCExampleList);
if (SampleMVCExampleSubmissionResp == null) {
// return error message to UI
sendResponse(SampleMVCExampleSubmission, status, EHelloStatus.OTHER_ERROR.getAlertMessage(), new BaseJsonResponse(), httpServletResponse);
return;
}
actionResponse.setRenderParameter(DeathConstants.PARAM_Hello_SUBMISSION_ID, String.valueOf(SampleMVCExampleSubmissionResp.getHelloSubmissionId()));
if (("proceed").equalsIgnoreCase(cmd)) {
status.setHelloe(String.valueOf(EHelloStatus.SUCCESSFUL_VALIDATED_DRAFT.getStatus()));
status.setMeaning(EHelloStatus.SUCCESSFUL_VALIDATED_DRAFT.getAlertMessage());
// send successful validation status to UI
sendResponse(SampleMVCExampleSubmissionResp, status, new BaseJsonResponse(), httpServletResponse);
}
} catch (SystemException e) {
LOG.error("Exception occured in persisting SampleMVCExampleSubmission", e);
sendResponse(SampleMVCExampleSubmission, status, EHelloStatus.OTHER_ERROR.getAlertMessage(), new BaseJsonResponse(), httpServletResponse);
}

}

@ActionMapping(params = "action=submitHello")
public void submitHello(ActionRequest actionRequest, ActionResponse actionResponse) {

// M001 - unauthorize submission of record
// check if user has NEHR_FORMS_ICA_Hello_WRITE role, if not send error message to UI
String sessionDetails = HelloCommonUtil.sessionLogging(actionRequest);
if (!NEHRRoleUtil.checkRole(actionRequest, NEHRRoleUtil.RoleNames.NEHR_FORMS_ICA_Hello_WRITE.name())) {
LOG.debug(sessionDetails + DeathConstants.USER_INSUFFICIENT_ROLE);
Status status = new Status();
BaseJsonResponse baseJsonResponse = new BaseJsonResponse();
HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(actionResponse);

status.setHelloe(EHelloStatus.OTHER_ERROR.getWsStatus());
status.setMeaning(EHelloStatus.OTHER_ERROR.getMeaning());
sendResponse(null, status, baseJsonResponse, httpServletResponse);
return;
}

String requestType = StringUtils.EMPTY;

// retrieve request type
if(ParamUtil.getString(actionRequest, DeathConstants.REQUEST_TYPE) != null) {
requestType = ParamUtil.getString(actionRequest, DeathConstants.REQUEST_TYPE);
}

LOG.debug(sessionDetails + "submitHello requestType : " + requestType);
if(requestType.trim().equalsIgnoreCase(DeathConstants.SUBMISSTION_TYPE_UPDATE)) {
String userNameICAWXS = HelloCommonUtil.getDBPropertyValue(DeathConstants.ICA_WXS_USERNAME);
String pwdICAWXS = HelloCommonUtil.getDBPropertyValue(DeathConstants.ICA_WXS_PASSWORD);
String nonceICAWXS = HelloCommonUtil.getNonceICAWXSe();

long HelloSubmissionId = ParamUtil.getLong(actionRequest, DeathConstants.PARAM_Hello_SUBMISSION_ID);
SampleMVCExampleSubmission HelloSubmission = null;
PerformCheckEligibilityForUpdateDeleteResult eHelloResponseObj = null;

try {
HelloSubmission = SampleMVCExampleSubmissionLocalServiceUtil.getSampleMVCExampleSubmission(HelloSubmissionId);
    // retrieve UserObject
UserObject userObject = NEHRSessionUtil.getUserObj(actionRequest);
// check if isEligibleForUpdateDelete
eHelloResponseObj = eHelloService.isEligibleForUpdateDelete(HelloSubmission, userNameICAWXS, pwdICAWXS, nonceICAWXS, userObject);
} catch (PortalException|SystemException e) {
LOG.error(DeathConstants.PORTAL_EXCEPTION_ERR_MSG, e);
}  catch (NEHRPortalException e) {
LOG.error("NEHRPortalException occurred in initiateSubmitHello:", e);
}

// check for response status
String statusHelloe = StringUtils.EMPTY;
if(eHelloResponseObj != null && eHelloResponseObj.getSTATS().get(0) != null) {
statusHelloe = eHelloResponseObj.getSTATS().get(0);
}

// if success, submit
if(statusHelloe.equals(EHelloStatus.SUCCESS.getWsStatus())) {
initiateSubmitHello(actionRequest, actionResponse, true);
} else {
// else, update the Hello Submission with error status for performEligibilityCheckForUpdateDelete & return error message to UI
HelloActionUtil.saveErrorStatus(HelloSubmission, statusHelloe, "E");
HelloActionUtil.setDeleteResponse(actionResponse, statusHelloe, "E");
}
} else if (requestType.trim().equalsIgnoreCase(DeathConstants.SUBMISSTION_TYPE_DELETE)) {
// if request type is delete, invoke deletion method
LOG.debug(sessionDetails + "Delete submission flow");

long HelloSubmissionId = ParamUtil.getLong(actionRequest, DeathConstants.PARAM_Hello_SUBMISSION_ID);
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
SampleMVCExampleSubmission HelloSubmission = null;
LOG.debug(sessionDetails + "CHECK HERE: Delete submission flow");

try {
HelloSubmission = SampleMVCExampleSubmissionLocalServiceUtil.getSampleMVCExampleSubmission(HelloSubmissionId);
HelloActionUtil.deleteFromIcaAndLR(actionRequest, actionResponse, themeDisplay, HelloSubmission);

} catch (PortalException|SystemException e) {
LOG.error(DeathConstants.PORTAL_EXCEPTION_ERR_MSG, e);
}
} else {
// if requestType is not update or delete, submit HelloForm
LOG.debug(sessionDetails + "HelloPortletController - submitHello : Request is not Update or Delete");
initiateSubmitHello(actionRequest, actionResponse, false);
}
}

public void initiateSubmitHello(ActionRequest actionRequest, ActionResponse actionResponse, boolean isUpdate) {
String sessionDetails = HelloCommonUtil.sessionLogging(actionRequest);
LOG.debug(sessionDetails + "Initiate Submit Hello. isUpdate: " + isUpdate);

long HelloSubmissionId = ParamUtil.getLong(actionRequest, DeathConstants.PARAM_Hello_SUBMISSION_ID);
BaseJsonResponse baseJsonResponse = new BaseJsonResponse();
SampleMVCExampleSubmission updatedHelloSubmission = null;
HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(actionResponse);
Status status = new Status();
SampleMVCExampleSubmission HelloSubmission = null;
String hospitalRefNumber = UUID.randomUUID().toString().substring(0, 30);
String alertMessage = null;
List<String> deathrecExistsErrorHelloes = new ArrayList<>(2);
List<SampleMVCExample> SampleMVCExamplesList = null;

deathrecExistsErrorHelloes.add(EHelloStatus.RECORD_ALREADY_EXIST_IN_EHello.getWsStatus());
deathrecExistsErrorHelloes.add(EHelloStatus.RECORD_ALREADY_EXIST_IN_DEATH_RECORD.getWsStatus());

LOG.debug(sessionDetails + "HelloSubmissionId in initiateSubmitHello :" + HelloSubmissionId);
LOG.debug(sessionDetails + "RECORD_ALREADY_EXIST_IN_EHello " + EHelloStatus.RECORD_ALREADY_EXIST_IN_EHello.getWsStatus());
LOG.debug(sessionDetails + "RECORD_ALREADY_EXIST_IN_DEATH_RECORD " + EHelloStatus.RECORD_ALREADY_EXIST_IN_DEATH_RECORD.getWsStatus());

try {
HelloSubmission = SampleMVCExampleSubmissionLocalServiceUtil.getSampleMVCExampleSubmission(HelloSubmissionId);
SampleMVCExamplesList = SampleMVCExampleSubmissionLocalServiceUtil.getSampleMVCExamplesByHelloSubmissionId(HelloSubmissionId);
} catch (PortalException | SystemException e) {
sendResponse(null, status,EHelloStatus.OTHER_ERROR.getAlertMessage(),  baseJsonResponse,  httpServletResponse);
LOG.error("Exception occurred in getSampleMVCExampleSubmission/ getSampleMVCExamplesByHelloSubmissionId of initiateSubmitHello Method:", e);
}

if(HelloSubmission == null){
sendResponse(null, status,EHelloStatus.OTHER_ERROR.getAlertMessage(),  baseJsonResponse,  httpServletResponse);
LOG.error("HelloSubmission Object for submission is null");
return;
}

HelloSubmission.setHospitalRefNo(hospitalRefNumber);
HelloSubmission.setModifiedDate(new Date());

String userNameICAWXS = HelloCommonUtil.getDBPropertyValue(DeathConstants.ICA_WXS_USERNAME);
String pwdICAWXS = HelloCommonUtil.getDBPropertyValue(DeathConstants.ICA_WXS_PASSWORD);
String nonceICAWXS = HelloCommonUtil.getNonceICAWXSe();
PerformCreateUpdateEHelloResult HelloStatus = null;

try {
// retrieve UserObject
UserObject userObject = NEHRSessionUtil.getUserObj(actionRequest);
HelloStatus = eHelloService.sendEHelloSoapMessage(HelloSubmission, SampleMVCExamplesList, userNameICAWXS,pwdICAWXS, nonceICAWXS, userObject);
} catch (NEHRPortalException e) {
LOG.error("NEHRPortalException occurred in initiateSubmitHello", e);
HelloSubmission.setStatus(EHelloStatus.OTHER_ERROR.getStatus());
alertMessage = EHelloStatus.OTHER_ERROR.getAlertMessage();
LOG.error("Exception occurred in sendEHelloSoapMessage of initiateSubmitHello Method:", e);
}

/*
* Based on the discussion with Wei Yang, we are not expecting
* multiple response stats with S000, E010, E011. For all other
* error Helloes we there might be multiple response, however we are
* only persisting only the first response message in DB rest all in
* the error log
*/
if (HelloStatus == null || HelloStatus.getSTATS().isEmpty()) {
LOG.debug(sessionDetails + "HelloPortletController - initiateSubmitHello : PerformCreateUpdateEHelloResult HelloStatus is null/ getSTATS is empty");
HelloSubmission.setStatus(EHelloStatus.OTHER_ERROR.getStatus());
} else {
setHelloStatus(HelloStatus, deathrecExistsErrorHelloes, HelloSubmission, isUpdate);
}

try {
updatedHelloSubmission = SampleMVCExampleSubmissionLocalServiceUtil.updateSampleMVCExampleSubmission(HelloSubmission);
sendResponse(updatedHelloSubmission, status,alertMessage,  baseJsonResponse,  httpServletResponse);
} catch (SystemException e) {
sendResponse(null, status,EHelloStatus.OTHER_ERROR.getAlertMessage(),  baseJsonResponse,  httpServletResponse);
LOG.error("Exception occurred in updateSampleMVCExampleSubmission of initiateSubmitHello Method:", e);
}
}

/**
*
* @param updatedHelloSubmission
* @param status
* @param alertMessage
* @param baseJsonResponse
* @param httpServletResponse
* @param objectMapper
* @throws IOException
*/
private void sendResponse(SampleMVCExampleSubmission updatedHelloSubmission,Status status,
String alertMessage, BaseJsonResponse baseJsonResponse, HttpServletResponse httpServletResponse){
//Fortify Fix : Redundant null check
if (baseJsonResponse == null) {
LOG.debug("HelloPortletController sendResponse : BaseJsonResponse is null");
return;
}
if (updatedHelloSubmission != null) {
HelloForm HelloForm = new HelloForm();
HelloForm.setHelloSubmissionId(updatedHelloSubmission.getHelloSubmissionId());
HelloForm.setStatus(String.valueOf(updatedHelloSubmission.getStatus()));
status.setHelloe(String.valueOf(updatedHelloSubmission.getStatus()));
status.setMeaning(Validator.isNotNull(alertMessage) ? alertMessage
: EHelloStatus.getAlertMessage(updatedHelloSubmission.getStatus()));

baseJsonResponse.setStatus(status);
baseJsonResponse.setDataObj(HelloForm);
}

// TODO Fix ESAPI error
// Fortify fix: Obsolete: Deprecated by ESAPI
httpServletResponse.setContentType(ContentTypes.TEXT_PLAIN_UTF8);
try {
ObjectMapper objectMapper = new ObjectMapper();
String HelloSubmitResponse = objectMapper.writeValueAsString(baseJsonResponse);
LOG.debug("HelloSubmitResponse : " + HelloSubmitResponse);
ServletResponseUtil.write(httpServletResponse, HelloSubmitResponse);
httpServletResponse.flushBuffer();
} catch (IOException e) {
LOG.error("Exception occurred in flushing response to frontend: " + e);
}
}

/**
* @param updatedHelloSubmission
* @param status
* @param baseJsonResponse
* @param httpServletResponse
*/
private void sendResponse(SampleMVCExampleSubmission updatedHelloSubmission,Status status,  BaseJsonResponse baseJsonResponse, HttpServletResponse httpServletResponse){
if (updatedHelloSubmission != null && status != null) {
HelloForm HelloForm = new HelloForm();
HelloForm.setHelloSubmissionId(updatedHelloSubmission.getHelloSubmissionId());
HelloForm.setStatus(String.valueOf(updatedHelloSubmission.getStatus()));

baseJsonResponse.setStatus(status);
baseJsonResponse.setDataObj(HelloForm);

} else {
baseJsonResponse.setStatus(status);
}
// TODO Fix ESAPI error
// Fortify fix: Obsolete: Deprecated by ESAPI
httpServletResponse.setContentType(ContentTypes.TEXT_PLAIN_UTF8);
try {
ObjectMapper objectMapper = new ObjectMapper();
String HelloSubmitResponse = objectMapper.writeValueAsString(baseJsonResponse);
LOG.debug("HelloSubmitResponse : " + HelloSubmitResponse);
ServletResponseUtil.write(httpServletResponse, HelloSubmitResponse);
httpServletResponse.flushBuffer();
} catch (IOException e) {
LOG.error("Exception occurred in flushing response to frontend: " + e);
}
}

    /**
     * This method is used use to set status
     *
     * @param HelloStatus
     * @param deathrecExistsErrorHelloes
     * @param HelloSubmission
     * @param alertMessage
     * @param isUpdate
     */
private void setHelloStatus(PerformCreateUpdateEHelloResult HelloStatus, List<String> deathrecExistsErrorHelloes,
SampleMVCExampleSubmission HelloSubmission, boolean isUpdate){
List<String> multipleErrorHelloes = new ArrayList<>();
if (HelloStatus.getSTATS().size() > 1) {
LOG.debug("Multiple Helloes");

for (String wsStatus : HelloStatus.getSTATS()) {
LOG.error(" Webservice Error Response Status Message " + wsStatus);
multipleErrorHelloes.add(wsStatus);
}

//Multiple Errors Scenario: If response contains E010 and E012 then persists E012
checkMulErrMsg(HelloStatus, HelloSubmission, deathrecExistsErrorHelloes, isUpdate);

} else {
LOG.debug("Single Error Helloe");
checkSingleErrMsg(HelloStatus, HelloSubmission, isUpdate);
}
}
 
/**
*
* @param HelloStatus
* @param HelloSubmission
* @param deathrecExistsErrorHelloes
* @param isUpdate
* @param alertMessage
*/
private void checkMulErrMsg(PerformCreateUpdateEHelloResult HelloStatus,SampleMVCExampleSubmission HelloSubmission,
List<String> deathrecExistsErrorHelloes,boolean isUpdate){
if (HelloStatus.getSTATS().containsAll(deathrecExistsErrorHelloes)) {
LOG.debug("Death record already exists case");
if (Validator.isNotNull(HelloStatus.getEHelloAPPLNNO())) {

HelloSubmission.setEHelloApplicationNumber(HelloStatus.getEHelloAPPLNNO());
}
HelloSubmission.setStatus(isUpdate ? EHelloStatus.getStatusDesc(EHelloStatus.RESUBMIT_RECORD_ALREADY_EXIST_IN_DEATH_RECORD.getWsStatus(), DeathConstants.SUBMISSTION_TYPE_UPDATE)
:EHelloStatus.getStatusDesc(EHelloStatus.RECORD_ALREADY_EXIST_IN_DEATH_RECORD.getWsStatus()));

} else {
// Else if response contains multiple Helloes, persist the first Helloe
LOG.debug("Other multiple error Helloe");
HelloSubmission.setStatus(isUpdate? EHelloStatus.getStatusDesc(HelloStatus.getSTATS().get(0), DeathConstants.SUBMISSTION_TYPE_UPDATE)
: EHelloStatus.getStatusDesc(HelloStatus.getSTATS().get(0)));
}
}

/**
*
* @param HelloStatus
* @param HelloSubmission
* @param isUpdate
*/
private void checkSingleErrMsg(PerformCreateUpdateEHelloResult HelloStatus,SampleMVCExampleSubmission HelloSubmission,boolean isUpdate){
if (HelloStatus.getSTATS().get(0).equalsIgnoreCase(EHelloStatus.SUCCESS.getWsStatus())) {
LOG.debug("Success Helloe");
// Success Scenario
if (HelloStatus.getEHelloAPPLNNO() != null) {
HelloSubmission.setEHelloApplicationNumber(HelloStatus.getEHelloAPPLNNO());
HelloSubmission.setStatus(isUpdate? EHelloStatus.getStatusDesc(HelloStatus.getSTATS().get(0), DeathConstants.SUBMISSTION_TYPE_UPDATE)
: EHelloStatus.getStatusDesc(HelloStatus.getSTATS().get(0)));

}
} else {
LOG.debug("Single Error Helloe");
// Single Error Scenario
HelloSubmission.setStatus(isUpdate? EHelloStatus.getStatusDesc(HelloStatus.getSTATS().get(0), DeathConstants.SUBMISSTION_TYPE_UPDATE)
: EHelloStatus.getStatusDesc(HelloStatus.getSTATS().get(0)));
}
}
 
@RenderMapping(params = "render=editHelloView")
public ModelAndView editHello(RenderRequest renderRequest, RenderResponse renderResponse) throws NEHRPortalException {
String sessionDetails = HelloCommonUtil.sessionLogging(renderRequest);
LOG.info(sessionDetails + "Render edit Hello page");
HelloForm HelloForm = HelloRenderUtil.getHelloForm(renderRequest, 0, DeathConstants.JSP_EDIT_Hello_FORM);

return new ModelAndView(DeathConstants.JSP_EDIT_Hello_FORM, DeathConstants.PARAM_Hello_FORM_OBJ,
HelloForm);

}


@RenderMapping(params = "render=previewHelloView")
public ModelAndView previewHello(RenderRequest renderRequest, RenderResponse renderResponse) throws NEHRPortalException {

String sessionDetails = HelloCommonUtil.sessionLogging(renderRequest);
LOG.debug(sessionDetails + "Render preview Hello page");
HelloForm HelloForm = HelloRenderUtil.getHelloForm(renderRequest, 0, DeathConstants.JSP_Hello_PREVIEW);
ModelAndView modelAndView = new ModelAndView(DeathConstants.JSP_Hello_PREVIEW, DeathConstants.PARAM_Hello_FORM_OBJ, HelloForm);

modelAndView.addObject(DeathConstants.SUBMIT_ACCESS, true);
return modelAndView;
}
 
@RenderMapping(params = "render=printHelloView")
public ModelAndView printHello(RenderRequest renderRequest, RenderResponse renderResponse) throws NEHRPortalException {

String sessionDetails = HelloCommonUtil.sessionLogging(renderRequest);
LOG.debug(sessionDetails + "Render print Hello page");
HelloForm HelloForm = HelloRenderUtil.getHelloForm(renderRequest, 0, DeathConstants.JSP_Hello_SUCCESS_PRINT);
LOG.debug(sessionDetails + "HelloForm ID : " + HelloForm.getHelloSubmissionId());

return new ModelAndView(DeathConstants.JSP_Hello_SUCCESS_PRINT, DeathConstants.PARAM_Hello_FORM_OBJ,HelloForm);

}
 
/**
* This method is used to delete the EHello
* @param actionRequest
* @param actionResponse
*/
@ActionMapping(params = "action=deleteHello")
public void deleteHello(ActionRequest actionRequest, ActionResponse actionResponse) throws NEHRPortalException {
// USAGE: Invoked when user clicks on DeleteDraft button
String sessionDetails = HelloCommonUtil.sessionLogging(actionRequest);
LOG.debug(sessionDetails + "Inside deleteHello method");

// M001 - unauthorize deletion of record
// check if user has NEHR_FORMS_ICA_Hello_WRITE role, if not send error message to UI
if (!NEHRRoleUtil.checkRole(actionRequest, NEHRRoleUtil.RoleNames.NEHR_FORMS_ICA_Hello_WRITE.name())) {
LOG.debug(DeathConstants.USER_INSUFFICIENT_ROLE);
throw new NEHRPortalException(EHelloStatus.OTHER_ERROR.getMeaning());
}

long HelloSubmissionId = ParamUtil.getLong(actionRequest, DeathConstants.PARAM_Hello_SUBMISSION_ID);
String typeOfChange = ParamUtil.getString(actionRequest, DeathConstants.UPDATE_Hello, null);
String reasonForChange = ParamUtil.getString(actionRequest, DeathConstants.INPUT_REASON, null);
SampleMVCExampleSubmission updatedHelloSubmission = null;
LOG.debug(sessionDetails + "HelloSubmissionId of the EHello to be deleted: " + HelloSubmissionId + ", typeOfChange: " + typeOfChange + ", reasonForChange: " + reasonForChange);

try {
if (HelloSubmissionId > 0) {
SampleMVCExampleSubmission HelloSubToDelete = SampleMVCExampleSubmissionLocalServiceUtil.getSampleMVCExampleSubmission(HelloSubmissionId);
HelloSubToDelete.setTypeOfChange(typeOfChange);
HelloSubToDelete.setReasonForChange(reasonForChange);
LOG.debug(sessionDetails + "Deleting DRAFT. SampleMVCExampleSubmission to be deleted: " + HelloSubToDelete);
if((HelloSubToDelete.getStatus() == 0) || (HelloSubToDelete.getStatus() == 55)){
// CASE : HelloSubmission is in 1) Fresh Draft state (status=0) or 2) Updated submission draft (status=55)
SampleMVCExampleSubmissionLocalServiceUtil.deleteSampleMVCExampleSubmission(HelloSubToDelete.getHelloSubmissionId());

}else{
// CASE : HelloSubmission is in "Successful" submitted or "Updated Submission" state
// Update status of the form in DB to "55"
HelloSubToDelete.setStatus(EHelloStatus.PENDING_RESUBMISSION.getStatus());
updatedHelloSubmission = SampleMVCExampleSubmissionLocalServiceUtil.updateSampleMVCExampleSubmission(HelloSubToDelete);
LOG.debug(sessionDetails + "deleteHello update status for applNum: " + updatedHelloSubmission.getEHelloApplicationNumber() + " updated status: " + updatedHelloSubmission.getStatus());
}
LOG.info(sessionDetails + "Hello Sub to Delete Status: ", HelloSubToDelete.getStatus());
}
} catch (NoSuchSampleMVCExampleSubmissionException e) {
LOG.error("NoSuchSampleMVCExampleSubmissionException occured while deleting SampleMVCExampleSubmission form:", e);
} catch (SystemException e) {
LOG.error("SystemException occured while deleting SampleMVCExampleSubmission form:", e);
} catch (PortalException e) {
LOG.error("PortalException occured while getting the SampleMVCExampleSubmission from LR DB to be deleted:", e);
}

actionResponse.setRenderParameter(DeathConstants.STR_JSP, DeathConstants.JSP_Hello_HISTORY);
}


@ResourceMapping(value = "actionPrint")
public BaseJsonResponse print(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
String sessionDetails = HelloCommonUtil.sessionLogging(resourceRequest);
LOG.debug(sessionDetails + "EHello form printed");
return null;

}
 
@ResourceMapping(value = "checkLoggedInNRIC")
public BaseJsonResponse checkLoggedInNRIC(ResourceRequest resourceRequest) throws NEHRPortalException {
return HelloRenderUtil.getLoggedInNRICJson(resourceRequest);
}

/*
     * checkIsFormAvailable - This method is invoked in order to check
     * if any Successfully submitted Form Available.
     */
@ResourceMapping(value = "checkIsFormAvailable")
public BaseJsonResponse checkIsFormAvailable(ResourceRequest resourceRequest) throws NEHRPortalException {

return HelloRenderUtil.checkIsFormAvailable(resourceRequest);
}
 
private SampleMVCExampleSubmission getSampleMVCExampleSubmission(SampleMVCExampleSubmission SampleMVCExampleSubmission, List<SampleMVCExample> SampleMVCExampleList) {

SampleMVCExampleSubmission SampleMVCExampleSubmissionResp = null;
if (SampleMVCExampleSubmission == null) {
return SampleMVCExampleSubmissionResp;
}
try {

if (SampleMVCExampleSubmission.getHelloSubmissionId() == 0) {
LOG.debug("#########ADD Hello########");
SampleMVCExampleSubmissionResp = SampleMVCExampleSubmissionLocalServiceUtil.addSampleMVCExampleSubmission(SampleMVCExampleSubmission, SampleMVCExampleList);
} else {
LOG.debug("#########UPDATE Hello########");
SampleMVCExampleSubmissionResp = SampleMVCExampleSubmissionLocalServiceUtil.updateSampleMVCExampleSubmission(SampleMVCExampleSubmission, SampleMVCExampleList);

LOG.debug("HelloSubmissionID" + SampleMVCExampleSubmissionResp.getHelloSubmissionId());
}

} catch (SystemException e) {
throw new SystemException(e);
}

return SampleMVCExampleSubmissionResp;
}

/**
* Handles the redirection of the Current Module's Online Help
*
* @param request
* @param response
*/
@ActionMapping(value = "doOnlineHelpRedirect")
public void doOnlineHelpRedirect(ActionRequest request, ActionResponse response) throws NEHRPortalException {
LOG.debug("inside do online redirection : ACTION : ");
OnlineHelpUtil.doOnlineHelpRedirection(request, response);
}


@ResourceMapping(value = "clearEhcache")
    @ResponseBody
    public BaseJsonResponse clearEhcache(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {

BaseJsonResponse response = new BaseJsonResponse();

if(NEHRRoleUtil.checkRole(resourceRequest, RoleConstants.ADMINISTRATOR)){
try {
HelloCommonUtil.clearEhcache();
response.setEmptyMsg(DeathConstants.REFRESH_UPDATE_MSG);
} catch(NEHRPortalException e){
LOG.error("NEHRPortalException occurred in clearEhcache", e);
response.setEmptyMsg(DeathConstants.REFRESH_UPDATE_PROCESS_ERROR);
}
} else {
response.setEmptyMsg(DeathConstants.REFRESH_UPDATE_PERMISSION_ERROR_MSG);
}

return response;
}

/**
* "Restful" invocation of clearing cache, ideally via NEHRAdminWS Project
* @return BaseJsonResponse with emptyMsg populated with cache clearing message & status
*/
@ResourceMapping(value = "clearEhcacheAdmin")
    @ResponseBody
    public BaseJsonResponse clearEhcacheAdmin() {
BaseJsonResponse response = new BaseJsonResponse();
try{
HelloCommonUtil.clearEhcache();
LOG.debug("Cleared EHello cache.");
response.setEmptyMsg(DeathConstants.REFRESH_UPDATE_MSG);
Status status = new Status();
status.setHelloe(HttpStatus.OK.name());
status.setMeaning(HttpStatus.OK.getReasonPhrase());
response.setStatus(status);
}
catch(NEHRPortalException e){
LOG.error("NEHRPortalException occurred in clearEhcacheAdmin", e);
response.setEmptyMsg(DeathConstants.REFRESH_UPDATE_PROCESS_ERROR);
Status status = new Status();
status.setHelloe(HttpStatus.INTERNAL_SERVER_ERROR.name());
status.setMeaning(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
response.setStatus(status);
}
return response;
}

/**
* Redirection to update page with the latest version HelloSubmission record that is submitted successfully.
* @param renderRequest
* @param renderResponse
* @param model
* @return ModelAndView
*/
@RenderMapping(params = "render=updateHello")
public ModelAndView updateHello(RenderRequest renderRequest, RenderResponse renderResponse) {

String sessionDetails = HelloCommonUtil.sessionLogging(renderRequest);
LOG.debug(sessionDetails + "Render update Hello page");

HelloForm HelloForm = null;
try {
// retrieves the HelloForm
HelloForm = HelloRenderUtil.getHelloFormLatestVersion(renderRequest, DeathConstants.JSP_EDIT_Hello_FORM);
LOG.debug(sessionDetails + "HelloForm to be updated: " + HelloForm);
} catch (NEHRPortalException e) {
LOG.error("NEHRPortalException occurred in updateHello", e);
}

if (HelloForm != null) {
//setting submissionType to "U"- indicating this form is getting updated
HelloForm.setSubmissionType(DeathConstants.SUBMISSTION_TYPE_UPDATE);
}

return new ModelAndView(DeathConstants.JSP_EDIT_Hello_FORM, DeathConstants.PARAM_Hello_FORM_OBJ, HelloForm);
}

// Added for CR564
/**
* Method that will return search result in Cause of Death
* @param resourceRequest
* @param resourceResponse
* @return BaseJsonResponse
* need to set searchTxt, fieldFilterings,translatedSearchTermList
*/
@ResourceMapping(value = "getSearchResponseForHello")
public BaseJsonResponse getSearchResponseForHello(ResourceRequest resourceRequest, ResourceResponse resourceResponse) {
String sessionDetails = HelloCommonUtil.sessionLogging(resourceRequest);
LOG.info(sessionDetails + "HelloPortletController - getSearchResponseForHello : started");

BaseJsonResponse json = new BaseJsonResponse();
if (Validator.isNull(resourceRequest)){
LOG.error("HelloPortletController - getSearchResponseForHello: resourceRequest is null");
json = JsonUtil.populateErrorJSON(resourceResponse);
return json;
}
// fetch search text from UI
String searchTxt = ParamUtil.getString(resourceRequest, DeathConstants.SEARCH_TXT);
String noRecordsFound = HelloCommonUtil.getDBPropertyValue(DeathConstants.NO_RECORDS_FOUND);
// fetch frequent flag in UI
String frequentlySearch = ParamUtil.getString(resourceRequest, DeathConstants.FREQUENT);

if (StringUtils.isBlank(searchTxt) && StringUtils.isBlank(frequentlySearch)){
// return empty search result message to UI
LOG.error("HelloPortletController - getSearchResponseForHello : Search text is null or empty");
json.setEmptyMsg(noRecordsFound);
return json;
}

LOG.info(sessionDetails + "HelloPortletController - getSearchResponseForHello : SEARCH_TEXT= " + searchTxt + " FREQUENTLY_SEARCH= " + frequentlySearch);

List<TranslatedSearchTerm> translatedSearchTermList = new ArrayList<>();
if (StringUtils.isNotBlank(searchTxt)) {
try {
// get synonym / acronym value of the search text
translatedSearchTermList = HelloActionUtil.getTranslatedSearchTerms(HelloConstants.SEARCH_MODULE, searchTxt);
} catch (SystemException e) {
LOG.error("Error occurred in getTranslatedSearchTerms", e);
return JsonUtil.populateErrorJSON(resourceResponse);
}
}

// set required attributes into searchRF to pass to BE
SearchForm searchFilter = new SearchForm();
searchFilter.setSearchTxt(searchTxt);
searchFilter.setTranslatedSearchTermList(translatedSearchTermList);
searchFilter.setIndexAliases(new String[]{HelloCommonUtil.getDBPropertyValue(DeathConstants.Hello_SEARCH_INDEX)});

// fetch Hello type in UI
String type = ParamUtil.getString(resourceRequest, DeathConstants.TYPE);
LOG.info(sessionDetails + "HelloPortletController - getSearchResponseForHello : TYPE= " + type);

//Populate fieldFilterings
List<List<String>> fieldFilterings = HelloActionUtil.getFieldFilterings(frequentlySearch, type);

if(!CollectionUtils.isEmpty(fieldFilterings)){
// set the criteria for the search filters
LOG.debug("sessionDetails + HelloPortletController - getSearchResponseForHello : fieldFilterings > " + JsonUtil.convertObjectToJson(fieldFilterings));
searchFilter.setFieldFilterings(fieldFilterings);
}

// get page size from DB
String pageSize =  NEHRStringUtil.getPropsConfig(com.mohh.nehr.commonUtil.util.Constants.PROPSKEY_COMMON.value(),
com.mohh.nehr.commonUtil.util.Constants.LIST_DISPLAY_COUNT.value());

// construct searchCriteria
SearchCriteria searchCriteria = SearchCriteriaUtil.getPaginatedSearch(resourceRequest, Integer.valueOf(pageSize), true);
if (Validator.isNull(searchCriteria)) {
LOG.error("HelloPortletController - getSearchResponseForHello: searchCriteria is null");
json = JsonUtil.populateErrorJSON(resourceResponse);
return json;
}

// Set searchCriteria to SearchCriteria of ES
com.mohh.nehr.form.req.SearchCriteriaES searchCriteriaES = new com.mohh.nehr.form.req.SearchCriteriaES();
searchCriteriaES.setPageSize(searchCriteria.getPageSize());
searchCriteriaES.setStartSeq(searchCriteria.getStartSeq());
searchCriteriaES.setEndSeq(searchCriteria.getEndSeq());

try {
// invoke searchHello to get list of search result

ObjectMapper mapper = new ObjectMapper();

// Set requestForm and searchCriteria
SearchformWrapper searchformWrapper = new SearchformWrapper();
searchformWrapper.setRequestform(searchFilter);
searchformWrapper.setCriteria(searchCriteriaES);

//Object to JSON in String
String jsonString = mapper.writeValueAsString(searchformWrapper);

LOG.info(sessionDetails + "HelloPortletController - searchHello Request: " + jsonString);

List<MasterSearchForm> masterSearchFormList = getSearchFormList(jsonString);

if (CollectionUtils.isEmpty(masterSearchFormList)) {
// return empty search result message to UI
LOG.error("HelloPortletController - getSearchResponseForHello : No matching search result found");
json.setEmptyMsg(noRecordsFound);
return json;
}
// get current URL from request
String getCurrentCompleteURL = PortalUtil.getCurrentURL(resourceRequest);
// get httpSession from request
HttpSession httpSession = NEHRSessionUtil.getHttpSessionFromRequest(resourceRequest);
if (Validator.isNull(httpSession) || StringUtils.isEmpty(getCurrentCompleteURL)){
LOG.error("HelloPortletController - getSearchResponseForHello: httpSession or currentURL is null");
json = JsonUtil.populateErrorJSON(resourceResponse);
return json;
}

// invoke populateJsonWHelloSearchParams to paginate search result from searchHello
return HelloCommonUtil.populateJsonWHelloSearchParams(JsonUtil.populateJSONFormWintoutSHI(masterSearchFormList, searchCriteria.getPageSize(),
getCurrentCompleteURL, resourceRequest, searchCriteria.getStartSeq()-1, searchCriteria.getEndSeq()-1, true),
searchTxt, frequentlySearch, type, resourceResponse);
} catch (NEHRPortalException e) {
LOG.error("Error occurred in getSearchResponseForHello or populateJSONFormWintoutSHI", e);
return JsonUtil.populateErrorJSON(resourceResponse);
} catch (JsonProcessingException e) {
LOG.error(e.getMessage(),e);
return JsonUtil.populateErrorJSON(resourceResponse);
}
}

//extracted condition from ' getSearchResponseForHello' method
private List<MasterSearchForm> getSearchFormList(String jsonString) {
List<MasterSearchForm> masterSearchFormList = new ArrayList<>();
ResponseEntity<String> responseEntity = HelloCommonUtil.callSearchServiceActions(jsonString, CommonConstants.SEARCH_Hello_ACTION);
if (responseEntity != null && StringUtils.isNotEmpty(responseEntity.getBody())) {
masterSearchFormList = HelloCommonUtil.populateMasterSearchForm(responseEntity.getBody());
} else {
LOG.debug("HelloPortletController - getSearchResponseForHello: response or response body is empty");
}
return masterSearchFormList;
}
}

Comments

Popular posts from this blog

Codity Test and results

TTD - Test Driven Development for Java Programmers

Generics In Java: