<commit_before>/*
* Copyright (c) 2013 <NAME>
* Permission is hereby granted, free of charge, to any person obtaining a copy of 
* this software and associated documentation files (the "Software"), to deal in the 
* Software without restriction, including without limitation the rights to use, copy, 
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
* to permit persons to whom the Software is furnished to do so, subject to the following conditions: 
* The above copyright notice and this permission notice shall be included in all copies or substantial 
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mapviewer.business.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

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

import com.mapviewer.business.LayerMenuManagerSingleton;
import com.mapviewer.business.NetCDFRequestManager;
import com.mapviewer.business.OpenLayersManager;
import com.mapviewer.business.UserRequestManager;
import com.mapviewer.conf.OpenLayerMapConfig;
import com.mapviewer.exceptions.XMLFilesException;
import com.mapviewer.exceptions.XMLLayerException;
import com.mapviewer.model.Layer;
import com.mapviewer.model.PagesNames;
import com.mapviewer.model.menu.MenuEntry;
import com.mapviewer.model.menu.TreeMenuUtils;
import com.mapviewer.model.menu.TreeNode;
import com.mapviewer.tools.HtmlMenuBuilder;
import java.io.FileNotFoundException;
import java.util.Arrays;

/**
 * Servelet to process all the request of the user and incharge of presenting the client
 * with the OpenLayers configuration
 *
 *
 * @author <NAME>
 */
public class MapViewerServlet extends HttpServlet {

	OpenLayersManager opManager;//OpenLayers Code
	OpenLayerMapConfig mapConfig;
	NetCDFRequestManager ncManager;// This object is used to manage the netcdf curr_main_layers
	String[] linksVectorialesKmz;
	String configFilePath;

	Boolean exceptionInitializingVariables = false;

	/**
	 * Initiliazes the varibles of the Servlet 
	 * @throws FileNotFoundException
	 * @throws XMLFilesException
	 * @throws XMLLayerException 
	 */
	private void initializeVariables() throws FileNotFoundException, XMLFilesException, XMLLayerException{
			mapConfig = OpenLayerMapConfig.getInstance();

			configFilePath = getServletContext().getRealPath("/WEB-INF/conf/MapViewConfig.properties");

			mapConfig.updateProperties(configFilePath);
            
			//Obtains the folder where XML layers file is stored.
			String layersFolder = getServletContext().getRealPath("/layers/");
			String baseLayerMenuOrientation = mapConfig.getProperty("baseLayerMenuOrientation");
			HtmlMenuBuilder.baseLayerMenuOrientation = baseLayerMenuOrientation;

			LayerMenuManagerSingleton.setLayersFolder(layersFolder);//Set the layers folder

			opManager = new OpenLayersManager();//initialize the OpenLayers
			ncManager = new NetCDFRequestManager();
            LayerMenuManagerSingleton.getInstance().refreshTree(true);//Initializes all the layers from the XML files
	}
	/**
	 * Initializes the object that controls the access to the server
	 *
	 */
	@Override
	public void init() throws ServletException {
		try {
			initializeVariables();
		} catch (XMLFilesException ex) {
			exceptionInitializingVariables = true;
			Logger.getLogger(MapViewerServlet.class.getName()).log(Level.SEVERE, null, ex);
		} catch (FileNotFoundException ex) {
			Logger.getLogger(MapViewerServlet.class.getName()).log(Level.SEVERE, null, ex);
		}
		
		super.init();
	}
	
