<commit_before>/*******************************************************************************
 * Copyright SemanticBits, Northwestern University and Akaza Research
 * 
 * Distributed under the OSI-approved BSD 3-Clause License.
 * See http://ncip.github.com/caaers/LICENSE.txt for details.
 ******************************************************************************/
package gov.nih.nci.cabig.caaers.web.ae;

import gov.nih.nci.cabig.caaers.dao.ResearchStaffDao;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.ReportStatus;
import gov.nih.nci.cabig.caaers.domain.ResearchStaff;
import gov.nih.nci.cabig.caaers.domain.ReviewStatus;
import gov.nih.nci.cabig.caaers.domain.SiteResearchStaff;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.UserGroupType;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.security.SecurityUtils;
import gov.nih.nci.cabig.caaers.service.ReportSubmittability;
import gov.nih.nci.cabig.caaers.validation.ValidationError;
import gov.nih.nci.cabig.caaers.validation.ValidationErrors;
import gov.nih.nci.cabig.caaers.web.fields.InputField;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldAttributes;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LazyInitializationException;
import org.springframework.beans.BeanWrapper;
import org.springframework.validation.Errors;

/**
 * @author <NAME>
 * @author <NAME>
 */
public class ViewReportTab extends AeTab {

	private ResearchStaffDao researchStaffDao;
	private StudyDao studyDao;
	private static final Log log = LogFactory.getLog(ViewReportTab.class);
	
    public ViewReportTab() {
        super("Submission", ExpeditedReportSection.SUBMIT_REPORT_SECTION.getDisplayName(),"ae/submit");
    }

    @Override
    public void postProcess(HttpServletRequest request, ExpeditedAdverseEventInputCommand command, Errors errors) {
        handleWithdrawAction(command, request.getParameter("_action"), request.getParameter("_selected"));
    }

    @Override
    public Map<String, Object> referenceData(HttpServletRequest request, ExpeditedAdverseEventInputCommand command) {

        Map<String, Object> refdata = super.referenceData(request,command);
        Map<Integer, ReportSubmittability> reportMessages = new HashMap<Integer, ReportSubmittability>();

        // evaluate business rules.
        ReportSubmittability commonReportSubmittability = new ReportSubmittability();
        for (ExpeditedReportSection section : ExpeditedReportSection.values()) {

            if (!section.isAssociatedToBusinessRules()) continue;
            if(section.equals(ExpeditedReportSection.ATTRIBUTION_SECTION) && !command.shouldValidateAttributions())  continue;

            ValidationErrors validationErrors = evaluationService.validateReportingBusinessRules( command.getAeReport(), section);
            for (ValidationError vError : validationErrors.getErrors()) {
            	if(command.isErrorApplicable(vError.getFieldNames())){
            		commonReportSubmittability.addValidityMessage(section, messageSource.getMessage(vError.getCode(), vError.getReplacementVariables(), vError.getMessage(), Locale.getDefault()));
            	}
            }
        }

        //reportMessages.put(ExpeditedAdverseEventInputCommand.ZERO, commonReportSubmittability);

        // -- check the report submittability
        for (Report report : command.getAeReport().getActiveReports()) {
        	ReportSubmittability reportSubmittability = reportValidationService.isSubmittable(report);
            reportMessages.put(report.getId(), reportSubmittability);
            // Merge the commonValidationErros with the errors for individual reports.
            if(!commonReportSubmittability.getMessages().isEmpty()){
            	for(ExpeditedReportSection section: commonReportSubmittability.getMessages().keySet()){
            		if(reportSubmittability.getMessages().containsKey(section))
            			reportSubmittability.getMessages().get(section).addAll(commonReportSubmittability.getMessages().get(section));
            		else
            			reportSubmittability.getMessages().put(section, commonReportSubmittability.getMessages().get(section));
            	}
            }
        }
        refdata.put("reportMessages", reportMessages);
        
        Map<Integer, Boolean> renderSubmitLink = initializeRenderSubmitLinkMap(command);
        refdata.put("renderSubmitLink", renderSubmitLink);
        
    	boolean isSuperUser = SecurityUtils.checkAuthorization(UserGroupType.caaers_super_user);
    	refdata.put("isSuperUser", isSuperUser);
    	
        return refdata;
    }


