<commit_before>/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.web.controller.encounter;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Encounter;
import org.openmrs.EncounterType;
import org.openmrs.Form;
import org.openmrs.FormField;
import org.openmrs.Location;
import org.openmrs.Obs;
import org.openmrs.Visit;
import org.openmrs.api.APIException;
import org.openmrs.api.EncounterService;
import org.openmrs.api.FormService;
import org.openmrs.api.context.Context;
import org.openmrs.propertyeditor.EncounterTypeEditor;
import org.openmrs.propertyeditor.FormEditor;
import org.openmrs.propertyeditor.LocationEditor;
import org.openmrs.propertyeditor.VisitEditor;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.util.PrivilegeConstants;
import org.openmrs.web.WebConstants;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

/**
 * This class controls the encounter.form jsp page. See
 * /web/WEB-INF/view/admin/encounters/encounterForm.jsp
 */
public class EncounterFormController extends SimpleFormController {
	
	/** Logger for this class and subclasses */
	protected final Log log = LogFactory.getLog(getClass());
	
	/**
	 * Allows for Integers to be used as values in input tags. Normally, only strings and lists are
	 * expected
	 * 
	 * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
	 *      org.springframework.web.bind.ServletRequestDataBinder)
	 */
	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);
		
		binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, true));
		binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(Context.getDateFormat(), true));
		binder.registerCustomEditor(EncounterType.class, new EncounterTypeEditor());
		binder.registerCustomEditor(Location.class, new LocationEditor());
		binder.registerCustomEditor(Form.class, new FormEditor());
		binder.registerCustomEditor(Visit.class, new VisitEditor());
	}
	
	/**
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse reponse, Object obj,
	        BindException errors) throws Exception {
		
		Encounter encounter = (Encounter) obj;
		
		try {
			if (Context.isAuthenticated()) {
				Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);
				Context.addProxyPrivilege(PrivilegeConstants.VIEW_PATIENTS);
				
				if (StringUtils.hasText(request.getParameter("patientId")))
					encounter.setPatient(Context.getPatientService().getPatient(
					    Integer.valueOf(request.getParameter("patientId"))));
				if (StringUtils.hasText(request.getParameter("providerId")))
					encounter.setProvider(Context.getPersonService().getPerson(
					    Integer.valueOf(request.getParameter("providerId"))));
				if (encounter.isVoided())
					ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voidReason", "error.null");
				
				ValidationUtils.rejectIfEmptyOrWhitespace(errors, "patient", "error.null");
				ValidationUtils.rejectIfEmptyOrWhitespace(errors, "provider", "error.null");
				ValidationUtils.rejectIfEmptyOrWhitespace(errors, "encounterDatetime", "error.null");
				
			}
		}
		finally {
			Context.removeProxyPrivilege(PrivilegeConstants.VIEW_USERS);
			Context.removeProxyPrivilege(PrivilegeConstants.VIEW_PATIENTS);
		}
		
		return super.processFormSubmission(request, reponse, encounter, errors);
	}
	
	/**
	 * The onSubmit function receives the form/command object that was modified by the input form
	 * and saves it to the db
	 * 
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
	        BindException errors) throws Exception {
		
		HttpSession httpSession = request.getSession();
		
		String view = getFormView();
		
		try {
			Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);
			Context.addProxyPrivilege(PrivilegeConstants.VIEW_PATIENTS);
			
			if (Context.isAuthenticated()) {
				Encounter encounter = (Encounter) obj;
				
				// if this is a new encounter, they can specify a patient.  add it
				if (request.getParameter("patientId") != null)
					encounter.setPatient(Context.getPatientService().getPatient(
					    Integer.valueOf(request.getParameter("patientId"))));
				
				// set the provider if they changed it
				encounter.setProvider(Context.getPersonService().getPerson(
				    Integer.valueOf(request.getParameter("providerId"))));
				
				if (encounter.isVoided() && encounter.getVoidedBy() == null)
					// if this is a "new" voiding, call voidEncounter to set appropriate attributes
					Context.getEncounterService().voidEncounter(encounter, encounter.getVoidReason());
				else if (!encounter.isVoided() && encounter.getVoidedBy() != null)
					// if this was just unvoided, call unvoidEncounter to unset appropriate attributes
					Context.getEncounterService().unvoidEncounter(encounter);
				else
					Context.getEncounterService().saveEncounter(encounter);
				
				view = getSuccessView();
				view = view + "?encounterId=" + encounter.getEncounterId();
				
				httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Encounter.saved");
			}
		}
		catch (APIException e) {
			log.error("Error while trying to save the encounter", e);
			httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Encounter.cannot.save");
			errors.reject("encounter", "Encounter.cannot.save");
			// return to the form because an exception was thrown
			return showForm(request, response, errors);
		}<commit_msg>Cannot submit an encounter form - TRUNK-2716<commit_after>/**
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.web.controller.encounter;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Encounter;
import org.openmrs.EncounterType;
import org.openmrs.Form;
import org.openmrs.FormField;
import org.openmrs.Location;
import org.openmrs.Obs;
import org.openmrs.Visit;
import org.openmrs.api.APIException;
import org.openmrs.api.EncounterService;
import org.openmrs.api.FormService;
import org.openmrs.api.context.Context;
import org.openmrs.propertyeditor.EncounterTypeEditor;
import org.openmrs.propertyeditor.FormEditor;
import org.openmrs.propertyeditor.LocationEditor;
import org.openmrs.propertyeditor.VisitEditor;
import org.openmrs.util.OpenmrsConstants;
import org.openmrs.util.OpenmrsUtil;
import org.openmrs.util.PrivilegeConstants;
import org.openmrs.web.WebConstants;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

/**
 * This class controls the encounter.form jsp page. See
 * /web/WEB-INF/view/admin/encounters/encounterForm.jsp
 */
