package com.cronos.admin.services;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.cronos.admin.panel.PanelForm;

public class ConfigurationService {
	public static final String K_fileConf = "ccadminconf.xml";
	public static final String K_fileConfCC = "cronoscontrol.xml";
	public static final String K_fileConfServer = "server.xml";

	@SuppressWarnings("finally")
	public static ConfigurationBean readXMLConfiguration(String absoluteDiskPath) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		ConfigurationBean result = new ConfigurationBean();
		String fileConfAdmin = absoluteDiskPath + File.separator + K_fileConf;

		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(fileConfAdmin);

			NodeList loginn = doc.getElementsByTagName("login");
			NodeList claven = doc.getElementsByTagName("clave");
			NodeList pathconfn = doc.getElementsByTagName("path");

			String login = loginn.item(0).getFirstChild().getTextContent();
			String clave = claven.item(0).getFirstChild().getTextContent();

			// admin = doc.getElementById("admin");
			// fileconf = doc.getElementById("fileconf");
			// String login = admin.getElementsByTagName("login").toString();
			// String clave = admin.getElementsByTagName("clave").toString();
			result.setLogin(login);
			result.setClave(clave);

			String pathconf = pathconfn.item(0).getFirstChild().getTextContent();

			File f = new File(pathconf);

			String tomcatHome = System.getProperty("catalina.base");
			result.setPathServerXML(tomcatHome + File.separator + "conf" + File.separator + K_fileConfServer);

			if (pathconf.isEmpty() || !f.exists()) {
				pathconf = tomcatHome + File.separator + "conf" + File.separator + "Catalina" + File.separator
						+ "localhost" + File.separator + K_fileConfCC;
				pathconfn.item(0).getFirstChild().setTextContent(pathconf);

				// write the content into xml file
				TransformerFactory transformerFactory = TransformerFactory.newInstance();
				Transformer transformer = transformerFactory.newTransformer();
				DOMSource source = new DOMSource(doc);
				StreamResult result1 = new StreamResult(new File(fileConfAdmin));

				// Output to console for testing
				// StreamResult result = new StreamResult(System.out);

				transformer.transform(source, result1);
			}