    /**
     * Will return true if the user is an Expedited Report Reviewer at the Cooordinating Center.
     * @return
     */
    private Boolean isUserAEReviewer(Study study){

        boolean userAEReviewer = false;
        String loginId = SecurityUtils.getUserLoginName();
        boolean isReportReviewer = SecurityUtils.checkAuthorization(UserGroupType.ae_expedited_report_reviewer);

        //now check if the sae coordinator is associated to the coordinaoting center
        if(isReportReviewer && study != null){
            Organization ccOrg = getStudyCoordinatingOrg(study);
            ResearchStaff researchStaff = researchStaffDao.getByLoginId(loginId);
            if(researchStaff != null && ccOrg != null){
                for(SiteResearchStaff siteRs : researchStaff.getSiteResearchStaffsInternal()){
                    if(siteRs.getOrganization().getId().equals(ccOrg.getId())){
                        userAEReviewer = true;
                        break;
                    }
                }
            }
        }

       return userAEReviewer;
    }
    
    private Organization getStudyCoordinatingOrg(Study study) {
    	Organization org = null;
    	try {
    		org = study.getStudyCoordinatingCenter().getOrganization();
    	} catch(LazyInitializationException lie) {
    		log.info("Sending unloaded study Data, reloading study to avoid error.", lie);
    		study = studyDao.getById(study.getId());
    		org = study.getStudyCoordinatingCenter().getOrganization();
    	}
    	return org;
	}
<commit_msg>CAAERS-7151, instatiate a collection since it can't be caught.<commit_after>/*******************************************************************************
 * Copyright SemanticBits, Northwestern University and Akaza Research
 * 
 * Distributed under the OSI-approved BSD 3-Clause License.
 * See http://ncip.github.com/caaers/LICENSE.txt for details.
 ******************************************************************************/
package gov.nih.nci.cabig.caaers.web.ae;

import gov.nih.nci.cabig.caaers.dao.ResearchStaffDao;
import gov.nih.nci.cabig.caaers.dao.StudyDao;
import gov.nih.nci.cabig.caaers.domain.Organization;
import gov.nih.nci.cabig.caaers.domain.ReportStatus;
import gov.nih.nci.cabig.caaers.domain.ResearchStaff;
import gov.nih.nci.cabig.caaers.domain.ReviewStatus;
import gov.nih.nci.cabig.caaers.domain.SiteResearchStaff;
import gov.nih.nci.cabig.caaers.domain.Study;
import gov.nih.nci.cabig.caaers.domain.UserGroupType;
import gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection;
import gov.nih.nci.cabig.caaers.domain.report.Report;
import gov.nih.nci.cabig.caaers.security.SecurityUtils;
import gov.nih.nci.cabig.caaers.service.ReportSubmittability;
import gov.nih.nci.cabig.caaers.validation.ValidationError;
import gov.nih.nci.cabig.caaers.validation.ValidationErrors;
import gov.nih.nci.cabig.caaers.web.fields.InputField;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldAttributes;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldFactory;
import gov.nih.nci.cabig.caaers.web.fields.InputFieldGroup;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LazyInitializationException;
import org.springframework.beans.BeanWrapper;
import org.springframework.validation.Errors;

/**
 * @author <NAME>
 * @author <NAME>
 */
public class ViewReportTab extends AeTab {

	private ResearchStaffDao researchStaffDao;
	private StudyDao studyDao;
	private static final Log log = LogFactory.getLog(ViewReportTab.class);
	
    public ViewReportTab() {
        super("Submission", ExpeditedReportSection.SUBMIT_REPORT_SECTION.getDisplayName(),"ae/submit");
    }

    @Override
    public void postProcess(HttpServletRequest request, ExpeditedAdverseEventInputCommand command, Errors errors) {
        handleWithdrawAction(command, request.getParameter("_action"), request.getParameter("_selected"));
    }

