Beispiel #1
0
 /**
  * This function is not part of the XmlSchema API. Who knows why?
  *
  * @param namespaceURI targetNamespace
  * @return schema, or null.
  */
 public XmlSchema getSchemaByTargetNamespace(String namespaceURI) {
   for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
     if (namespaceURI.equals(schema.getTargetNamespace())) {
       return schema;
     }
   }
   return null;
 }
 public File writeSchema(File targetDir, File schemaFile) throws Exception {
   File bkFile = new File(targetDir, "bk_" + schemaFile.getName());
   FileWriter writer = new FileWriter(bkFile);
   FileReader reader = new FileReader(schemaFile);
   XmlSchema schema = schemaCol.read(reader, null);
   schema.write(writer);
   reader.close();
   writer.close();
   writer = null;
   reader = null;
   return bkFile;
 }
Beispiel #3
0
 /**
  * Validate that a qualified name points to some namespace in the schema.
  *
  * @param qname
  */
 public void validateQNameNamespace(QName qname) {
   // astonishingly, xmlSchemaCollection has no accessor by target URL.
   if ("".equals(qname.getNamespaceURI())) {
     return; // references to the 'unqualified' namespace are OK even if there is no schema for it.
   }
   for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
     if (schema.getTargetNamespace().equals(qname.getNamespaceURI())) {
       return;
     }
   }
   throw new InvalidXmlSchemaReferenceException(qname + " refers to unknown namespace.");
 }
Beispiel #4
0
  public XmlSchema getSchemaForElement(QName name) {
    for (XmlSchema schema : schemaCollection.getXmlSchemas()) {
      if (name.getNamespaceURI().equals(schema.getTargetNamespace())) {

        if (schema.getElementByName(name.getLocalPart()) != null) {
          return schema;
        } else if (schema.getElementByName(name) != null) {
          return schema;
        }
      }
    }
    return null;
  }
Beispiel #5
0
 private void addOneSchemaCrossImports(XmlSchema schema) {
   /*
    * We need to visit all the top-level items.
    */
   for (XmlSchemaElement element : schema.getElements().values()) {
     addElementCrossImportsElement(schema, element);
   }
   for (XmlSchemaAttribute attribute : schema.getAttributes().values()) {
     XmlSchemaUtils.addImportIfNeeded(schema, attribute.getRef().getTargetQName());
     XmlSchemaUtils.addImportIfNeeded(schema, attribute.getSchemaTypeName());
   }
   for (XmlSchemaType type : schema.getSchemaTypes().values()) {
     addCrossImportsType(schema, type);
   }
 }
Beispiel #6
0
 /**
  * By convention, an element that is named in its schema's TNS can have a 'name' but no QName.
  * This can get inconvenient for consumers who want to think about qualified names. Unfortunately,
  * XmlSchema elements, unlike types, don't store a reference to their containing schema.
  *
  * @param element
  * @param schema
  */
 public static QName getElementQualifiedName(XmlSchemaElement element, XmlSchema schema) {
   if (element.getQName() != null) {
     return element.getQName();
   } else if (element.getName() != null) {
     return new QName(schema.getTargetNamespace(), element.getName());
   } else {
     return null;
   }
 }
Beispiel #7
0
  /**
   * Assist in managing the required <import namespace='uri'> for imports of peer schemas.
   *
   * @param schema
   * @param namespaceUri
   */
  public static void addImportIfNeeded(XmlSchema schema, String namespaceUri) {
    // no need to import nothing or the XSD schema, or the schema we are fixing.
    if ("".equals(namespaceUri)
        || Constants.URI_2001_SCHEMA_XSD.equals(namespaceUri)
        || schema.getTargetNamespace().equals(namespaceUri)) {
      return;
    }

    List<XmlSchemaExternal> externals = schema.getExternals();
    for (XmlSchemaExternal what : externals) {
      if (what instanceof XmlSchemaImport) {
        XmlSchemaImport imp = (XmlSchemaImport) what;
        // already there.
        if (namespaceUri.equals(imp.getNamespace())) {
          return;
        }
      }
    }
    XmlSchemaImport imp = new XmlSchemaImport(schema);
    imp.setNamespace(namespaceUri);
  }