	/**
	 * Processes requests for both HTTP
	 * <code>GET</code> and
	 * <code>POST</code> methods.
	 *
	 * @param {HttpServletRequest} request servlet request
	 * @param {HttpServletResponse} response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
    @SuppressWarnings("UnusedAssignment")
	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String nextPage = PagesNames.ERROR_PAGE;//error page, this gets modified if everything is fine.
		mapConfig.updateProperties(configFilePath);
		//its important to erase the basePath becuase it get appended again.
		try {
			
			response.setContentType("text/html;charset=iso-8859-1");
			HttpSession session = request.getSession();//Se obtiene la sesion
			
			TreeNode arbolMenuRasters = null;
            //If there was a problem initializing the variables we try to do it again.
			// This code catches information about the exception and displays it for the user.
			try {
                
				if(exceptionInitializingVariables){
                    initializeVariables();
                }
				arbolMenuRasters = UserRequestManager.createNewRootMenu(request, session);
				exceptionInitializingVariables = false;
			} catch (XMLFilesException ex) {
                //If an exception happens, we start with the default menu
				arbolMenuRasters = UserRequestManager.createNewRootMenu(request, session);
				session.setAttribute("MenuDelUsuario", arbolMenuRasters);
				//If there is an XMLLayerException exception we just display it as
				// warning in the main site
                StringWriter sw = new StringWriter();
				ex.printStackTrace(new PrintWriter(sw));
				String exceptionInfo = ex.getMessage();
				String exceptionTrace = sw.toString();
				exceptionTrace = exceptionTrace.substring(0, exceptionTrace.indexOf("\n"));
				exceptionTrace = exceptionTrace.replace("\"","");
				exceptionTrace = exceptionTrace.replace("\'","");
				exceptionInfo = exceptionInfo.replace("\"","");
				exceptionInfo = exceptionInfo.replace("\'","");
				
				request.setAttribute("warningText", exceptionInfo);
				request.setAttribute("warningInfo", exceptionTrace);
				
				exceptionInitializingVariables = true;
			}
            
			if(linksVectorialesKmz  == null){
				linksVectorialesKmz = UserRequestManager.getCheckboxKmlLinks(opManager.getVectorLayers());
				HtmlMenuBuilder.vecLinks = linksVectorialesKmz;
			}
			
			//get menu entry
			MenuEntry[] rasterSelecteLayers = TreeMenuUtils.obtieneMenuSeleccionado(arbolMenuRasters);
            
			//obtain layer index
			int[] baseLayers = opManager.obtainArrayIndexOfLayers(rasterSelecteLayers);
            Layer curr_main_layer = null;
            //this variables are then read by the GlobalJavascript.jsp
            //The next variable is used to decide if the layer has
            // a custom CQL filter
            request.setAttribute("cqlfilter", false);
            if(baseLayers != null) {
                curr_main_layer = opManager.getRasterLayers().get(baseLayers[0]); //get main layer of user
                request.setAttribute("ncwms", curr_main_layer.isncWMS());
                request.setAttribute("currents", curr_main_layer.isoverlayStreamlines());
                request.setAttribute("layerDetails", curr_main_layer.getLayerDetails());
                request.setAttribute("zaxis", curr_main_layer.isZaxis());
                request.setAttribute("multipleDates", curr_main_layer.isMultipleDates());
                request.setAttribute("mainLayer", curr_main_layer.getName());
                request.setAttribute("style", curr_main_layer.getStyle());
                request.setAttribute("max_time_range", curr_main_layer.getMaxTimeLayer());
                request.setAttribute("cqlcols", curr_main_layer.getCql_cols());
                if (!curr_main_layer.getCql_cols().equals("")) {
                    request.setAttribute("cqlfilter", true);
                }
            } else {
                request.setAttribute("ncwms", false);
                request.setAttribute("currents", null);
                request.setAttribute("layerDetails", "{}");
                request.setAttribute("zaxis", null);
                request.setAttribute("multipleDates", "null");
                request.setAttribute("mainLayer", null);
                request.setAttribute("style", null);
                request.setAttribute("max_time_range", null);
                request.setAttribute("cqlcols", null);
            }
			
			//Obtains and set a lenguage.
			
			String defaultLang=mapConfig.getProperty("defaultLanguage");
			String availableLanguages=mapConfig.getProperty("availableLanguages");
			int imageResolution = Integer.parseInt(mapConfig.getProperty("imageResolution"));
            
            request.setAttribute("imageResolution", imageResolution);
            
			request.setAttribute("defaultLanguage", defaultLang);
			request.setAttribute("availableLanguages", availableLanguages);
            
            //Setting the locale gotten from the one seleted by the user on the website
			String language=request.getParameter("_locale");
			
			//setting Default locale from the properties file on first time page load
			if(language==null || "".equals(language)){
				language=defaultLang;
			}

            //get and set background layers
            
            String defaultBackgroundLayer = mapConfig.getProperty("backgroundLayer");
			String backgroundLayer = request.getParameter("backgroundLayer");
            backgroundLayer =  (backgroundLayer == null || "".equals(backgroundLayer)) ? defaultBackgroundLayer : backgroundLayer;
            //get the resolution for a selected background layer
            if(! backgroundLayer.equals(defaultBackgroundLayer)) {
                String[] amr = mapConfig.getProperty("availableMaxResolution").split(";");
                String[] abl = mapConfig.getProperty("availableBackgroundLayers").split(";");
                int i;
                for(i = 1; i < amr.length; i++) {
                    if(backgroundLayer.equals(abl[i])) {
                        mapConfig.updateProperty("maxResolution", amr[i]);
                        break;
                    }
                }
            } else {
                mapConfig.updateProperty("maxResolution", mapConfig.getMaxResolution() + "");
            }
			request.setAttribute("backgroundLayer", backgroundLayer);

            //Obtains the selection of the vector layers of the user.

			String[] selectedVectorLayers = UserRequestManager.manageVectorLayersOptions(request, session);
			int[] vectorLayers = opManager.obtainIndexForOptionalLayers(selectedVectorLayers);<commit_msg>the index for the maximum resolution of the wms layer was corrected<commit_after>/*
* Copyright (c) 2013 <NAME>
* Permission is hereby granted, free of charge, to any person obtaining a copy of 
* this software and associated documentation files (the "Software"), to deal in the 
* Software without restriction, including without limitation the rights to use, copy, 
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
* to permit persons to whom the Software is furnished to do so, subject to the following conditions: 
* The above copyright notice and this permission notice shall be included in all copies or substantial 
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
*/
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mapviewer.business.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

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

import com.mapviewer.business.LayerMenuManagerSingleton;
import com.mapviewer.business.NetCDFRequestManager;
import com.mapviewer.business.OpenLayersManager;
import com.mapviewer.business.UserRequestManager;
import com.mapviewer.conf.OpenLayerMapConfig;
import com.mapviewer.exceptions.XMLFilesException;
import com.mapviewer.exceptions.XMLLayerException;
import com.mapviewer.model.Layer;
import com.mapviewer.model.PagesNames;
import com.mapviewer.model.menu.MenuEntry;
import com.mapviewer.model.menu.TreeMenuUtils;
import com.mapviewer.model.menu.TreeNode;
import com.mapviewer.tools.HtmlMenuBuilder;
import java.io.FileNotFoundException;
import java.util.Arrays;

/**
 * Servelet to process all the request of the user and incharge of presenting the client
 * with the OpenLayers configuration
 *
 *
 * @author <NAME>
 */
public class MapViewerServlet extends HttpServlet {