    @Override
    public Map<String, Object> referenceData(HttpServletRequest request, ExpeditedAdverseEventInputCommand command) {

        Map<String, Object> refdata = super.referenceData(request,command);
        Map<Integer, ReportSubmittability> reportMessages = new HashMap<Integer, ReportSubmittability>();

        // evaluate business rules.
        ReportSubmittability commonReportSubmittability = new ReportSubmittability();
        for (ExpeditedReportSection section : ExpeditedReportSection.values()) {

            if (!section.isAssociatedToBusinessRules()) continue;
            if(section.equals(ExpeditedReportSection.ATTRIBUTION_SECTION) && !command.shouldValidateAttributions())  continue;

            ValidationErrors validationErrors = evaluationService.validateReportingBusinessRules( command.getAeReport(), section);
            for (ValidationError vError : validationErrors.getErrors()) {
            	if(command.isErrorApplicable(vError.getFieldNames())){
            		commonReportSubmittability.addValidityMessage(section, messageSource.getMessage(vError.getCode(), vError.getReplacementVariables(), vError.getMessage(), Locale.getDefault()));
            	}
            }
        }

        //reportMessages.put(ExpeditedAdverseEventInputCommand.ZERO, commonReportSubmittability);

        // -- check the report submittability
        for (Report report : command.getAeReport().getActiveReports()) {
        	ReportSubmittability reportSubmittability = reportValidationService.isSubmittable(report);
            reportMessages.put(report.getId(), reportSubmittability);
            // Merge the commonValidationErros with the errors for individual reports.
            if(!commonReportSubmittability.getMessages().isEmpty()){
            	for(ExpeditedReportSection section: commonReportSubmittability.getMessages().keySet()){
            		if(reportSubmittability.getMessages().containsKey(section))
            			reportSubmittability.getMessages().get(section).addAll(commonReportSubmittability.getMessages().get(section));
            		else
            			reportSubmittability.getMessages().put(section, commonReportSubmittability.getMessages().get(section));
            	}
            }
        }
        refdata.put("reportMessages", reportMessages);
        
        Map<Integer, Boolean> renderSubmitLink = initializeRenderSubmitLinkMap(command);
        refdata.put("renderSubmitLink", renderSubmitLink);
        
    	boolean isSuperUser = SecurityUtils.checkAuthorization(UserGroupType.caaers_super_user);
    	refdata.put("isSuperUser", isSuperUser);
    	
        return refdata;
    }


    /**
     * Will return true if the user is an Expedited Report Reviewer at the Cooordinating Center.
     * @return
     */
    private Boolean isUserAEReviewer(Study study){

        boolean userAEReviewer = false;
        String loginId = SecurityUtils.getUserLoginName();
        boolean isReportReviewer = SecurityUtils.checkAuthorization(UserGroupType.ae_expedited_report_reviewer);

        //now check if the sae coordinator is associated to the coordinaoting center
        if(isReportReviewer && study != null){
            Organization ccOrg = getStudyCoordinatingOrg(study);
            ResearchStaff researchStaff = researchStaffDao.getByLoginId(loginId);
            if(researchStaff != null && ccOrg != null){
                for(SiteResearchStaff siteRs : researchStaff.getSiteResearchStaffsInternal()){
                    if(siteRs.getOrganization().getId().equals(ccOrg.getId())){
                        userAEReviewer = true;
                        break;
                    }
                }
            }
        }

       return userAEReviewer;
    }
    
    private Organization getStudyCoordinatingOrg(Study study) {
    	Organization org = null;
    	study = studyDao.getById(study.getId());
		org = study.getStudyCoordinatingCenter().getOrganization();
    	/* LazyInitializationException cannot be reliably caught.
    	 * try {
    		org = study.getStudyCoordinatingCenter().getOrganization();
    	} catch(LazyInitializationException lie) {
    		log.info("Sending unloaded study Data, reloading study to avoid error.", lie);
    		study = studyDao.getById(study.getId());
    		org = study.getStudyCoordinatingCenter().getOrganization();
    	}*/
    	return org;
	}

{'fraction_non_alphanumeric': 0.11979590327590031, 'fraction_numerical': 0.00044368853065148263, 'mean_word_length': 3.7419354838709675, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2280914', 'n_tokens_mistral': 3941, 'n_tokens_neox': 3802, 'n_words': 624}