<?xml version = '1.0' encoding = 'utf-8'?>
<%@ page contentType="text/html;charset=windows-1252"%>
<%@ page import="java.util.Enumeration" %>
<%@ page import="java.net.URL" %>
<%@ page import="org.w3c.dom.*" %>
<%@ page import="java.io.*" %>
<%@ page import="javax.xml.parsers.DocumentBuilder" %>
<%@ page import="javax.xml.parsers.DocumentBuilderFactory" %>
<%@ page import="javax.xml.parsers.ParserConfigurationException" %>

<%! private static String RELATIVE_PATH = "../"; %>
<%
//  String hrefz = "\"/client/sicraweb.jsp?";
//  Enumeration enum = request.getParameterNames();
//  while(enum.hasMoreElements())
//  {
//    String name = (String)enum.nextElement();
//    href += name+"="+request.getParameter(name);
//    if (enum.hasMoreElements()) href += "&";
//  }
//  href+="\"";
  
  // VERIFICA DEI PARAMETRI
  // in questa parte faccio la verifica dei parametri e nel caso cartauz tiro un cartauz
  String appType=request.getParameter("appServerType");
  String port=request.getParameter("port");
  String j2eeUser=request.getParameter("j2eeUser");
  String j2eePassword=request.getParameter("j2eePassword");
  String user=request.getParameter("user");
  String password=request.getParameter("password");
  String specJnlp = null;
  String serverType = null;
  String rmiPort = null;
  
  if (appType == null) appType = "jboss";
  if (port == null) port = String.valueOf(request.getServerPort());
  if (j2eeUser == null) 
  {
    String db = request.getParameter("db");
    if (db != null)
    {
      String[] tt = db.split(":");
      if (tt.length > 0) j2eeUser = tt[0];
      if (tt.length > 1) rmiPort  = tt[1];
    }
  }

  String appUrl = appType+":"+request.getServerName();
  if (port != null) appUrl += ":"+port;
  if (rmiPort != null) appUrl += ":"+rmiPort;
  
  String args = request.getParameter("args");
  
  String title = "Sicr@Web inside a web browser";
  String menuParam = "false";
  
  // JNLP 
  String jnlpFileName = request.getParameter("jnlp");
  if (jnlpFileName != null)
  {
    System.out.println("jnlp="+jnlpFileName);
    if (!jnlpFileName.toLowerCase().endsWith(".jnlp")) jnlpFileName += ".jnlp"; 
    
    String filename = config.getServletContext().getRealPath(jnlpFileName);
    File jnlpFile = new File(filename);
    if (!jnlpFile.exists()) response.sendError(500, "Il file '"+jnlpFileName+"' non � stato trovato!");
    
    System.out.println("jnlp file path="+filename);
    String[] result = caricaParametriConnessioneDaJNLP(new FileInputStream(jnlpFile));
    args = result[0];
    if (result[1] != null) title = result[1];
    
    menuParam = caricaNuovoMenuDaJNLP(new FileInputStream(jnlpFile));
  }  
   
  if (args != null)
  {
    String[] aa = args.split(";");
    if (aa.length > 5)
    {
      response.sendError(500, "Numero di argomenti nel JNLP non supportato: "+aa.length+". La vecchia sintassi non � supportata, convertire il JNLP alla nuova sintassi [max 5 parametri].");
    }
    
    appUrl = aa[0];
    j2eeUser = aa[1];
    j2eePassword = aa[2];
    if (aa.length>3) user = aa[3];
    if (aa.length>4) password = aa[4];
  
    String[] token = appUrl.split(":");
    appType = token[0];
    //port = token[2];
    port = token[2];
  }
         
  if (appType==null || appType.equalsIgnoreCase("jboss"))
  {
    serverType="jboss";
    specJnlp="jboss-client.jnlp";
  }
  else if ("OC4J".equalsIgnoreCase(appType))
  {
    serverType="oc4j";
    specJnlp="orion-client.jnlp";
  }
  else response.sendError(500,"il parametro appServerType deve valere \"JBOSS\" o \"OC4J\" (default = JBOSS)");
  
  if (j2eeUser == null) response.sendError(500,"il parametro j2eeUser deve essere valorizzato");
  
  // se non scrivo la password la imposto allo user
  if (j2eePassword == null) j2eePassword = j2eeUser;

  // dalle ultime versioni per ovviare al bug jnlp della 1.6
  // il setup cambai il nome al sicraweb-resources
  // questo algoritmo trova il nome giusto
  URL url=null;
  InputStream is = null;
  int i=0;
  String resourcePath=null;
  String res = null;
  //while(url==null)
  while(is == null)
  {
    res = "/sicraweb-resources"+(i==0 ? "" : "-ver"+i)+".jnlp";
    url = config.getServletContext().getResource(res);
    is = config.getServletContext().getResourceAsStream(res);
    i++;
    //if (url != null)
//    if (is != null)
//    {
//      System.out.println("resourcePath="+resourcePath);
//      resourcePath = resourcePath.substring(resourcePath.indexOf("/localhost/client"));
//    }
  }
  System.out.println("real path="+config.getServletContext().getRealPath(res));
//  System.out.println("url="+url);
//  System.out.println("url path="+url.getPath());
//  System.out.println("url file="+url.getFile());
//  System.out.println("url host="+url.getHost());

  System.out.println("filename="+res);
  
  // Calcolo il classpath estraendolo dai file JNLP
  String archive = RELATIVE_PATH+"signed-jars/it.saga.pubblici.menu.client.jar";
  String sicrawebResources = caricaJarDaJNLP(is);
  String jbossClient = caricaJarDaJNLP(new FileInputStream(config.getServletContext().getRealPath(specJnlp)));
  String actalisSiaCapi = caricaJarDaJNLP(new FileInputStream(config.getServletContext().getRealPath("actalis-siacapi.jnlp")));
  
  archive = archive+","+jbossClient+","+sicrawebResources+","+actalisSiaCapi;
  
 
  %>

