<?xml version="1.0"?>
<!-- Copyright 1998-2003 W3C (MIT, ERCIM, Keio), All Rights Reserved. See http://www.w3.org/Consortium/Legal/. -->
<!--  Transforms an ircgi test file into a Java Server Page.
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/" >
  <xsl:apply-templates />
</xsl:template>

<xsl:template match="ircgi">
  <xsl:call-template name="header" />
  <xsl:call-template name="declarations" />
  <xsl:call-template name="determineResult" />
</xsl:template>

<!--   Official contentType is 'application/voicexml+xml'.
  Change contentType to 'text/xml' to view generated JSP in IE.
 -->
<!-- D.B. 27/12/03: Removed new lines in content -->
<xsl:template name="header" >&lt;%@ page language="java" contentType="text/xml" %>&lt;%@ page import="java.io.BufferedInputStream" %>&lt;%@ page import="java.io.BufferedReader" %>&lt;%@ page import="java.io.InputStreamReader" %>&lt;%@ page import="java.net.URL" %>&lt;%@ page import="java.net.URLConnection" %>&lt;%@ page import="java.util.Date" %></xsl:template>

<!--   Define a Result class to hold the destination, comments, and
  HTTP status code that will be set by 'determineResult' method.
-->
<xsl:template name="declarations">&lt;%!
    
    // Handles server side includes so they can be parsed
    private class JSPIncluder
    {
        void readInput(HttpServletRequest request, String strIncludePath) throws JspException
        {
            URLConnection conn;

            // Get URL
            StringBuffer strUrl = request.getRequestURL();
            String strUri = strUrl.toString();
            int nFindSlash = strUri.lastIndexOf("/");
            if (nFindSlash != -1)
            {
                strUri = strUri.substring(0, nFindSlash + 1);              
            }
            strUri += strIncludePath;
            // Open connection
            try
            {
                conn = (new URL(strUri)).openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(false);
                conn.connect();
            }
            catch (Exception e)
            {
                throw new JspException(e.toString());
            }

            // Read in contents
            try
            {
                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuffer buff = new StringBuffer();
                char[] chars = new char[2048];
                int nLen;

                while ((nLen = in.read(chars, 0, chars.length)) &gt;= 0)
                {
                    buff.append(chars, 0, nLen);
                }
                m_strBuffer = buff.toString();
                in.close();
            }
            catch (Exception e)
            {
                throw new JspException(e.toString());
            }
        }

        boolean replace(String strFind, String strReplace)
        {
            boolean bFound = false;
            if (m_strBuffer != null &amp;&amp; m_strBuffer.length() > 0)
            {
                int a = 0;
                int b = 0;
                while (true)
                {
                    a = m_strBuffer.indexOf(strFind, b);
                    if (a != -1)
                    {
                        m_strBuffer = m_strBuffer.substring(0, a) + strReplace + m_strBuffer.substring(a + strFind.length());
                        b = a + strReplace.length();
                        bFound = true;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return bFound;
        }
        
        void doOutput(PageContext context) throws JspException
        {
            JspWriter out = context.getOut();
            try
            {
                out.print(m_strBuffer.toString());
            }
            catch (Exception e)
            {
                throw new JspException(e.toString());
            }   
        }
        private String m_strBuffer;
    }
    
  private class Result {
    String dest;
    long sleep = 0;
    boolean expiresHeaderSet = false;
    long expires = 0;
    boolean include = false;
    StringBuffer comments = new StringBuffer();
    int statusCode = 200;
  }
  private final String NL = System.getProperty("line.separator");
  private void determineResult(HttpServletRequest request, Result result) {
    <xsl:apply-templates />
  }
%&gt;</xsl:template>


<!--  Create Result object and call 'determineResult' to set its fields.
  Return VoiceXML document only if HTTP response status code is 200.
  Otherwise, return just the status code.
-->
<xsl:template name="determineResult" >&lt;%
    Result myResult = new Result();
    determineResult(request, myResult);
    response.setStatus(myResult.statusCode);
    
    if (myResult.sleep &gt; 0)
    {
        try
        {
            Thread.sleep(myResult.sleep * 1000);
        }
        catch (InterruptedException e)
        {
            throw new JspException(e.toString());
        }
    }
    
    if (myResult.expiresHeaderSet)
    {
        Date now = new Date();
        long nMillis = now.getTime();
        response.setDateHeader("Expires", nMillis + myResult.expires*1000);
    }
    
    if (myResult.include) 
    {
        Date now = new Date();
        long nMillis = now.getTime();
        String strEpoch = String.valueOf(nMillis);
        JSPIncluder includer = new JSPIncluder();
        includer.readInput(request, myResult.dest);
        includer.replace("__EPOCH__", strEpoch);
        includer.doOutput(pageContext);
    }
    else {%&gt;<xsl:call-template name="vxml" />&lt;%}%&gt;
</xsl:template>


<xsl:template match="if-parameter" >
  if (<xsl:call-template name="genIfExpr">
        <xsl:with-param name="type" select="'Parameter'" />
      </xsl:call-template>) {
    <xsl:apply-templates />
  }
</xsl:template>


<xsl:template match="if-header" >
  if (<xsl:call-template name="genIfExpr">
        <xsl:with-param name="type" select="'Header'" />
      </xsl:call-template>) {
    <xsl:apply-templates />
  }
</xsl:template>


<!--  Generate an expression that determines when the condition of an 'if-*'
  element is true.  The 'type' parameter determines the
  HttpServletRequest method to use to get the value to be checked.
-->
<xsl:template name="genIfExpr" >
  <xsl:param name="type" />
  <xsl:variable name="method">
    <xsl:choose>
      <xsl:when test="@ignore-case = 'true'" >equalsIgnoreCase</xsl:when>
      <xsl:otherwise>equals</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  <xsl:choose>
    <xsl:when test="@value">
      request.get<xsl:value-of select="$type"/>
        ("<xsl:value-of select="@name"/>") != null &amp;&amp;
      request.get<xsl:value-of select="$type"/>
        ("<xsl:value-of select="@name"/>").<xsl:value-of select="$method"/>
        ("<xsl:value-of select="@value" />")
    </xsl:when>
    <xsl:otherwise>
      request.get<xsl:value-of select="$type"/>("<xsl:value-of select="@name"/>") != null
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>


<xsl:template match="if-method" >
  if (request.getMethod().equalsIgnoreCase("<xsl:value-of select="@type" />")) {
    <xsl:apply-templates />
  }
</xsl:template>


<!--  Disarm double quotes and newline characters from comments, then
  add to result's comment buffer for use later in 'log' element.
-->
<xsl:template match="comment" >
  result.comments.append
    ("<xsl:value-of select="translate(., '&#034;&#013;&#010;', '   ')" />".trim());
  result.comments.append(NL);
</xsl:template>


<xsl:template match="next" >
  <xsl:if test="@code" >
    result.statusCode = <xsl:value-of select="@code" />;
  </xsl:if>
  <xsl:if test="@dest" >
      result.dest = "<xsl:value-of select="@dest" />";
  </xsl:if>
  <xsl:if test="@include = 'true'">
    result.include = true;
  </xsl:if>  
  <xsl:if test="@sleep">
      result.sleep = <xsl:value-of select="@sleep" />;
  </xsl:if>  
  <xsl:if test="@expires">
      result.expiresHeaderSet = true;
      result.expires = <xsl:value-of select="@expires" />;
  </xsl:if>
    return;
</xsl:template>


<!--  Generate VoiceXML document that does a 'goto' to the document
  indicated in myResult.  If comment buffer is not empty, include
  a 'log' element to aid in debugging.
-->
<xsl:template name="vxml" ><![CDATA[<?xml version="1.0" ?>
<vxml version="2.0" xmlns="http://www.w3.org/2001/vxml">
  <form>
    <block><% String comments = myResult.comments.toString();
   if (comments.length()>0) {%>
      <log>]]>
        <xsl:text disable-output-escaping="yes">
          &lt;![CDATA[&lt;%= comments %&gt;]]&gt;
        </xsl:text><![CDATA[
      </log><%}%>
      <goto next="<%= myResult.dest %>"/>
    </block>
  </form>
</vxml> ]]>
</xsl:template>

</xsl:stylesheet>