			result.setPath(pathconf);
		} catch (Exception e) {
		} finally {
			return result;
		}
	}

	@SuppressWarnings("finally")
	public static ConfigurationCCBean readXMLCCConfiguration(String fileCCConfiguration, String absoluteDiskPath) {
		File f = new File(fileCCConfiguration);
		if (!f.exists()) {
			CreateCCConfiguration(fileCCConfiguration, absoluteDiskPath);
		}

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		ConfigurationCCBean result = new ConfigurationCCBean();

		try {
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(fileCCConfiguration);

			NodeList context = doc.getElementsByTagName("Context");
			for (int j = 0; j < context.getLength(); ++j) {

				Node prop = context.item(j);

				// Atributos del context
				NamedNodeMap attr = prop.getAttributes();
				if (null != attr) {
					Node p = attr.getNamedItem("path");
					Node p1 = attr.getNamedItem("docBase");
					Node p2 = attr.getNamedItem("workDir");
					Node pR = attr.getNamedItem("reloadable");
					// Node p3 = attr.getNamedItem("maxActiveSessions");

					@SuppressWarnings("unused")
					String val = p.getNodeValue();
					/*
					 * System.out.println("path:  " + val); System.out.println( "docBase:  " +
					 * p1.getNodeValue()); System.out.println( "workDir:  " + p2.getNodeValue());
					 */

					result.setPath(p.getNodeValue());
					result.setDocBase(p1.getNodeValue());
					result.setWorkDir(p2.getNodeValue());
					// System.out.println("reloadable: " +
					// pR.getNodeValue().toString().toLowerCase());
					result.setReloadable((pR.getNodeValue().toString().toLowerCase().equals("true")));
				}

				NodeList nodes = prop.getChildNodes();
				for (int i = 0; i < nodes.getLength(); ++i) {
					Node resource = nodes.item(i);
					NamedNodeMap attrib = resource.getAttributes();
					if (resource.getNodeName().equals("Manager")) {
						Node p = attrib.getNamedItem("maxActiveSessions");
						result.setMaxActiveSessions(Integer.parseInt(p.getNodeValue()));
					} else if (resource.getNodeName().equals("Resource")) {

						Node p = attrib.getNamedItem("name");
						DatabaseEngineConnInfo cnn = new DatabaseEngineConnInfo();

						cnn.setName(p.getNodeValue());

						if (cnn.getName().equals("jdbc/cronosSqlServer")) {
							result.setDatabaseEngineConnInfoSQLServer(cnn);
						} else if (cnn.getName().equals("jdbc/cronosOracle")) {
							result.setDatabaseEngineConnInfoOracle(cnn);
						} else if (cnn.getName().equals("jdbc/cronosPostgreSQL")) {
							result.setDatabaseEngineConnInfoPostgres(cnn);
						}

						Node p1 = attrib.getNamedItem("username");
						cnn.setUsername(p1.getNodeValue());

						Node p2 = attrib.getNamedItem("password");
						cnn.setPassword(p2.getNodeValue());

						Node p3 = attrib.getNamedItem("url");

						analizeUrl(p3.getNodeValue(), cnn);

						Node p4 = attrib.getNamedItem("maxIdle");
						cnn.setMaxIdle(Integer.parseInt(p4.getNodeValue()));

						Node p5 = attrib.getNamedItem("maxActive");
						cnn.setMaxActive(Integer.parseInt(p5.getNodeValue()));

						Node p6 = attrib.getNamedItem("maxWait");
						cnn.setMaxWait(Integer.parseInt(p6.getNodeValue()));

						/*
						 * System.out.println("server  :  " + cnn.getServer());
						 * System.out.println("port    :  " + cnn.getServerPort()); System.out.println(
						 * "database:  " + cnn.getDbname()); System.out.println( "user    :  " +
						 * cnn.getUsername()); System.out.println("password:  " + cnn.getPassword());
						 */
					}
				}
			}

			// admin = doc.getElementById("admin");
			// fileconf = doc.getElementById("fileconf");
			// String login = admin.getElementsByTagName("login").toString();
			// String clave = admin.getElementsByTagName("clave").toString();

			// result.setLogin(login);
			// result.setClave(clave);

			// String pathconf =
			// pathconfn.item(0).getFirstChild().getTextContent();
			// result.setPath(pathconf);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return result;
		}
	}

	private static boolean CreateCCConfiguration(String fileCCConfiguration, String absoluteDiskPathOrig) {

		PrintWriter writer;
		try {
			String absoluteDiskPath = absoluteDiskPathOrig.replaceFirst("CCAdmin", "CC");
			absoluteDiskPath = absoluteDiskPath.replaceFirst("WEB-INF", "");

			String tomcatHome = System.getProperty("catalina.base");
			String workDir = tomcatHome + File.separator + "work" + File.separator + "Catalina" + File.separator
					+ "localhost" + File.separator + "CC";

			writer = new PrintWriter(fileCCConfiguration, "UTF-8");
			writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
			writer.println("<Context docBase=\"" + absoluteDiskPath
					+ "\" path=\"/cronoscontrol\" reloadable=\"false\" workDir=\"" + workDir + "\">");
			writer.println("<Manager maxActiveSessions=\"30\"/>");
			writer.println("");
			writer.println(
					"<Resource driverClassName=\"com.microsoft.sqlserver.jdbc.SQLServerDriver\" maxActive=\"4\" maxIdle=\"2\" maxWait=\"5000\" name=\"jdbc/cronosSqlServer\" password=\"masterkey\" scope=\"Shareable\" type=\"javax.sql.DataSource\" url=\"jdbc:sqlserver://localhost:1433;database=Cronos\" username=\"SYSDBA\"/>");
			writer.println("");
			writer.println(
					"<Resource driverClassName=\"oracle.jdbc.driver.OracleDriver\" maxActive=\"4\" maxIdle=\"2\" maxWait=\"5000\" name=\"jdbc/cronosOracle\" password=\"masterkey\" scope=\"Shareable\" type=\"javax.sql.DataSource\" url=\"jdbc:oracle:thin:@127.0.0.1:1521:XE\" username=\"SYSDBA\"/>");
			writer.println("");
			writer.println(
					"<Resource driverClassName=\"org.postgresql.Driver\" maxActive=\"4\" maxIdle=\"2\" maxWait=\"5000\" name=\"jdbc/cronosPostgreSQL\" password=\"masterkey\" scope=\"Shareable\" type=\"javax.sql.DataSource\" url=\"jdbc:postgresql://localhost:5432/cronos\" username=\"postgres\"/>");
			writer.println("");
			writer.println("</Context>");
			writer.close();
			return true;

		} catch (FileNotFoundException | UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	@SuppressWarnings({ "unused", "finally" })
	public static ConfigurationServerBean readXMLServerConfiguration(String fileServerConfiguration) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		ConfigurationServerBean result = new ConfigurationServerBean();

		try {
			DocumentBuilder db = dbf.newDocumentBuilder();

			Document doc = db.parse(fileServerConfiguration);

			NodeList nodesR = doc.getChildNodes();

			for (int i = 0; i < nodesR.getLength(); ++i) {
				Node propR = nodesR.item(i);

				if (propR.getNodeName().equals("Server")) {
					NodeList nodesS = propR.getChildNodes();
					// Atributos del context

					for (int n = 0; n < nodesS.getLength(); ++n) {
						Node propS = nodesS.item(n);
						if (propS.getNodeName().equals("Service")) {
							NodeList nodesSv = propS.getChildNodes();
							for (int j = 0; j < nodesSv.getLength(); ++j) {

								Node prop = nodesSv.item(j);
								NamedNodeMap attr = prop.getAttributes();

								if (prop.getNodeName().equals("Connector")) {

									if (null != attr && result.getNavProtocol() == null) {

										Node p = attr.getNamedItem("port");

										Node p1 = attr.getNamedItem("protocol");
										Node p2 = attr.getNamedItem("enableLookups");
										Node p3 = attr.getNamedItem("acceptCount");
										Node p4 = attr.getNamedItem("maxThreads");
										Node p5 = attr.getNamedItem("maxHttpHeaderSize");
										Node p6 = attr.getNamedItem("connectionTimeout");

										String val = p.getNodeValue();
										/*
										 * System.out.println("port:  " + val); System.out.println("protocol:  " +
										 * p1.getNodeValue()); System.out.println("enableLookups:  " +
										 * p2.getNodeValue()); System.out.println("acceptCount:" + p3.getNodeValue());
										 * System.out.println("maxThreads :" + p4.getNodeValue()); System.out.println (
										 * "maxHttpHeaderSize :" + p5.getNodeValue()); System.out.println (
										 * "connectionTimeout :" + p6.getNodeValue());
										 */
										// result.setPath(p.getNodeValue());
										// result.setDocBase(p1.getNodeValue());
										// result.setWorkDir(p2.getNodeValue());
										// result.setMaxActiveSessions(Integer.parseInt(p3.getNodeValue()));

										String ssl = (attr.getNamedItem("SSLEnabled") == null ? "false"
												: attr.getNamedItem("SSLEnabled").getNodeValue());
										if (ssl.equals("false")) {
											result.setNavProtocol(NavProtocol.HTTP);
										} else {
											result.setNavProtocol(NavProtocol.HTTPS);
											Node pSSL1 = attr.getNamedItem("keystoreFile");
											Node pSSL2 = attr.getNamedItem("keystorePass");
											result.setKeyStoreFile(pSSL1.getNodeValue());
											result.setKeyStorePass(pSSL2.getNodeValue());
										}
										if (p3 != null)
											result.setAcceptCount(Integer.parseInt(p3.getNodeValue()));
										else
											result.setAcceptCount(100); // Default

										if (p4 != null)
											result.setMaxThreads(Integer.parseInt(p4.getNodeValue()));
										else
											result.setMaxThreads(200); // Default

										if (p5 != null)
											result.setMaxHttpHeaderSize(Integer.parseInt(p5.getNodeValue()));
										else
											result.setMaxHttpHeaderSize(8192); // Default

										if (p2 != null)
											result.setEnableLookups((p2.getNodeValue().equals("true")));
										else
											result.setEnableLookups(false); // Default

										if (p6 != null)
											result.setConnectionTimeout(Integer.parseInt(p6.getNodeValue()));
										else
											result.setConnectionTimeout(60000); // Default

										if (p != null)
											result.setPort(Integer.parseInt(p.getNodeValue()));
										else
											result.setPort(8080);

									}
								} else if (prop.getNodeName().equals("Engine")) {
									NodeList nodesE = prop.getChildNodes();
									for (int e = 0; e < nodesE.getLength(); ++e) {

										Node propE = nodesE.item(e);
										NamedNodeMap attrE = propE.getAttributes();
										if (propE.getNodeName().equals("Host")) {
											if (null != attrE) {
												Node p = attrE.getNamedItem("deployOnStartup");
												if (p != null)
													result.setDeployOnStartup(p.getNodeValue().equals("true"));

											}
										}
									}
								}
								// ---------------------------
							}
						}
					}
				}

			}

			// admin = doc.getElementById("admin");
			// fileconf = doc.getElementById("fileconf");
			// String login = admin.getElementsByTagName("login").toString();
			// String clave = admin.getElementsByTagName("clave").toString();

			// result.setLogin(login);
			// result.setClave(clave);

			// String pathconf =
			// pathconfn.item(0).getFirstChild().getTextContent();
			// result.setPath(pathconf);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			return result;
		}
	}

	public static void SaveCCConfiguration(ConfigurationCCBean ccConf, String fileCCConfiguration) {
		boolean sqlOk = false, oraOk = false, pgOk = false;

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {
			DocumentBuilder db = dbf.newDocumentBuilder();

			Document doc = db.parse(fileCCConfiguration);

			NodeList context = doc.getElementsByTagName("Context");
			for (int j = 0; j < context.getLength(); ++j) {
				Node prop = context.item(j);

				// Atributos del context
				NamedNodeMap attr = prop.getAttributes();
				if (null != attr) {
					Node p = attr.getNamedItem("path");
					Node p1 = attr.getNamedItem("docBase");
					Node p2 = attr.getNamedItem("workDir");
					Node pR = attr.getNamedItem("reloadable");

					p.setNodeValue(ccConf.getPath());
					p1.setNodeValue(ccConf.getDocBase());
					p2.setNodeValue(ccConf.getWorkDir());
					pR.setNodeValue(ccConf.isReloadable() ? "true" : "false");
				}

				NodeList nodes = prop.getChildNodes();
				for (int i = 0; i < nodes.getLength(); ++i) {
					Node resource = nodes.item(i);
					NamedNodeMap attrib = resource.getAttributes();
					if (resource.getNodeName().equals("Manager")) {
						Node p = attrib.getNamedItem("maxActiveSessions");
						p.setNodeValue(String.valueOf(ccConf.getMaxActiveSessions()));

					} else if (resource.getNodeName().equals("Resource")) {
						Node p = attrib.getNamedItem("name");
						DatabaseEngineConnInfo cnn = new DatabaseEngineConnInfo();
						// System.out.println("name: " + p.getNodeValue());
						cnn.setName(p.getNodeValue());

						Node pc1 = attrib.getNamedItem("username");
						Node pc2 = attrib.getNamedItem("password");
						Node pc3 = attrib.getNamedItem("url");
						Node pc4 = attrib.getNamedItem("maxActive");
						Node pc5 = attrib.getNamedItem("maxIdle");
						Node pc6 = attrib.getNamedItem("maxWait");

						if (cnn.getName().equals("jdbc/cronosSqlServer")) {
							pc1.setNodeValue(ccConf.getDatabaseEngineConnInfoSQLServer().getUsername());

							pc2.setNodeValue(ccConf.getDatabaseEngineConnInfoSQLServer().getPassword());

							pc3.setNodeValue(
									"jdbc:sqlserver://" + ccConf.getDatabaseEngineConnInfoSQLServer().getServer() + ":"
											+ ccConf.getDatabaseEngineConnInfoSQLServer().getServerPort() + ";database="
											+ ccConf.getDatabaseEngineConnInfoSQLServer().getDbname());
							pc4.setNodeValue(
									String.valueOf(ccConf.getDatabaseEngineConnInfoSQLServer().getMaxActive()));

							pc5.setNodeValue(String.valueOf(ccConf.getDatabaseEngineConnInfoSQLServer().getMaxIdle()));

							pc6.setNodeValue(String.valueOf(ccConf.getDatabaseEngineConnInfoSQLServer().getMaxWait()));

							sqlOk = true;

						} else if (cnn.getName().equals("jdbc/cronosOracle")) {
							pc1.setNodeValue(ccConf.getDatabaseEngineConnInfoOracle().getUsername());

							pc2.setNodeValue(ccConf.getDatabaseEngineConnInfoOracle().getPassword());

							pc3.setNodeValue("jdbc:oracle:thin:@" + ccConf.getDatabaseEngineConnInfoOracle().getServer()
									+ ":" + ccConf.getDatabaseEngineConnInfoOracle().getServerPort() + ":"
									+ ccConf.getDatabaseEngineConnInfoOracle().getDbname());
							pc4.setNodeValue(String.valueOf(ccConf.getDatabaseEngineConnInfoOracle().getMaxActive()));

							pc5.setNodeValue(String.valueOf(ccConf.getDatabaseEngineConnInfoOracle().getMaxIdle()));

							pc6.setNodeValue(String.valueOf(ccConf.getDatabaseEngineConnInfoOracle().getMaxWait()));
							oraOk = true;

						} else if (cnn.getName().equals("jdbc/cronosPostgreSQL")) {
							pc1.setNodeValue(ccConf.getDatabaseEngineConnInfoPostgres().getUsername());

							pc2.setNodeValue(ccConf.getDatabaseEngineConnInfoPostgres().getPassword());

							pc3.setNodeValue(
									"jdbc:postgresql://" + ccConf.getDatabaseEngineConnInfoPostgres().getServer() + ":"
											+ ccConf.getDatabaseEngineConnInfoPostgres().getServerPort() + "/"
											+ ccConf.getDatabaseEngineConnInfoPostgres().getDbname());
							pc4.setNodeValue(String.valueOf(ccConf.getDatabaseEngineConnInfoPostgres().getMaxActive()));

							pc5.setNodeValue(String.valueOf(ccConf.getDatabaseEngineConnInfoPostgres().getMaxIdle()));

							pc6.setNodeValue(String.valueOf(ccConf.getDatabaseEngineConnInfoPostgres().getMaxWait()));
							pgOk = true;
						}

					}

				}
				// Si falta algun tag lo agregamos
				if (!sqlOk) // Si falta el tag de SQL
				{
					Element newChild = doc.createElement("Resource");

					newChild.setAttribute("driverClassName", "com.microsoft.sqlserver.jdbc.SQLServerDriver");
					newChild.setAttribute("maxActive",
							String.valueOf(ccConf.getDatabaseEngineConnInfoSQLServer().getMaxActive()));
					newChild.setAttribute("maxIdle",
							String.valueOf(ccConf.getDatabaseEngineConnInfoSQLServer().getMaxIdle()));
					newChild.setAttribute("maxWait",
							String.valueOf(ccConf.getDatabaseEngineConnInfoSQLServer().getMaxWait()));
					newChild.setAttribute("scope", "Shareable");
					newChild.setAttribute("type", "javax.sql.DataSource");

					newChild.setAttribute("name", "jdbc/cronosSqlServer");
					newChild.setAttribute("username", ccConf.getDatabaseEngineConnInfoSQLServer().getUsername());
					newChild.setAttribute("password", ccConf.getDatabaseEngineConnInfoSQLServer().getPassword());
					newChild.setAttribute("url",
							"jdbc:sqlserver://" + ccConf.getDatabaseEngineConnInfoSQLServer().getServer() + ":"
									+ ccConf.getDatabaseEngineConnInfoSQLServer().getServerPort() + ";database="
									+ ccConf.getDatabaseEngineConnInfoSQLServer().getDbname());
					prop.appendChild(newChild);
				}
				if (!oraOk) // Si falta el tag de Oracle
				{

					Element newChild = doc.createElement("Resource");

					newChild.setAttribute("driverClassName", "oracle.jdbc.driver.OracleDriver");
					newChild.setAttribute("maxActive",
							String.valueOf(ccConf.getDatabaseEngineConnInfoOracle().getMaxActive()));
					newChild.setAttribute("maxIdle",
							String.valueOf(ccConf.getDatabaseEngineConnInfoOracle().getMaxIdle()));
					newChild.setAttribute("maxWait",
							String.valueOf(ccConf.getDatabaseEngineConnInfoOracle().getMaxWait()));
					newChild.setAttribute("scope", "Shareable");
					newChild.setAttribute("type", "javax.sql.DataSource");

					newChild.setAttribute("name", "jdbc/cronosOracle");
					newChild.setAttribute("username", ccConf.getDatabaseEngineConnInfoOracle().getUsername());
					newChild.setAttribute("password", ccConf.getDatabaseEngineConnInfoOracle().getPassword());
					newChild.setAttribute("url",
							"jdbc:oracle:thin:@" + ccConf.getDatabaseEngineConnInfoOracle().getServer() + ":"
									+ ccConf.getDatabaseEngineConnInfoOracle().getServerPort() + ":"
									+ ccConf.getDatabaseEngineConnInfoOracle().getDbname());
					prop.appendChild(newChild);
				}
				if (!pgOk) // Si falta el tag de Postgres
				{
					Element newChild = doc.createElement("Resource");

					newChild.setAttribute("driverClassName", "org.postgresql.Driver");
					newChild.setAttribute("maxActive",
							String.valueOf(ccConf.getDatabaseEngineConnInfoPostgres().getMaxActive()));
					newChild.setAttribute("maxIdle",
							String.valueOf(ccConf.getDatabaseEngineConnInfoPostgres().getMaxIdle()));
					newChild.setAttribute("maxWait",
							String.valueOf(ccConf.getDatabaseEngineConnInfoPostgres().getMaxWait()));
					newChild.setAttribute("scope", "Shareable");
					newChild.setAttribute("type", "javax.sql.DataSource");

					newChild.setAttribute("name", "jdbc/cronosPostgreSQL");
					newChild.setAttribute("username", ccConf.getDatabaseEngineConnInfoPostgres().getUsername());
					newChild.setAttribute("password", ccConf.getDatabaseEngineConnInfoPostgres().getPassword());
					newChild.setAttribute("url",
							"jdbc:postgresql://" + ccConf.getDatabaseEngineConnInfoPostgres().getServer() + ":"
									+ ccConf.getDatabaseEngineConnInfoPostgres().getServerPort() + "/"
									+ ccConf.getDatabaseEngineConnInfoPostgres().getDbname());
					prop.appendChild(newChild);
				}
			}

			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result1 = new StreamResult(new File(fileCCConfiguration));

			// Output to console for testing
			// StreamResult result = new StreamResult(System.out);

			transformer.transform(source, result1);

		} catch (Exception e) {
			System.out.println(e.getLocalizedMessage());

		}
	}

	public static void SaveServerConfiguration(ConfigurationServerBean csConf, String fileCSConfiguration) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		try {
			DocumentBuilder db = dbf.newDocumentBuilder();

			Document doc = db.parse(fileCSConfiguration);

			boolean connectorUpdated = false;

			NodeList nodesR = doc.getChildNodes();

			for (int i = 0; i < nodesR.getLength(); ++i) {
				Node propR = nodesR.item(i);

				if (propR.getNodeName().equals("Server")) {
					NodeList nodesS = propR.getChildNodes();
					// Atributos del context

					for (int n = 0; n < nodesS.getLength(); ++n) {
						Node propS = nodesS.item(n);
						if (propS.getNodeName().equals("Service")) {
							NodeList nodesSv = propS.getChildNodes();
							for (int j = 0; j < nodesSv.getLength(); ++j) {

								Node prop = nodesSv.item(j);
								NamedNodeMap attr = prop.getAttributes();

								if (prop.getNodeName().equals("Connector")) {
									if (null != attr && !connectorUpdated) {

										Node p = attr.getNamedItem("port");
										@SuppressWarnings("unused")
										Node p1 = attr.getNamedItem("protocol");
										@SuppressWarnings("unused")
										Node p2 = attr.getNamedItem("enableLookups");
										@SuppressWarnings("unused")
										Node p3 = attr.getNamedItem("acceptCount");
										@SuppressWarnings("unused")
										Node p4 = attr.getNamedItem("maxThreads");
										@SuppressWarnings("unused")
										Node p5 = attr.getNamedItem("maxHttpHeaderSize");
										@SuppressWarnings("unused")
										Node p6 = attr.getNamedItem("connectionTimeout");

										@SuppressWarnings("unused")
										Node p7 = attr.getNamedItem("SSLEnabled");
										@SuppressWarnings("unused")
										Node p8 = attr.getNamedItem("scheme");
										@SuppressWarnings("unused")
										Node p9 = attr.getNamedItem("secure");

										@SuppressWarnings("unused")
										String val = p.getNodeValue();

										/*
										 * System.out.println("port:  " + val); System.out.println("protocol:  " +
										 * p1.getNodeValue()); System.out.println("enableLookups:  " +
										 * p2.getNodeValue()); System.out.println("acceptCount:" + p3.getNodeValue());
										 * System.out.println("maxThreads :" + p4.getNodeValue()); System.out.println (
										 * "maxHttpHeaderSize :" + p5.getNodeValue()); System.out.println (
										 * "connectionTimeout :" + p6.getNodeValue());
										 */
										// result.setPath(p.getNodeValue());
										// result.setDocBase(p1.getNodeValue());
										// result.setWorkDir(p2.getNodeValue());
										// result.setMaxActiveSessions(Integer.parseInt(p3.getNodeValue()));

										if (csConf.getNavProtocol().equals(NavProtocol.HTTP)) {

											p.setNodeValue(String.valueOf(csConf.getPort()));
											// p.setNodeValue("8080");

											setAttribute(prop, "SSLEnabled", "false");
											setAttribute(prop, "scheme", "http");
											setAttribute(prop, "secure", "false");
										} else if (csConf.getNavProtocol().equals(NavProtocol.HTTPS)) {
											p.setNodeValue(String.valueOf(csConf.getPort()));
											// p.setNodeValue("8443");
											setAttribute(prop, "SSLEnabled", "true");
											setAttribute(prop, "scheme", "https");
											setAttribute(prop, "secure", "true");

											setAttribute(prop, "keystoreFile", csConf.getKeystoreFile());
											setAttribute(prop, "keystorePass", csConf.getKeystorePass());

										}
										setAttribute(prop, "enableLookups",
												csConf.getEnableLookups() ? "true" : "false");
										// p2.setNodeValue(csConf
										// .getEnableLookups() ? "true"
										// : "false");

										setAttribute(prop, "acceptCount", String.valueOf(csConf.getAcceptCount()));
										// p3.setNodeValue(String.valueOf(csConf
										// .getAcceptCount()));

										setAttribute(prop, "maxThreads", String.valueOf(csConf.getMaxThreads()));
										// p4.setNodeValue(String.valueOf(csConf
										// .getMaxThreads()));

										setAttribute(prop, "maxHttpHeaderSize",
												String.valueOf(csConf.getMaxHttpHeaderSize()));
										// p5.setNodeValue(String.valueOf(csConf
										// .getMaxHttpHeaderSize()));

										setAttribute(prop, "connectionTimeout",
												String.valueOf(csConf.getConnectionTimeout()));
										// p6.setNodeValue(String.valueOf(csConf
										// .getConnectionTimeout()));

										setAttribute(prop, "relaxedQueryChars", csConf.getRelaxedQueryChars());

										connectorUpdated = true;
									}

								} else if (prop.getNodeName().equals("Engine")) {
									NodeList nodesE = prop.getChildNodes();
									for (int e = 0; e < nodesE.getLength(); ++e) {

										Node propE = nodesE.item(e);
										NamedNodeMap attrE = propE.getAttributes();
										if (propE.getNodeName().equals("Host")) {
											if (null != attrE) {
												@SuppressWarnings("unused")
												Node p = attrE.getNamedItem("deployOnStartup");
												setAttribute(propE, "deployOnStartup",
														(csConf.getDeployOnStartup() ? "true" : "false"));
												// p.setNodeValue((csConf
												// .getDeployOnStartup() ?
												// "true"
												// : "false"));

											}
										}
									}
								}
								// ---------------------------
							}
						}
					}
				}

			}

			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StreamResult result1 = new StreamResult(new File(fileCSConfiguration));

			// Output to console for testing

			transformer.transform(source, result1);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void PanelFormToConfigurationCCBean(PanelForm pf, ConfigurationCCBean cc) {
		cc.setDocBase(pf.getdocBase());
		cc.setWorkDir(pf.getWorkDir());
		cc.setPath(pf.getPath());
		cc.setMaxActiveSessions(pf.getMaxActiveSessions());
		cc.setReloadable(pf.isReloadable());

		DatabaseEngineConnInfo sscnn = new DatabaseEngineConnInfo();
		sscnn.setName("jdbc/cronosSqlServer");
		sscnn.setDbname(pf.getSsDbname());
		sscnn.setUsername(pf.getSsUser());
		sscnn.setPassword(pf.getSsPassword());
		sscnn.setServerPort(pf.getSsServerPort());
		sscnn.setServer(pf.getSsServer());

		sscnn.setMaxActive(pf.getSsMaxActive());
		sscnn.setMaxIdle(pf.getSsMaxIdle());
		sscnn.setMaxWait(pf.getSsMaxWait());

		cc.setDatabaseEngineConnInfoSQLServer(sscnn);

		DatabaseEngineConnInfo pgcnn = new DatabaseEngineConnInfo();
		pgcnn.setName("jdbc/cronosPostgreSQL");
		pgcnn.setDbname(pf.getPgDbname());
		pgcnn.setUsername(pf.getPgUser());
		pgcnn.setPassword(pf.getPgPassword());
		pgcnn.setServerPort(pf.getPgServerPort());
		pgcnn.setServer(pf.getPgServer());
		pgcnn.setMaxActive(pf.getPgMaxActive());
		pgcnn.setMaxIdle(pf.getPgMaxIdle());
		pgcnn.setMaxWait(pf.getPgMaxWait());

		cc.setDatabaseEngineConnInfoPostgres(pgcnn);

		DatabaseEngineConnInfo orcnn = new DatabaseEngineConnInfo();
		orcnn.setName("jdbc/cronosOracle");
		orcnn.setDbname(pf.getOrDbname());
		orcnn.setUsername(pf.getOrUser());
		orcnn.setPassword(pf.getOrPassword());
		orcnn.setServerPort(pf.getOrServerPort());
		orcnn.setServer(pf.getOrServer());
		orcnn.setMaxActive(pf.getOrMaxActive());
		orcnn.setMaxIdle(pf.getOrMaxIdle());
		orcnn.setMaxWait(pf.getOrMaxWait());

		cc.setDatabaseEngineConnInfoOracle(orcnn);
	}

	public static void PanelFormToConfigurationServerBean(PanelForm pf, ConfigurationServerBean cs) {
		cs.setAcceptCount(pf.getAcceptCount());
		cs.setConnectionTimeout(pf.getConnectionTimeout());
		cs.setDeployOnStartup(pf.getDeployOnStartup());
		cs.setEnableLookups(pf.getEnableLookups());
		cs.setMaxHttpHeaderSize(pf.getMaxHttpHeaderSize());
		cs.setMaxThreads(pf.getMaxThreads());
		cs.setPort(pf.getPort());

		if (!pf.getSslEnabled()) {
			cs.setNavProtocol(NavProtocol.HTTP);
			cs.setKeyStoreFile("");
			cs.setKeyStorePass("");
		} else {
			cs.setNavProtocol(NavProtocol.HTTPS);
			cs.setKeyStoreFile(pf.getKeystoreFile());
			cs.setKeyStorePass(pf.getKeystorePass());
		}
		cs.setLinuxRootPassword(pf.getLinuxRootPassword());
		cs.setSocketBuffer(pf.getSocketBuffer());

	}

	public static void ConfigurationCCBeanToPanelForm(ConfigurationCCBean cc, PanelForm pf) {
		pf.setDocBase(cc.getDocBase());
		pf.setWorkDir(cc.getWorkDir());
		pf.setPath(cc.getPath());
		pf.setMaxActiveSessions(cc.getMaxActiveSessions());
		pf.setReloadable(cc.isReloadable());

		if (cc.getDatabaseEngineConnInfoSQLServer() != null) {
			DatabaseEngineConnInfo cnn = cc.getDatabaseEngineConnInfoSQLServer();
			pf.setSsDbname(cnn.getDbname());
			pf.setSsPassword(cnn.getPassword());
			pf.setSsUser(cnn.getUsername());
			pf.setSsServer(cnn.getServer());
			pf.setSsServerPort(cnn.getServerPort());
			pf.setSsMaxActive(cnn.getMaxActive());
			pf.setSsMaxIdle(cnn.getMaxIdle());
			pf.setSsMaxWait(cnn.getMaxWait());
		}

		if (cc.getDatabaseEngineConnInfoPostgres() != null) {
			DatabaseEngineConnInfo cnn = cc.getDatabaseEngineConnInfoPostgres();
			pf.setPgDbname(cnn.getDbname());
			pf.setPgPassword(cnn.getPassword());
			pf.setPgUser(cnn.getUsername());
			pf.setPgServer(cnn.getServer());
			pf.setPgServerPort(cnn.getServerPort());

			pf.setPgMaxActive(cnn.getMaxActive());
			pf.setPgMaxIdle(cnn.getMaxIdle());
			pf.setPgMaxWait(cnn.getMaxWait());
		}

		if (cc.getDatabaseEngineConnInfoOracle() != null) {
			DatabaseEngineConnInfo cnn = cc.getDatabaseEngineConnInfoOracle();
			pf.setOrDbname(cnn.getDbname());
			pf.setOrPassword(cnn.getPassword());
			pf.setOrUser(cnn.getUsername());
			pf.setOrServer(cnn.getServer());
			pf.setOrServerPort(cnn.getServerPort());
			pf.setOrMaxActive(cnn.getMaxActive());
			pf.setOrMaxIdle(cnn.getMaxIdle());
			pf.setOrMaxWait(cnn.getMaxWait());
		}
	}

	private static void analizeUrl(String url, DatabaseEngineConnInfo cnn) {
		String[] parts;
		String[] subparts;
		String[] dbparts;
		switch (cnn.getName()) {
		case "jdbc/cronosSqlServer":
			url = url.replace("jdbc:sqlserver://", "");
			parts = url.split(";");
			cnn.setServer(parts[0]);
			subparts = parts[0].split(":");
			cnn.setServer(subparts[0]);
			cnn.setServerPort(subparts[1]);

			dbparts = parts[1].split("=");
			cnn.setDbname(dbparts[1]);

			break;
		case "jdbc/cronosPostgreSQL":
			url = url.replace("jdbc:postgresql://", "");
			parts = url.split("/");

			subparts = parts[0].split(":");
			cnn.setServer(subparts[0]);
			cnn.setServerPort(subparts[1]);

			cnn.setDbname(parts[1]);
			break;
		case "jdbc/cronosOracle":
			url = url.replace("jdbc:oracle:thin:@", "");
			parts = url.split(":");
			cnn.setServer(parts[0]);

			cnn.setServerPort(parts[1]);

			cnn.setDbname(parts[2]);
			break;
		}
	}

	public static void ConfigurationServerBeanToPanelForm(ConfigurationServerBean cs, PanelForm pf) {
		pf.setEnableLookups(cs.getEnableLookups());
		pf.setAcceptCount(cs.getAcceptCount());
		pf.setConnectionTimeout(cs.getConnectionTimeout());
		pf.setDeployOnStartup(cs.getDeployOnStartup());
		pf.setMaxHttpHeaderSize(cs.getMaxHttpHeaderSize());
		pf.setMaxThreads(cs.getMaxThreads());

		if (cs.getNavProtocol() != null)
			pf.setSslEnabled(cs.getNavProtocol().equals(NavProtocol.HTTPS));
		else
			pf.setSslEnabled(false);

		pf.setKeystoreFile(cs.getKeystoreFile());
		pf.setKeystorePass(cs.getKeystorePass());
		pf.setPort(cs.getPort());
	}

	public static void setAttribute(Node node, String attName, String val) {
		NamedNodeMap attributes = node.getAttributes();
		Node attNode = node.getOwnerDocument().createAttribute(attName);
		attNode.setNodeValue(val);
		attributes.setNamedItem(attNode);
	}
}
