1. /*
  2. * Copyright 1999-2004 The Apache Software Foundation.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. /*
  17. * $Id: FuncTranslate.java,v 1.8 2004/02/17 04:34:00 minchau Exp $
  18. */
  19. package com.sun.org.apache.xpath.internal.functions;
  20. import com.sun.org.apache.xpath.internal.XPathContext;
  21. import com.sun.org.apache.xpath.internal.objects.XObject;
  22. import com.sun.org.apache.xpath.internal.objects.XString;
  23. /**
  24. * Execute the Translate() function.
  25. * @xsl.usage advanced
  26. */
  27. public class FuncTranslate extends Function3Args
  28. {
  29. /**
  30. * Execute the function. The function must return
  31. * a valid object.
  32. * @param xctxt The current execution context.
  33. * @return A valid XObject.
  34. *
  35. * @throws javax.xml.transform.TransformerException
  36. */
  37. public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
  38. {
  39. String theFirstString = m_arg0.execute(xctxt).str();
  40. String theSecondString = m_arg1.execute(xctxt).str();
  41. String theThirdString = m_arg2.execute(xctxt).str();
  42. int theFirstStringLength = theFirstString.length();
  43. int theThirdStringLength = theThirdString.length();
  44. // A vector to contain the new characters. We'll use it to construct
  45. // the result string.
  46. StringBuffer sbuffer = new StringBuffer();
  47. for (int i = 0; i < theFirstStringLength; i++)
  48. {
  49. char theCurrentChar = theFirstString.charAt(i);
  50. int theIndex = theSecondString.indexOf(theCurrentChar);
  51. if (theIndex < 0)
  52. {
  53. // Didn't find the character in the second string, so it
  54. // is not translated.
  55. sbuffer.append(theCurrentChar);
  56. }
  57. else if (theIndex < theThirdStringLength)
  58. {
  59. // OK, there's a corresponding character in the
  60. // third string, so do the translation...
  61. sbuffer.append(theThirdString.charAt(theIndex));
  62. }
  63. else
  64. {
  65. // There's no corresponding character in the
  66. // third string, since it's shorter than the
  67. // second string. In this case, the character
  68. // is removed from the output string, so don't
  69. // do anything.
  70. }
  71. }
  72. return new XString(sbuffer.toString());
  73. }
  74. }