<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.module.hl7query.util;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

/**
 * The ExceptionUtil class is responsible for creating json / xml formatted based on the parameters received from the controller class
 *
 */

public class ExceptionUtil {
	
	public static Object generateMessage(HttpServletRequest request, HttpServletResponse response, ErrorDetailsEnum error, String segment){
		boolean isPipeDelimited = false;
		
		String acceptHeader = request.getHeader("Accept");
		if (acceptHeader == null || !acceptHeader.contains("text/xml"))
				isPipeDelimited = true;
		
		if(isPipeDelimited){
			//If pipe delimited, create message in json format
			response.setContentType("application/json");
			return writeJsonMessage(error, segment);		
			}else{
			//if not, create message in xml format
				response.setContentType("text/xml");
			return writeXmlMessage(error, segment);	
			}
	}

	private static Object writeJsonMessage(ErrorDetailsEnum error, String segment) {
		String errorMsg = null; 
		ObjectMapper mapper = new ObjectMapper();
		ErrorMessageTemplate errorMessageTemplate = new ErrorMessageTemplate();
		errorMessageTemplate.setError(error);
		
		if(segment != null)
			errorMsg = error.getMessage().toString() + " " + segment;
		else
			errorMsg = error.getMessage().toString();
			
		errorMessageTemplate.setErrorMessage(errorMsg);
		errorMessageTemplate.setErrorCode(Integer.toString(error.getCode()));

		Writer strWriter = new StringWriter();
		try {
			mapper.writeValue(strWriter, errorMessageTemplate);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String userDataJSON = strWriter.toString();
		System.out.println(userDataJSON);

		return userDataJSON;
	}
	
	private static Object writeXmlMessage(ErrorDetailsEnum error, String segment) {
		String xmlString = null;
		String errorDescription = null;<commit_msg>Adding javadoc // needs improvement<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.module.hl7query.util;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

/**
 * The ExceptionUtil class is responsible for creating json / xml formatted based on the parameters received from the controller class
 *
 */

public class ExceptionUtil {
	
	protected final Log log = LogFactory.getLog(getClass());
	
	/**
	 * 
	 * @param request 
	 * 		The http request object made by the user
	 * @param response
	 * 		The http response object returned to the user
	 * @param error
	 * 		The error message object which contains the appopriate error message description and the error code
	 * @param segment
	 * 		An additional (optional) string used to contain additional details (etc. which parameter is causing the error)
	 * @return
	 * 		An appopriately formed error message object containing details of  the error
	 * 
	 * Based on the users request, the generateMessage() method will call either of two methods - writeJsonMessage() or writeXmlMessage().
	 * These methods are responsible for creating a well formed error message 
	 */
	public static Object generateMessage(HttpServletRequest request, HttpServletResponse response, ErrorDetailsEnum error, String segment){
		boolean isPipeDelimited = false;
		
		//check the users request header, and decide which method to call
		String acceptHeader = request.getHeader("Accept");
		if (acceptHeader == null || !acceptHeader.contains("text/xml"))
				isPipeDelimited = true;
		
		if(isPipeDelimited){
			//If pipe delimited, create message in json format
			response.setContentType("application/json");
			return writeJsonMessage(error, segment);		
			}else{
			//if not, create message in xml format
				response.setContentType("text/xml");
			return writeXmlMessage(error, segment);	
			}
	}

	/**
	 * 
	 * @param error
	 * 		The error message object which contains the appopriate error message description and the error code
	 * @param segment
	 * 		An additional (optional) string used to contain additional details (etc. which parameter is causing the error)
	 * @return
	 * 		An appopriately formed error message object containing details of  the error
	 * 
	 * This message is triggered is the user had wanted the response hl7 message to be in pipe delimited format
	 */
	private static Object writeJsonMessage(ErrorDetailsEnum error, String segment) {
		String errorMsg = null; 
		ObjectMapper mapper = new ObjectMapper();
		ErrorMessageTemplate errorMessageTemplate = new ErrorMessageTemplate();
		errorMessageTemplate.setError(error);
		
		//The segment is optional, it contains additional error message details
		if(segment != null)
			errorMsg = error.getMessage().toString() + " " + segment;
		else
			errorMsg = error.getMessage().toString();
			
		errorMessageTemplate.setErrorMessage(errorMsg);
		errorMessageTemplate.setErrorCode(Integer.toString(error.getCode()));

		Writer strWriter = new StringWriter();
		try {
			mapper.writeValue(strWriter, errorMessageTemplate);
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String userDataJSON = strWriter.toString();

		return userDataJSON;
	}
	
	/**
	 * 
	 * @param error
	 * 		The error message object which contains the appopriate error message description and the error code
	 * @param segment
	 * 		An additional (optional) string used to contain additional details (etc. which parameter is causing the error)
	 * @return
	 * 		An appopriately formed error message object containing details of  the error
	 * This message is triggered is the user had wanted the response hl7 message to be in pipe delimited format
	 */
	private static Object writeXmlMessage(ErrorDetailsEnum error, String segment) {
		String xmlString = null;
		String errorDescription = null;
{'fraction_non_alphanumeric': 0.08457238015939099, 'fraction_numerical': 0.0016652789342214821, 'mean_word_length': 4.488250652741514, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 24}, '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': '3957261', 'n_tokens_mistral': 2410, 'n_tokens_neox': 2195, 'n_words': 770}