Beispiel #8
0
 public static boolean isElementNameQualified(XmlSchemaElement element, XmlSchema schema) {
   if (element.isRef()) {
     throw new RuntimeException("isElementNameQualified on element with ref=");
   }
   if (element.getForm().equals(XmlSchemaForm.QUALIFIED)) {
     return true;
   }
   if (element.getForm().equals(XmlSchemaForm.UNQUALIFIED)) {
     return false;
   }
   return schema.getElementFormDefault().equals(XmlSchemaForm.QUALIFIED);
 }
Beispiel #9
0
 /**
  * Is there an import for a particular namespace in a schema?
  *
  * @param schema
  * @param namespaceUri
  */
 public static boolean schemaImportsNamespace(XmlSchema schema, String namespaceUri) {
   List<XmlSchemaExternal> externals = schema.getExternals();
   for (XmlSchemaExternal what : externals) {
     if (what instanceof XmlSchemaImport) {
       XmlSchemaImport imp = (XmlSchemaImport) what;
       // already there.
       if (namespaceUri.equals(imp.getNamespace())) {
         return true;
       }
     }
   }
   return false;
 }
Beispiel #10
0
  private void processXmlSchema(XmlSchema schema) {
    Map<QName, XmlSchemaElement> elements = schema.getElements();
    Iterator<XmlSchemaElement> xmlSchemaElementIterator = elements.values().iterator();

    while (xmlSchemaElementIterator.hasNext()) {
      Object o = xmlSchemaElementIterator.next();
      XmlSchemaElement element = (XmlSchemaElement) o;
      XmlSchemaType schemaType = element.getSchemaType();
      if (schemaType instanceof XmlSchemaComplexType) {
        processComplexType(element);
      } else if (schemaType instanceof XmlSchemaSimpleType) {
        processSimpleType(element);
      }
    }
  }
 private void processSchemaUpdates(
     QName elementQname, List<XmlSchema> xmlSchemaList, ConfigurationContext configContext) {
   Object ob = configContext.getProperty(JsonConstant.CURRENT_XML_SCHEMA);
   if (ob != null) {
     Map<QName, XmlSchema> schemaMap = (Map<QName, XmlSchema>) ob;
     if (schemaMap != null) {
       XmlSchema currentXmlSchema = schemaMap.get(elementQname);
       for (XmlSchema xmlSchema : xmlSchemaList) {
         if (xmlSchema.getTargetNamespace().equals(elementQname.getNamespaceURI())) {
           if (currentXmlSchema != xmlSchema) {
             schemaMap.put(elementQname, xmlSchema);
             configContext.setProperty(JsonConstant.XMLNODES, null);
             if (log.isDebugEnabled()) {
               log.debug(
                   "Updating message schema. [Current:"
                       + currentXmlSchema
                       + ", New:"
                       + xmlSchema
                       + "]");
             }
           }
           break;
         }
       }
     }
   } else {
     Map<QName, XmlSchema> schemaMap = new HashMap<QName, XmlSchema>();
     for (XmlSchema xmlSchema : xmlSchemaList) {
       if (xmlSchema.getTargetNamespace().equals(elementQname.getNamespaceURI())) {
         schemaMap.put(elementQname, xmlSchema);
         configContext.setProperty(JsonConstant.CURRENT_XML_SCHEMA, schemaMap);
         break;
       }
     }
   }
 }
 private static String extractNamespace(XmlSchema schema) {
   String pkg;
   pkg = schema.getTargetNamespace();
   if (pkg == null) {
     XmlSchema[] schemas2 = SchemaUtil.getAllSchemas(schema);
     for (int j = 0; schemas2 != null && j < schemas2.length; j++) {
       pkg = schemas2[j].getTargetNamespace();
       if (pkg != null) break;
     }
   }
   if (pkg == null) {
     pkg = URLProcessor.DEFAULT_PACKAGE;
   }
   pkg = URLProcessor.makePackageName(pkg);
   return pkg;
 }
 private XmlSchemaComplexType getComplexBaseType(
     XmlSchemaComplexContentExtension schemaComplexContent, XmlSchema schema) {
   XmlSchemaComplexType complexBaseType = null;
   QName baseTypeName = schemaComplexContent.getBaseTypeName();
   XmlSchemaType baseType = schema.getTypeByName(baseTypeName);
   if (baseType != null) {
     if (baseType instanceof XmlSchemaComplexType) {
       complexBaseType = (XmlSchemaComplexType) baseType;
     } else {
       throw new RuntimeException(
           "Unsupported complex base type: " + baseType.getClass().getCanonicalName());
     }
   } else {
     throw new RuntimeException("Schema complex base type not found: " + baseTypeName);
   }
   return complexBaseType;
 }