<HTML>
  <HEAD>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=windows-1252"/>
    <TITLE>Saga S.p.A.  -  SicraWeb  -  <%=title%></TITLE>
    <script language="javascript">
      function init() {        
        window.onbeforeunload = confirmUnload;
        window.onunload = onUnload;
      }
      
      function confirmUnload() {
        if (document.sicraweb != null && !document.sicraweb.hasBeenClosed()) return "LA CHIUSURA DELLA PAGINA COMPORTA LA CHIUSURA DELL'APPLICAZIONE.";
      }
      
      function onUnload() {
        if (document.sicraweb != null & !document.sicraweb.hasBeenClosed()) document.sicraweb.close();
      }
      
    </script>
  </HEAD>
  <BODY onload="init();">
    <!--h2><%=title%></h2-->
    <applet width="1024" height="670" name="sicraweb" archive="<%=archive%>" code="it.saga.pubblici.menu.MnuMainApplet">
      <param name="argomenti" value="<%=appUrl%>;<%=j2eeUser%>;<%=j2eePassword%>"/>
      <param name="menuMaggioli" value="<%=menuParam%>"/>
      Your browser does not support the applet tag.
    </applet>
  </BODY>
</HTML>

<%! 
  private Document loadXmlDocument(InputStream input) throws Exception
  {
    // Step 1: create a DocumentBuilderFactory and configure it
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    //factory.setValidating(validate);
    
    // Step 2: create a DocumentBuilder that satisfies the constraints
    DocumentBuilder builder = factory.newDocumentBuilder();
    //log.debug("builder validate="+builder.isValidating());
   
//      // imposto l'entity resolver
//      if (entityResolver != null)
//      {
//        //if (log.isDebugEnabled()) log.debug("setting entity resolver: "+entityResolver);
//        builder.setEntityResolver(entityResolver);
//      }
      
    // Step 3: parse the input file
    Document doc = builder.parse( input );  
    return doc;
  }
  
  /**
   * Estrai i parametri da connessione dal JNLP 
   */
  private String[] caricaParametriConnessioneDaJNLP(InputStream jnlpInputStream) throws Exception
  {
    Document doc = loadXmlDocument(jnlpInputStream);
    Element jnlp = doc.getDocumentElement();
    NodeList tt = jnlp.getElementsByTagName("title");
    String title = null;
    Element elTitle = (Element)tt.item(0);
    if (elTitle != null)
    {
      title = elTitle.getFirstChild().getNodeValue();
      System.out.println("title="+title);
    }    
        
    NodeList nl = jnlp.getElementsByTagName("application-desc");
    Element applicationDesc = (Element)nl.item(0);
    NodeList arguments = applicationDesc.getElementsByTagName("argument");
    String args = null;
    for (int i=0; i<arguments.getLength(); i++) 
    {
      Element el = (Element)arguments.item(i);
      String arg = el.getFirstChild().getNodeValue();
      System.out.println("arg #"+i+": "+arg);
      if (args == null) args = arg;
      else              args = args+";"+arg;

    }
    return new String[] {args, title};    
  }  
  
  private String caricaJarDaJNLP(InputStream jnlpInputStream) throws Exception
  {
    Document doc = loadXmlDocument(jnlpInputStream);
    Element jnlp = doc.getDocumentElement();
    NodeList nl = jnlp.getElementsByTagName("jar");
    
    String archive = null; 
    for (int i=0; i<nl.getLength(); i++) 
    {
      Element jar = (Element)nl.item(i);
      String href = jar.getAttribute("href");
      if (href.startsWith("/client")) href = href.substring(8);
      //System.out.println(href);
      href = RELATIVE_PATH+href; 
      if (archive == null) archive = href;
      else archive = archive+","+href;
    }
    //System.out.println("archive="+archive);
    return archive;
  }
  
  private String caricaNativeLibsDaJNLP(InputStream jnlpInputStream) throws Exception
  {
    Document doc = loadXmlDocument(jnlpInputStream);
    Element jnlp = doc.getDocumentElement();
    NodeList nl = jnlp.getElementsByTagName("nativelib");
    
    String archive = null; 
    for (int i=0; i<nl.getLength(); i++) 
    {
      Element jar = (Element)nl.item(i);
      String href = jar.getAttribute("href");
      if (href.startsWith("/client")) href = href.substring(8);
      //System.out.println(href);
      href = RELATIVE_PATH+href;
      
      if (archive == null) archive = href;
      else archive = archive+","+href;
    }
    //System.out.println("archive="+archive);
    return archive;
  }
  
  private String caricaNuovoMenuDaJNLP(FileInputStream jnlpInputStream) throws Exception
  {
    String result = "false";
    Document doc = loadXmlDocument(jnlpInputStream);
    Element jnlp = doc.getDocumentElement();
    NodeList nl = jnlp.getElementsByTagName("resources");
    Element resources = (Element)nl.item(0);
    NodeList properties = resources.getElementsByTagName("property");
    for (int i=0; i<properties.getLength(); i++) 
    {
      Element el = (Element)properties.item(i);
      if(el.getAttribute("name") != null && el.getAttribute("name").equals("menu.maggioli"))
      {
        result = el.getAttribute("value");
      }
    }
    
    return result;
  }
  
  
  %>