	OpenLayersManager opManager;//OpenLayers Code
	OpenLayerMapConfig mapConfig;
	NetCDFRequestManager ncManager;// This object is used to manage the netcdf curr_main_layers
	String[] linksVectorialesKmz;
	String configFilePath;

	Boolean exceptionInitializingVariables = false;

	/**
	 * Initiliazes the varibles of the Servlet 
	 * @throws FileNotFoundException
	 * @throws XMLFilesException
	 * @throws XMLLayerException 
	 */
	private void initializeVariables() throws FileNotFoundException, XMLFilesException, XMLLayerException{
			mapConfig = OpenLayerMapConfig.getInstance();

			configFilePath = getServletContext().getRealPath("/WEB-INF/conf/MapViewConfig.properties");

			mapConfig.updateProperties(configFilePath);
            
			//Obtains the folder where XML layers file is stored.
			String layersFolder = getServletContext().getRealPath("/layers/");
			String baseLayerMenuOrientation = mapConfig.getProperty("baseLayerMenuOrientation");
			HtmlMenuBuilder.baseLayerMenuOrientation = baseLayerMenuOrientation;

			LayerMenuManagerSingleton.setLayersFolder(layersFolder);//Set the layers folder

			opManager = new OpenLayersManager();//initialize the OpenLayers
			ncManager = new NetCDFRequestManager();
            LayerMenuManagerSingleton.getInstance().refreshTree(true);//Initializes all the layers from the XML files
	}
	/**
	 * Initializes the object that controls the access to the server
	 *
	 */
	@Override
	public void init() throws ServletException {
		try {
			initializeVariables();
		} catch (XMLFilesException ex) {
			exceptionInitializingVariables = true;
			Logger.getLogger(MapViewerServlet.class.getName()).log(Level.SEVERE, null, ex);
		} catch (FileNotFoundException ex) {
			Logger.getLogger(MapViewerServlet.class.getName()).log(Level.SEVERE, null, ex);
		}
		
		super.init();
	}
	