Beispiel #14
0
  /**
   * due to a bug, feature, or just plain oddity of JAXB, it isn't good enough to just check the
   * form of an element and of its schema. If schema 'a' (default unqualified) has a complex type
   * with an element with a ref= to schema (b) (default unqualified), JAXB seems to expect to see a
   * qualifier, anyway. <br>
   * So, if the element is local to a complex type, all we care about is the default element form of
   * the schema and the local form of the element. <br>
   * If, on the other hand, the element is global, we might need to compare namespaces. <br>
   *
   * @param element the element.
   * @param global if this element is a global element (complex type ref= to it, or in a part)
   * @param localSchema the schema of the complex type containing the reference, only used for the
   *     'odd case'.
   * @param elementSchema the schema for the element.
   * @return if the element needs to be qualified.
   */
  public static boolean isElementQualified(
      XmlSchemaElement element, boolean global, XmlSchema localSchema, XmlSchema elementSchema) {
    QName qn = getElementQualifiedName(element, localSchema);
    if (qn == null) {
      throw new RuntimeException("isElementQualified on anonymous element.");
    }
    if (element.isRef()) {
      throw new RuntimeException("isElementQualified on the 'from' side of ref=.");
    }

    if (global) {
      return isElementNameQualified(element, elementSchema)
          || (localSchema != null
              && !(qn.getNamespaceURI().equals(localSchema.getTargetNamespace())));
    } else {
      return isElementNameQualified(element, elementSchema);
    }
  }
  private XmlSchemaSimpleType getSimpleBaseType(QName simpleBaseTypeName, XmlSchema schema) {
    XmlSchemaSimpleType simpleBaseType = null;
    if (simpleBaseTypeName != null) {
      XmlSchemaType baseType = schema.getTypeByName(simpleBaseTypeName);
      if (baseType != null) {
        if (baseType instanceof XmlSchemaSimpleType) {
          simpleBaseType = (XmlSchemaSimpleType) baseType;
        } else {
          throw new RuntimeException(
              "Unsupported simple base type: " + baseType.getClass().getCanonicalName());
        }
      } else {
        throw new RuntimeException("Schema simple base type not found: " + simpleBaseTypeName);
      }
    }

    return simpleBaseType;
  }
  void loadSchema(XmlSchema schema) {
    XmlSchemaObjectCollection schemaItems = schema.getItems();

    // Iterate XML Schema items
    for (int i = 0; i < schemaItems.getCount(); i++) {
      XmlSchemaObject schemaObject = schemaItems.getItem(i);

      NeutralSchema neutralSchema;
      if (schemaObject instanceof XmlSchemaType) {
        neutralSchema = parse((XmlSchemaType) schemaObject, schema);
      } else if (schemaObject instanceof XmlSchemaElement) {
        neutralSchema = parseElement((XmlSchemaElement) schemaObject, schema);
      } else if (schemaObject instanceof XmlSchemaInclude) {
        continue; // nothing to do for includes
      } else {
        throw new RuntimeException(
            "Unhandled XmlSchemaObject: " + schemaObject.getClass().getCanonicalName());
      }
      schemas.put(neutralSchema.getType(), neutralSchema);
      partialSchemas.clear();
    }
  }
