Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
    * 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.xb.binding;
 
 import java.io.Reader;
 
 
 import  org.apache.xerces.xs.XSImplementation;
 import  org.apache.xerces.xs.XSLoader;
 import  org.apache.xerces.xs.XSModel;
 import  org.jboss.logging.Logger;
Various utilities for XML binding.

Author(s):
Alexey Loubyansky
Version:
$Revision: 2124 $
 
 public final class Util
 {
   
Characters that are considered to be word separators while convertinging XML names to Java identifiers according to JAXB 2.0 spec.
 
    public static final char HYPHEN_MINUS = '\u002D';
    public static final char FULL_STOP = '\u002E';
    public static final char COLLON = '\u003A';
    public static final char LOW_LINE = '\u005F';
    public static final char MIDDLE_DOT = '\u00B7';
    public static final char GREEK_ANO_TELEIA = '\u0387';
    public static final char ARABIC_END_OF_AYAH = '\u06DD';
    public static final char ARABIC_START_OF_RUB_EL_HIZB = '\u06DE';
 
    private static final Logger log = Logger.getLogger(Util.class);
 
    private static XSImplementation xsImpl;

   
Returns a prefixed name for the passed in QName instance. If the argument has a prefix, the prefix is used. If not then local part is returned.

Parameters:
qName an instance of QName to generate prefix name for
Returns:
generated prefixed name or empty string in case the argument is null
 
    public static String getPrefixedName(QName qName)
    {
       String result = "";
       if(qName != null)
       {
          String prefix = qName.getPrefix();
          if(prefix.length() > 0)
          {
             result = prefix + ':' + qName.getLocalPart();
          }
          else
          {
             result = qName.getLocalPart();
          }
       }
       return result;
    }

   
Returns a prefixed name for passed in QName instance. If the argument has a prefix then its prefix is used. If not and the argument has namespace URI then namespace context is used to get the prefix.

Parameters:
qName an instance of QName to generate prefix name for
nc an instance of the NamespaceContext
Returns:
generated prefixed name or empty string in case the argument is null
   public static String getPrefixedName(QName qNameNamespaceContext nc)
   {
      String result = "";
      if(qName != null)
      {
         String prefix = qName.getPrefix();
         if(prefix.length() > 0)
         {
            result = prefix + ':' + qName.getLocalPart();
         }
         else
         {
            String ns = qName.getNamespaceURI();
            prefix = nc.getPrefix(ns);
            if(prefix != null && prefix.length() > 0)
            {
               result = prefix + ':' + qName.getLocalPart();
            }
            else
            {
               result = qName.getLocalPart();
            }
         }
      }
      return result;
   }

   
Converts XML name to Java class name according to Binding XML Names to Java Identifiers C.2. The Name to Identifier Mapping Algorithm jaxb-2_0-edr-spec-10_jun_2004.pdf

Parameters:
name XML name
ignoreLowLine whether low lines should not be parts of Java identifiers
Returns:
Java class name
   public static String xmlNameToClassName(String nameboolean ignoreLowLine)
   {
      return XMLNameToJavaIdentifierConverter.PARSER.parse(.,
         name,
         ignoreLowLine
      );
   }
   public static String xmlNameToFieldName(String nameboolean ignoreLowLine)
   {
      return XMLNameToJavaIdentifierConverter.PARSER.parse(.,
         name,
         ignoreLowLine
      );
   }

   
Converts XML name to Java getter method name according to Binding XML Names to Java Identifiers C.2. The Name to Identifier Mapping Algorithm jaxb-2_0-edr-spec-10_jun_2004.pdf

Parameters:
name XML name
ignoreLowLine whether low lines should not be parts of Java identifiers
Returns:
Java getter method name
   public static String xmlNameToGetMethodName(String nameboolean ignoreLowLine)
   {
      return "get" + xmlNameToClassName(nameignoreLowLine);
   }

   
Converts XML name to Java setter method name according to Binding XML Names to Java Identifiers C.2. The Name to Identifier Mapping Algorithm jaxb-2_0-edr-spec-10_jun_2004.pdf

Parameters:
name XML name
ignoreLowLine whether low lines should not be parts of Java identifiers
Returns:
Java setter method name
   public static String xmlNameToSetMethodName(String nameboolean ignoreLowLine)
   {
      return "set" + xmlNameToClassName(nameignoreLowLine);
   }

   
Converts XML name to Java constant name according to Binding XML Names to Java Identifiers C.2. The Name to Identifier Mapping Algorithm jaxb-2_0-edr-spec-10_jun_2004.pdf

Parameters:
name XML name
Returns:
Java constant name
   public static String xmlNameToConstantName(String name)
   {
      return XMLNameToJavaIdentifierConverter.PARSER.parse(.,
         name,
         true
      );
   }

   
Converts XML namespace to Java package name. The base algorithm is described in JAXB-2.0 spec in 'C.5 Generating a Java package name'.

Parameters:
namespace XML namespace
Returns:
Java package name
   public static String xmlNamespaceToJavaPackage(String namespace)
   {
      if(namespace.length() == 0)
      {
         return namespace;
      }
      char[] src = namespace.toLowerCase().toCharArray();
      char[] dst = new char[namespace.length()];
      int srcInd = 0;
      // skip protocol part, i.e. http://, urn://
      while(src[srcInd++] != ':')
      {
      }
      while(src[srcInd] == '/')
      {
         ++srcInd;
      }
      // skip www part
      if(src[srcInd] == 'w' && src[srcInd + 1] == 'w' && src[srcInd + 2] == 'w')
      {
         srcInd += 4;
      }
      // find domain start and end indexes
      int domainStart = srcInd;
      while(srcInd < src.length && src[srcInd] != '/')
      {
         ++srcInd;
      }
      int dstInd = 0;
      // copy domain parts in the reverse order
      for(int start = srcInd - 1, end = srcIndtrue; --start)
      {
         if(start == domainStart)
         {
            System.arraycopy(srcstartdstdstIndend - start);
            dstInd += end - start;
            break;
         }
         if(src[start] == '.')
         {
            System.arraycopy(srcstart + 1, dstdstIndend - start - 1);
            dstInd += end - start;
            dst[dstInd - 1] = '.';
            end = start;
         }
      }
      // copy the rest
      while(srcInd < src.length)
      {
         char c = src[srcInd++];
         if(c == '/')
         {
            if(srcInd < src.length)
            {
               dst = append(dstdstInd++, '.');
               if(!Character.isJavaIdentifierStart(src[srcInd]))
               {
                  dst = append(dstdstInd++, '_');
               }
            }
         }
         else if(c == '.')
         {
            // for now assume it's an extention, i.e. '.xsd'
            break;
         }
         else
         {
            dst = append(dstdstInd++, Character.isJavaIdentifierPart(c) ? c : '_');
         }
      }
      return String.valueOf(dst, 0, dstInd);
   }

   
Converts XML namespace URI and local name to fully qualified class name.

Parameters:
namespaceUri namespace URI
localName local name
ignoreLowLine should low lines be ignored in the class name
Returns:
fully qualified class name
   public static String xmlNameToClassName(String namespaceUriString localNameboolean ignoreLowLine)
   {
      return namespaceUri == null || namespaceUri.length() == 0 ?
         xmlNameToClassName(localNameignoreLowLine) :
         xmlNamespaceToJavaPackage(namespaceUri) + '.' + xmlNameToClassName(localNameignoreLowLine);
   }
   public static boolean isAttributeType(final Class type)
   {
      return Classes.isPrimitive(type) ||
         type == String.class ||
         type == java.util.Date.class;
   }

   
Parse the namespace location pairs in the schemaLocation and return the location that matches the nsURI argument.

Returns:
the location uri if found, null otherwise
   public static String getSchemaLocation(Attributes attrsString nsUri)
   {
      String location = null;
      String schemaLocation = attrs.getValue(."schemaLocation");
      if(schemaLocation != null)
      {
         StringTokenizer tokenizer = new StringTokenizer(schemaLocation" \t\n\r");
         while (tokenizer.hasMoreTokens())
         {
            String namespace = tokenizer.nextToken();
            if (namespace.equals(nsUri) && tokenizer.hasMoreTokens())
            {
               location = tokenizer.nextToken();
               break;
            }
         }
      }
      return location;
   }
   public static XSModel loadSchema(String xsdURLSchemaBindingResolver schemaResolver)
   {
      boolean trace = .isTraceEnabled();
      long start = System.currentTimeMillis();
      if(trace)
         .trace("loading xsd: " + xsdURL);
      if( == null)
      {
          = getXSImplementation();
      }
      XSLoader schemaLoader = .createXSLoader(null);
      if(schemaResolver != null)
      {
         setResourceResolver(schemaLoaderschemaResolver);
      }
      setDOMErrorHandler(schemaLoader);
      XSModel model = schemaLoader.loadURI(xsdURL);
      if(model == null)
      {
         throw new IllegalArgumentException("Invalid URI for schema: " + xsdURL);
      }
      if (trace)
         .trace("Loaded xsd: " + xsdURL + " in " + (System.currentTimeMillis() - start) + "ms");
      return model;
   }
   public static XSModel loadSchema(InputStream isString encodingSchemaBindingResolver schemaResolver)
   {
      if(.isTraceEnabled())
      {
         .trace("loading xsd from InputStream");
      }
      LSInputAdaptor input = new LSInputAdaptor(isencoding);
      XSImplementation impl = getXSImplementation();
      XSLoader schemaLoader = impl.createXSLoader(null);
      setDOMErrorHandler(schemaLoader);
      if(schemaResolver != null)
      {
         setResourceResolver(schemaLoaderschemaResolver);
      }
      return schemaLoader.load(input);
   }
   public static XSModel loadSchema(Reader readerString encodingSchemaBindingResolver schemaResolver)
   {
      if(.isTraceEnabled())
      {
         .trace("loading xsd from Reader");
      }
      LSInputAdaptor input = new LSInputAdaptor(readerencoding);
      XSImplementation impl = getXSImplementation();
      XSLoader schemaLoader = impl.createXSLoader(null);
      setDOMErrorHandler(schemaLoader);
      if(schemaResolver != null)
      {
         setResourceResolver(schemaLoaderschemaResolver);
      }
      return schemaLoader.load(input);
   }
   public static XSModel loadSchema(String dataString encoding)
   {
      if(.isTraceEnabled())
      {
         .trace("loading xsd from string");
      }
      LSInputAdaptor input = new LSInputAdaptor(dataencoding);
      XSImplementation impl = getXSImplementation();
      XSLoader schemaLoader = impl.createXSLoader(null);
      setDOMErrorHandler(schemaLoader);
      return schemaLoader.load(input);
   }
   // Private

   
Sets an array character's element with the given index to a character value. If index is more or equal to the length of the array, a new array is created with enough length to set the element.

Parameters:
buf array of characters
index index of the element to set
ch character to set
Returns:
if the index parameter is less then array's length then the original array is returned, otherwise a new array is returned
   private static char[] append(char[] bufint indexchar ch)
   {
      if(index >= buf.length)
      {
         char[] tmp = buf;
         buf = new char[index + 4];
         System.arraycopy(tmp, 0, buf, 0, tmp.length);
      }
      buf[index] = ch;
      return buf;
   }
   private static void setResourceResolver(XSLoader schemaLoaderfinal SchemaBindingResolver schemaResolver)
   {
      DOMConfiguration config = schemaLoader.getConfig();
      config.setParameter("resource-resolver"new LSResourceResolver()
      {
         public LSInput resolveResource(String typeString namespaceURIString publicIdString systemIdString baseURI)
         {
            if (..equals(type))
            {
               String schemaLocation = systemId;
               return schemaResolver.resolveAsLSInput(namespaceURIbaseURIschemaLocation);
            }
            return null;
         }
      }
      );
   }
   private static void setDOMErrorHandler(XSLoader schemaLoader)
   {
      DOMConfiguration config = schemaLoader.getConfig();
      DOMErrorHandler errorHandler = (DOMErrorHandler)config.getParameter("error-handler");
      if (errorHandler == null)
      {
         config.setParameter("error-handler", XsdBinderTerminatingErrorHandler.newInstance());
      }
   }
   private static XSImplementation getXSImplementation()
   {
      return (XSImplementation) AccessController.doPrivileged(new PrivilegedAction()
      {
         public Object run()
         {
            
            // Get DOM Implementation using DOM Registry
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            try
            {
               // Try the 2.6.2 version
               String name = "org.apache.xerces.dom.DOMXSImplementationSourceImpl";
               loader.loadClass(name);
               System.setProperty(.name);
            }
            catch(ClassNotFoundException e)
            {
               // Try the 2.7.0 version
               String name = "org.apache.xerces.dom.DOMXSImplementationSourceImpl";
               System.setProperty(.name);
            }
            XSImplementation impl;
            try
            {
               DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
               impl = (XSImplementation)registry.getDOMImplementation("XS-Loader");
            }
            catch(Exception e)
            {
               throw new IllegalStateException("Failed to create schema loader: " + e.getClass().getName() + " " + e.getMessage());
            }
            return impl;
         }
      });
   }
   // Inner

   
An interface for XML name to Java identifier (class name, get/set methods, constant names) converter. The following rules and algorithms should be supported
  • Binding XML Names to Java Identifiers, C.2. The Name to Identifier Mapping Algorithm, jaxb-2_0-edr-spec-10_jun_2004.pdf
  • http://www.w3.org/TR/soap12-part2/#namemap

But these are not guaranteed to work yet. Instead, a simplified implementation is provided. Incompatabilities should be fixed.

   {
      // commands indicating what should be done with the next character from the XML name
      byte IGNORE = 0;
      byte APPEND = 1;
      byte APPEND_WITH_LOW_LINE = 2;
      byte APPEND_UPPER_CASED = 3;
      byte APPEND_UPPER_CASED_WITH_LOW_LINE = 4;

      
Returns a command for the next character given the previous character.

Parameters:
prev previous character
next next character
ignoreLowLine whether low lines are allowed in the Java identifier or should be ignored
Returns:
command for the next character
      byte commandForNext(char prevchar nextboolean ignoreLowLine);
      char firstCharacter(char chString strint secondCharIndex);

      
An XML name parser class that parses the XML name and asks the outer interface implementation what to do with the next parsed character from the XML name.
      final class PARSER
      {
         
Parses an XML name, asks the converter for a command for the next parsed character, applies the command, composed the resulting Java identifier.

Parameters:
converter an implementation of XMLNameToJavaIdentifierConverter
xmlName XML name
ignoreLowLine indicated whether low lines are allowed as part of the Java identifier or should be ignored
Returns:
Java identifier
         static String parse(XMLNameToJavaIdentifierConverter converterString xmlNameboolean ignoreLowLine)
         {
            if(xmlName == null || xmlName.length() == 0)
            {
               throw new IllegalArgumentException("Bad XML name: " + xmlName);
            }
            char c = xmlName.charAt(0);
            int i = 1;
            if(!Character.isJavaIdentifierStart(c) || (c ==  && ignoreLowLine))
            {
               while(i < xmlName.length())
               {
                  c = xmlName.charAt(i++);
                  if(Character.isJavaIdentifierStart(c) && !(c ==  && ignoreLowLine))
                  {
                     break;
                  }
               }
               if(i == xmlName.length())
               {
                  throw new IllegalArgumentException(
                     "XML name contains no valid character to start Java identifier: " + xmlName
                  );
               }
            }
            char[] buf = new char[xmlName.length() - i + 1];
            buf[0] = converter.firstCharacter(cxmlNamei);
            int bufInd = 1;
            while(i < xmlName.length())
            {
               char prev = c;
               c = xmlName.charAt(i++);
               byte command = converter.commandForNext(prevcignoreLowLine);
               switch(command)
               {
                  case :
                     break;
                  case :
                     buf = Util.append(bufbufInd++, c);
                     break;
                  case :
                     buf = Util.append(bufbufInd++, );
                     buf = Util.append(bufbufInd++, c);
                     break;
                  case :
                     buf = Util.append(bufbufInd++, Character.toUpperCase(c));
                     break;
                  case :
                     buf = Util.append(bufbufInd++, );
                     buf = Util.append(bufbufInd++, Character.toUpperCase(c));
                     break;
                  default:
                     throw new IllegalArgumentException("Unexpected command: " + command);
               }
            }
            return new String(buf, 0, bufInd);
         }
      }

      
XML name to Java class name converter
      {
         public char firstCharacter(char chString strint secondCharIndex)
         {
            return Character.toUpperCase(ch);
         }
         public byte commandForNext(char prevchar nextboolean ignoreLowLine)
         {
            byte command;
            if(Character.isDigit(next))
            {
               command = ;
            }
            else if(next == )
            {
               command = ignoreLowLine ?  : ;
            }
            else if(Character.isJavaIdentifierPart(next))
            {
               if(Character.isJavaIdentifierPart(prev) && !Character.isDigit(prev))
               {
                  command = prev ==  ?  : ;
               }
               else
               {
                  command = ;
               }
            }
            else
            {
               command = ;
            }
            return command;
         }
      };

      
XML name to Java class name converter
      {
         public char firstCharacter(char chString strint secondCharIndex)
         {
            if(Character.isLowerCase(ch))
            {
               return ch;
            }
            else
            {
               return (str.length() > secondCharIndex &&
                  Character.isJavaIdentifierPart(str.charAt(secondCharIndex)) &&
                  Character.isUpperCase(str.charAt(secondCharIndex))
                  ) ?
                  Character.toUpperCase(ch) :
                  Character.toLowerCase(ch);
            }
         }
         public byte commandForNext(char prevchar nextboolean ignoreLowLine)
         {
            return .commandForNext(prevnextignoreLowLine);
         }
      };

      
XML name to Java constant name converter
      {
         public char firstCharacter(char chString strint secondCharIndex)
         {
            return Character.toUpperCase(ch);
         }
         public byte commandForNext(char prevchar nextboolean ignoreLowLine)
         {
            byte command;
            if(Character.isDigit(next))
            {
               command = Character.isDigit(prev) ?  : ;
            }
            else if(Character.isJavaIdentifierPart(next))
            {
               if(Character.isDigit(prev))
               {
                  command = ;
               }
               else if(Character.isJavaIdentifierPart(prev))
               {
                  command = Character.isUpperCase(next) ?
                     (Character.isUpperCase(prev) ?  : ) :
                     ;
               }
               else
               {
                  command = ;
               }
            }
            else
            {
               command = ;
            }
            return command;
         }
      };
   }
New to GrepCode? Check out our FAQ X