	/**
	 * Processes requests for both HTTP
	 * <code>GET</code> and
	 * <code>POST</code> methods.
	 *
	 * @param {HttpServletRequest} request servlet request
	 * @param {HttpServletResponse} response servlet response
	 * @throws ServletException if a servlet-specific error occurs
	 * @throws IOException if an I/O error occurs
	 */
    @SuppressWarnings("UnusedAssignment")
	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String nextPage = PagesNames.ERROR_PAGE;//error page, this gets modified if everything is fine.
		mapConfig.updateProperties(configFilePath);
		//its important to erase the basePath becuase it get appended again.
		try {
			
			response.setContentType("text/html;charset=iso-8859-1");
			HttpSession session = request.getSession();//Se obtiene la sesion
			
			TreeNode arbolMenuRasters = null;
            //If there was a problem initializing the variables we try to do it again.
			// This code catches information about the exception and displays it for the user.
			try {
                
				if(exceptionInitializingVariables){
                    initializeVariables();
                }
				arbolMenuRasters = UserRequestManager.createNewRootMenu(request, session);
				exceptionInitializingVariables = false;
			} catch (XMLFilesException ex) {
                //If an exception happens, we start with the default menu
				arbolMenuRasters = UserRequestManager.createNewRootMenu(request, session);
				session.setAttribute("MenuDelUsuario", arbolMenuRasters);
				//If there is an XMLLayerException exception we just display it as
				// warning in the main site
                StringWriter sw = new StringWriter();
				ex.printStackTrace(new PrintWriter(sw));
				String exceptionInfo = ex.getMessage();
				String exceptionTrace = sw.toString();
				exceptionTrace = exceptionTrace.substring(0, exceptionTrace.indexOf("\n"));
				exceptionTrace = exceptionTrace.replace("\"","");
				exceptionTrace = exceptionTrace.replace("\'","");
				exceptionInfo = exceptionInfo.replace("\"","");
				exceptionInfo = exceptionInfo.replace("\'","");
				
				request.setAttribute("warningText", exceptionInfo);
				request.setAttribute("warningInfo", exceptionTrace);
				
				exceptionInitializingVariables = true;
			}
            
			if(linksVectorialesKmz  == null){
				linksVectorialesKmz = UserRequestManager.getCheckboxKmlLinks(opManager.getVectorLayers());
				HtmlMenuBuilder.vecLinks = linksVectorialesKmz;
			}
			
			//get menu entry
			MenuEntry[] rasterSelecteLayers = TreeMenuUtils.obtieneMenuSeleccionado(arbolMenuRasters);
            
			//obtain layer index
			int[] baseLayers = opManager.obtainArrayIndexOfLayers(rasterSelecteLayers);
            Layer curr_main_layer = null;
            //this variables are then read by the GlobalJavascript.jsp
            //The next variable is used to decide if the layer has
            // a custom CQL filter
            request.setAttribute("cqlfilter", false);
            if(baseLayers != null) {
                curr_main_layer = opManager.getRasterLayers().get(baseLayers[0]); //get main layer of user
                request.setAttribute("ncwms", curr_main_layer.isncWMS());
                request.setAttribute("currents", curr_main_layer.isoverlayStreamlines());
                request.setAttribute("layerDetails", curr_main_layer.getLayerDetails());
                request.setAttribute("zaxis", curr_main_layer.isZaxis());
                request.setAttribute("multipleDates", curr_main_layer.isMultipleDates());
                request.setAttribute("mainLayer", curr_main_layer.getName());
                request.setAttribute("style", curr_main_layer.getStyle());
                request.setAttribute("max_time_range", curr_main_layer.getMaxTimeLayer());
                request.setAttribute("cqlcols", curr_main_layer.getCql_cols());
                if (!curr_main_layer.getCql_cols().equals("")) {
                    request.setAttribute("cqlfilter", true);
                }
            } else {
                request.setAttribute("ncwms", false);
                request.setAttribute("currents", null);
                request.setAttribute("layerDetails", "{}");
                request.setAttribute("zaxis", null);
                request.setAttribute("multipleDates", "null");
                request.setAttribute("mainLayer", null);
                request.setAttribute("style", null);
                request.setAttribute("max_time_range", null);
                request.setAttribute("cqlcols", null);
            }
			
			//Obtains and set a lenguage.
			
			String defaultLang=mapConfig.getProperty("defaultLanguage");
			String availableLanguages=mapConfig.getProperty("availableLanguages");
			int imageResolution = Integer.parseInt(mapConfig.getProperty("imageResolution"));
            
            request.setAttribute("imageResolution", imageResolution);
            
			request.setAttribute("defaultLanguage", defaultLang);
			request.setAttribute("availableLanguages", availableLanguages);
            
            //Setting the locale gotten from the one seleted by the user on the website
			String language=request.getParameter("_locale");
			
			//setting Default locale from the properties file on first time page load
			if(language==null || "".equals(language)){
				language=defaultLang;
			}

            //get and set background layers
            
            String defaultBackgroundLayer = mapConfig.getProperty("backgroundLayer");
			String backgroundLayer = request.getParameter("backgroundLayer");
            backgroundLayer =  (backgroundLayer == null || "".equals(backgroundLayer)) ? defaultBackgroundLayer : backgroundLayer;
            //get the resolution for a selected background layer
            if(! backgroundLayer.equals(defaultBackgroundLayer)) {
                String[] amr = mapConfig.getProperty("availableMaxResolution").split(";");
                String[] abl = mapConfig.getProperty("availableBackgroundLayers").split(";");
                int i;
                for(i = 0; i < amr.length; i++) {
                    if(backgroundLayer.equals(abl[i])) {
                        mapConfig.updateProperty("maxResolution", amr[i]);
                        break;
                    }
                }
            } else {
                mapConfig.updateProperty("maxResolution", mapConfig.getMaxResolution() + "");
            }
			request.setAttribute("backgroundLayer", backgroundLayer);

            //Obtains the selection of the vector layers of the user.

			String[] selectedVectorLayers = UserRequestManager.manageVectorLayersOptions(request, session);
			int[] vectorLayers = opManager.obtainIndexForOptionalLayers(selectedVectorLayers);
{'fraction_non_alphanumeric': 0.09255119377626755, 'fraction_numerical': 0.001073057319145131, 'mean_word_length': 3.485960689931809, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 15, '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': '5904762', 'n_tokens_mistral': 6159, 'n_tokens_neox': 5664, 'n_words': 1536}