public class EncounterFormController extends SimpleFormController {
	
	/** Logger for this class and subclasses */
	protected final Log log = LogFactory.getLog(getClass());
	
	/**
	 * Allows for Integers to be used as values in input tags. Normally, only strings and lists are
	 * expected
	 * 
	 * @see org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
	 *      org.springframework.web.bind.ServletRequestDataBinder)
	 */
	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		super.initBinder(request, binder);
		
		binder.registerCustomEditor(java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, true));
		binder.registerCustomEditor(java.util.Date.class, new CustomDateEditor(Context.getDateFormat(), true));
		binder.registerCustomEditor(EncounterType.class, new EncounterTypeEditor());
		binder.registerCustomEditor(Location.class, new LocationEditor());
		binder.registerCustomEditor(Form.class, new FormEditor());
		binder.registerCustomEditor(Visit.class, new VisitEditor());
	}
	
	/**
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#processFormSubmission(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse reponse, Object obj,
	        BindException errors) throws Exception {
		
		Encounter encounter = (Encounter) obj;
		
		try {
			if (Context.isAuthenticated()) {
				Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);
				Context.addProxyPrivilege(PrivilegeConstants.VIEW_PATIENTS);
				
				if (StringUtils.hasText(request.getParameter("patientId")))
					encounter.setPatient(Context.getPatientService().getPatient(
					    Integer.valueOf(request.getParameter("patientId"))));
				if (encounter.isVoided())
					ValidationUtils.rejectIfEmptyOrWhitespace(errors, "voidReason", "error.null");
				
				ValidationUtils.rejectIfEmptyOrWhitespace(errors, "patient", "error.null");
				ValidationUtils.rejectIfEmptyOrWhitespace(errors, "encounterDatetime", "error.null");
				
			}
		}
		finally {
			Context.removeProxyPrivilege(PrivilegeConstants.VIEW_USERS);
			Context.removeProxyPrivilege(PrivilegeConstants.VIEW_PATIENTS);
		}
		
		return super.processFormSubmission(request, reponse, encounter, errors);
	}
	
	/**
	 * The onSubmit function receives the form/command object that was modified by the input form
	 * and saves it to the db
	 * 
	 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
	 *      org.springframework.validation.BindException)
	 */
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
	        BindException errors) throws Exception {
		
		HttpSession httpSession = request.getSession();
		
		String view = getFormView();
		
		try {
			Context.addProxyPrivilege(PrivilegeConstants.VIEW_USERS);
			Context.addProxyPrivilege(PrivilegeConstants.VIEW_PATIENTS);
			
			if (Context.isAuthenticated()) {
				Encounter encounter = (Encounter) obj;
				
				// if this is a new encounter, they can specify a patient.  add it
				if (request.getParameter("patientId") != null)
					encounter.setPatient(Context.getPatientService().getPatient(
					    Integer.valueOf(request.getParameter("patientId"))));
				
				if (encounter.isVoided() && encounter.getVoidedBy() == null)
					// if this is a "new" voiding, call voidEncounter to set appropriate attributes
					Context.getEncounterService().voidEncounter(encounter, encounter.getVoidReason());
				else if (!encounter.isVoided() && encounter.getVoidedBy() != null)
					// if this was just unvoided, call unvoidEncounter to unset appropriate attributes
					Context.getEncounterService().unvoidEncounter(encounter);
				else
					Context.getEncounterService().saveEncounter(encounter);
				
				view = getSuccessView();
				view = view + "?encounterId=" + encounter.getEncounterId();
				
				httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Encounter.saved");
			}
		}
		catch (APIException e) {
			log.error("Error while trying to save the encounter", e);
			httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Encounter.cannot.save");
			errors.reject("encounter", "Encounter.cannot.save");
			// return to the form because an exception was thrown
			return showForm(request, response, errors);
		}
{'fraction_non_alphanumeric': 0.10084659668134101, 'fraction_numerical': 0.0005418218760582459, 'mean_word_length': 5.03432774826318, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '2408708', 'n_tokens_mistral': 4593, 'n_tokens_neox': 4145, 'n_words': 897}