Beispiel #17
0
  /**
   * due to a bug, feature, or just plain oddity of JAXB, it isn't good enough to just check the
   * form of an element and of its schema. If schema 'a' (default unqualified) has a complex type
   * with an element with a ref= to schema (b) (default unqualified), JAXB seems to expect to see a
   * qualifier, anyway. <br>
   * So, if the element is local to a complex type, all we care about is the default element form of
   * the schema and the local form of the element. <br>
   * If, on the other hand, the element is global, we might need to compare namespaces. <br>
   *
   * @param attribute the attribute
   * @param global if this element is a global element (complex type ref= to it, or in a part)
   * @param localSchema the schema of the complex type containing the reference, only used for the
   *     'odd case'.
   * @param attributeSchema the schema for the element.
   * @return if the element needs to be qualified.
   */
  public static boolean isAttributeQualified(
      XmlSchemaAttribute attribute,
      boolean global,
      XmlSchema localSchema,
      XmlSchema attributeSchema) {
    if (attribute.getQName() == null) {
      throw new RuntimeException("getSchemaQualifier on anonymous element.");
    }
    if (attribute.isRef()) {
      throw new RuntimeException("getSchemaQualified on the 'from' side of ref=.");
    }

    if (global) {
      return isAttributeNameQualified(attribute, attributeSchema)
          || (localSchema != null
              && !(attribute
                  .getQName()
                  .getNamespaceURI()
                  .equals(localSchema.getTargetNamespace())));
    } else {
      return isAttributeNameQualified(attribute, attributeSchema);
    }
  }
 private static String getSchemaAsString(XmlSchema schema) {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   schema.write(baos);
   return baos.toString();
 }
  /**
   * @param additionalSchemas
   * @throws RuntimeException
   */
  public static TypeMapper processSchemas(
      final List schemas, Element[] additionalSchemas, CodeGenConfiguration cgconfig)
      throws RuntimeException {
    try {

      // check for the imported types. Any imported types are supposed to be here also
      if (schemas == null || schemas.isEmpty()) {
        // there are no types to be code generated
        // However if the type mapper is left empty it will be a problem for the other
        // processes. Hence the default type mapper is set to the configuration
        return new DefaultTypeMapper();
      }

      final Map schemaToInputSourceMap = new HashMap();
      final Map<String, StringBuffer> publicIDToStringMap = new HashMap<String, StringBuffer>();

      // create the type mapper
      JavaTypeMapper mapper = new JavaTypeMapper();

      String baseURI = cgconfig.getBaseURI();
      if (!baseURI.endsWith("/")) {
        baseURI = baseURI + "/";
      }

      for (int i = 0; i < schemas.size(); i++) {
        XmlSchema schema = (XmlSchema) schemas.get(i);
        InputSource inputSource = new InputSource(new StringReader(getSchemaAsString(schema)));
        // here we have to set a proper system ID. otherwise when processing the
        // included schaemas for this schema we have a problem
        // it creates the system ID using this target namespace value

        inputSource.setSystemId(baseURI + "xsd" + i + ".xsd");
        inputSource.setPublicId(schema.getTargetNamespace());
        schemaToInputSourceMap.put(schema, inputSource);
      }

      File outputDir = new File(cgconfig.getOutputLocation(), "src");
      // outputDir.mkdir();
      createDir(outputDir);

      Map nsMap = cgconfig.getUri2PackageNameMap();
      EntityResolver resolver =
          new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId)
                throws SAXException, IOException {
              InputSource returnInputSource = null;
              XmlSchema key = null;
              for (Iterator iter = schemaToInputSourceMap.keySet().iterator(); iter.hasNext(); ) {
                key = (XmlSchema) iter.next();
                String nsp = key.getTargetNamespace();
                if (nsp != null && nsp.equals(publicId)) {

                  // when returning the input stream we have to always return a new
                  // input stream.
                  // sinc jaxbri internally consumes the input stream it gives an
                  // exception.
                  returnInputSource = new InputSource(new StringReader(getSchemaAsString(key)));
                  InputSource existingInputSource = (InputSource) schemaToInputSourceMap.get(key);
                  returnInputSource.setSystemId(existingInputSource.getSystemId());
                  returnInputSource.setPublicId(existingInputSource.getPublicId());
                  break;
                }
              }
              if (returnInputSource == null) {
                // then we have to find this using the file system
                if (systemId != null) {
                  returnInputSource = new InputSource(systemId);
                  returnInputSource.setSystemId(systemId);
                }
              }

              if (returnInputSource == null) {
                if (publicId != null) {

                  if (!publicIDToStringMap.containsKey(publicId)) {
                    URL url = new URL(publicId);
                    BufferedReader bufferedReader =
                        new BufferedReader(new InputStreamReader(url.openStream()));
                    StringBuffer stringBuffer = new StringBuffer();
                    String str = null;
                    while ((str = bufferedReader.readLine()) != null) {
                      stringBuffer.append(str);
                    }
                    publicIDToStringMap.put(publicId, stringBuffer);
                  }

                  String schemaString = publicIDToStringMap.get(publicId).toString();
                  returnInputSource = new InputSource(new StringReader(schemaString));
                  returnInputSource.setPublicId(publicId);
                  returnInputSource.setSystemId(publicId);
                }
              }
              return returnInputSource;
            }
          };

      Map properties = cgconfig.getProperties();
      String bindingFileName = (String) properties.get(BINDING_FILE_NAME);

      XmlSchema key = null;
      for (Iterator schemaIter = schemaToInputSourceMap.keySet().iterator();
          schemaIter.hasNext(); ) {

        SchemaCompiler sc = XJC.createSchemaCompiler();
        if (bindingFileName != null) {
          if (bindingFileName.endsWith(".jar")) {
            scanEpisodeFile(new File(bindingFileName), sc);
          } else {
            InputSource inputSoruce = new InputSource(new FileInputStream(bindingFileName));
            inputSoruce.setSystemId(new File(bindingFileName).toURI().toString());
            sc.getOptions().addBindFile(inputSoruce);
          }
        }

        key = (XmlSchema) schemaIter.next();

        if (nsMap != null) {
          Iterator iterator = nsMap.entrySet().iterator();
          while (iterator.hasNext()) {
            Map.Entry entry = (Map.Entry) iterator.next();
            String namespace = (String) entry.getKey();
            String pkg = (String) nsMap.get(namespace);
            registerNamespace(sc, namespace, pkg);
          }
        }

        sc.setEntityResolver(resolver);

        sc.setErrorListener(
            new ErrorListener() {
              public void error(SAXParseException saxParseException) {
                log.error(saxParseException.getMessage());
                log.debug(saxParseException.getMessage(), saxParseException);
              }

              public void fatalError(SAXParseException saxParseException) {
                log.error(saxParseException.getMessage());
                log.debug(saxParseException.getMessage(), saxParseException);
              }

              public void warning(SAXParseException saxParseException) {
                log.warn(saxParseException.getMessage());
                log.debug(saxParseException.getMessage(), saxParseException);
              }

              public void info(SAXParseException saxParseException) {
                log.info(saxParseException.getMessage());
                log.debug(saxParseException.getMessage(), saxParseException);
              }
            });

        sc.parseSchema((InputSource) schemaToInputSourceMap.get(key));
        sc.getOptions().addGrammar((InputSource) schemaToInputSourceMap.get(key));

        for (Object property : properties.keySet()) {
          String propertyName = (String) property;
          if (propertyName.startsWith("X")) {
            String[] args = null;
            String propertyValue = (String) properties.get(property);
            if (propertyValue != null) {
              args = new String[] {"-" + propertyName, propertyValue};
            } else {
              args = new String[] {"-" + propertyName};
            }
            sc.getOptions().parseArguments(args);
          }
        }

        // Bind the XML
        S2JJAXBModel jaxbModel = sc.bind();

        if (jaxbModel == null) {
          throw new RuntimeException("Unable to generate code using jaxbri");
        }

        // Code change to sort Object factory classes start -SOA2.8
        sortGeneratedObjectFactoryClasses(jaxbModel);
        // Code change to sort Object factory classes end -SOA2.8

        // Emit the code artifacts
        JCodeModel codeModel = jaxbModel.generateCode(null, null);
        FileCodeWriter writer = new FileCodeWriter(outputDir);
        codeModel.build(writer);

        Collection mappings = jaxbModel.getMappings();

        Iterator iter = mappings.iterator();

        while (iter.hasNext()) {
          Mapping mapping = (Mapping) iter.next();
          QName qn = mapping.getElement();
          String typeName = mapping.getType().getTypeClass().fullName();

          mapper.addTypeMappingName(qn, typeName);
        }

        // process the unwrapped parameters
        if (!cgconfig.isParametersWrapped()) {
          // figure out the unwrapped operations
          List axisServices = cgconfig.getAxisServices();
          for (Iterator servicesIter = axisServices.iterator(); servicesIter.hasNext(); ) {
            AxisService axisService = (AxisService) servicesIter.next();
            for (Iterator operations = axisService.getOperations(); operations.hasNext(); ) {
              AxisOperation op = (AxisOperation) operations.next();

              if (WSDLUtil.isInputPresentForMEP(op.getMessageExchangePattern())) {
                AxisMessage message = op.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
                if (message != null && message.getParameter(Constants.UNWRAPPED_KEY) != null) {

                  Mapping mapping = jaxbModel.get(message.getElementQName());
                  List elementProperties = mapping.getWrapperStyleDrilldown();
                  for (int j = 0; j < elementProperties.size(); j++) {
                    Property elementProperty = (Property) elementProperties.get(j);

                    QName partQName =
                        WSDLUtil.getPartQName(
                            op.getName().getLocalPart(),
                            WSDLConstants.INPUT_PART_QNAME_SUFFIX,
                            elementProperty.elementName().getLocalPart());
                    // this type is based on a primitive type- use the
                    // primitive type name in this case
                    String fullJaveName = elementProperty.type().fullName();
                    if (elementProperty.type().isArray()) {
                      fullJaveName = fullJaveName.concat("[]");
                    }
                    mapper.addTypeMappingName(partQName, fullJaveName);

                    if (elementProperty.type().isPrimitive()) {
                      mapper.addTypeMappingStatus(partQName, Boolean.TRUE);
                    }
                    if (elementProperty.type().isArray()) {
                      mapper.addTypeMappingStatus(partQName, Constants.ARRAY_TYPE);
                    }
                  }
                }
              }

              if (WSDLUtil.isOutputPresentForMEP(op.getMessageExchangePattern())) {
                AxisMessage message = op.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE);
                if (message != null && message.getParameter(Constants.UNWRAPPED_KEY) != null) {

                  Mapping mapping = jaxbModel.get(message.getElementQName());
                  List elementProperties = mapping.getWrapperStyleDrilldown();
                  for (int j = 0; j < elementProperties.size(); j++) {
                    Property elementProperty = (Property) elementProperties.get(j);

                    QName partQName =
                        WSDLUtil.getPartQName(
                            op.getName().getLocalPart(),
                            WSDLConstants.OUTPUT_PART_QNAME_SUFFIX,
                            elementProperty.elementName().getLocalPart());
                    // this type is based on a primitive type- use the
                    // primitive type name in this case
                    String fullJaveName = elementProperty.type().fullName();
                    if (elementProperty.type().isArray()) {
                      fullJaveName = fullJaveName.concat("[]");
                    }
                    mapper.addTypeMappingName(partQName, fullJaveName);

                    if (elementProperty.type().isPrimitive()) {
                      mapper.addTypeMappingStatus(partQName, Boolean.TRUE);
                    }
                    if (elementProperty.type().isArray()) {
                      mapper.addTypeMappingStatus(partQName, Constants.ARRAY_TYPE);
                    }
                  }
                }
              }
            }
          }
        }
      }

      // Return the type mapper
      return mapper;

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }