/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.boot.servlets;

import javax.xml.transform.TransformerException;

import org.apache.xalan.extensions.ExpressionContext;
import org.apache.xml.utils.QName;
import org.apache.xpath.objects.XObject;

import gnu.regexp.RE;
import gnu.regexp.REException;
import gnu.regexp.REMatch;

/** A utility class that implements a xalan XSLT extension function used by
the default.xsl transformation document.

 *
 * @author  Scott.Stark@jboss.org
 * @version $revision:$
 */
public class Util
{
   static RE variableRE;

   public static void setVariableRE(RE variableRE)
   {
      Util.variableRE = variableRE;
   }

   /** This function replaces all occurrences of variable references ${...} with
    the corresponding XSL variable. If no such variable is defined the variable
    is replaced with an empty string.
   */
   public static String replaceVariables(ExpressionContext ctx, String text)
   {
      String value = text;
      try
      {
         REMatch[] matches = variableRE.getAllMatches(text);
         if( matches.length > 0 )
         {
            StringBuffer tmp = new StringBuffer();
            for(int m = 0; m < matches.length; m ++)
            {
               String prefix = matches[m].toString(1);
               String name = matches[m].toString(2);
               String suffix = matches[m].toString(3);
               QName varName = new QName(name);
               XObject var = ctx.getVariableOrParam(varName);
               tmp.append(prefix);
               if( var != null )
                  tmp.append(var.toString());
               tmp.append(suffix);
            }
            value = tmp.toString();
         }
      }
      catch(TransformerException e)
      {
         e.printStackTrace();
      }
      return value;
   }

}
