/*
   * Analyze the schema at the given URI, the schema is parsed and stored in
   * XMLObjectInfos.
   */
  private void analyzeXSD(URI uri) {

    uri = uri.normalize();

    // already seen this xsd, skip it
    if (xmlObjectInfos.containsKey(uri.toString())) return;

    XSDSchema xsdSchema = XSDSchemaImpl.getSchemaForSchema(uri.toString());

    String encoding = null;
    // if schema is not cached, parse it
    if (xsdSchema == null) {
      XSDParser p = new XSDParser(null);
      InputStream is = NetUtils.getURLInputStream(uri.toString());

      if (is != null) {
        p.parse(is);
        xsdSchema = p.getSchema();
        encoding = p.getEncoding();
      }
    } else encoding = xsdSchema.getDocument().getXmlEncoding();

    if (xsdSchema != null) {

      if (encoding == null) encoding = "UTF-8";

      XMLObjectInfo info = new XMLObjectInfo(new Path(uri.getPath()), xsdSchema, encoding);
      xmlObjectInfos.put(uri.toString(), info);
      updatePathPrefix(info);

      // analyze its imports and includes
      analyzeXSD(uri, xsdSchema);
    }
  }
  private void resetXsdSimpleTypeUuids(final Resource resource) throws Exception {
    if (resource instanceof XSDResourceImpl) {
      final XSDResourceImpl xsdResource = (XSDResourceImpl) resource;
      final XSDSchema schema = xsdResource.getSchema();
      if (schema != null) {
        for (final Iterator iter = schema.getContents().iterator(); iter.hasNext(); ) {
          EObject eObj = (EObject) iter.next();

          // Only process global simple type definitions ...
          if (eObj instanceof XSDSimpleTypeDefinition) {
            final XSDSimpleTypeDefinition type = (XSDSimpleTypeDefinition) eObj;

            // Get the application information ...
            final XSDAnnotation annotation = type.getAnnotation();

            // If no annotation exists then no UUID attribute exists to reset ...
            if (annotation == null) {
              continue;
            }
            for (final Iterator appInfos = annotation.getApplicationInformation().iterator();
                appInfos.hasNext(); ) {
              final Element appInfo = (Element) appInfos.next();
              String uuid = appInfo.getAttribute(UUID_ATTRIBUTE_NAME);
              if (uuid != null) {
                uuid = IDGenerator.getInstance().create().toString();
                appInfo.setAttribute(UUID_ATTRIBUTE_NAME, uuid);
                uuid = appInfo.getAttribute(UUID_ATTRIBUTE_NAME);
              }
            }
          }
        }
      }
    }
  }
Esempio n. 3
0
  /**
   * Like getPrimitives(), this returns a list of XSDSimpleTypeDefinition. However where
   * getPrimitives() returns the basic set supported by the editor, getAdvancedPrimitives returns
   * every known XSD primitive type.
   *
   * @return list of simple type definitions.
   */
  public static List<XSDSimpleTypeDefinition> getAdvancedPrimitives() {

    if (advancedPrimitives == null) {

      advancedPrimitives = new ArrayList<XSDSimpleTypeDefinition>();

      // Get the schema for schemas instance to use when resolving primitives
      XSDSchema schemaForSchemas =
          XSDUtil.getSchemaForSchema(XSDConstants.SCHEMA_FOR_SCHEMA_URI_2001);

      // Start adding the simple types using the supportedPrimitives list
      for (String typeName : supportedPrimitives) {
        XSDSimpleTypeDefinition type = schemaForSchemas.resolveSimpleTypeDefinition(typeName);
        advancedPrimitives.add(type);
      }

      // Return primitives in alpha order
      Collections.sort(
          advancedPrimitives,
          new Comparator<XSDSimpleTypeDefinition>() {
            public int compare(XSDSimpleTypeDefinition o1, XSDSimpleTypeDefinition o2) {
              if (o1 == null || o2 == null || o1.getName() == null) return 0;
              return o1.getName().compareToIgnoreCase(o2.getName());
            }
          });
    }
    return advancedPrimitives;
  }
  /** Helper method for identifying if a given type is a built-in type. */
  public static boolean isBuiltInType(XSDTypeDefinition target) {

    XSDSchema schema = (XSDSchema) target.eContainer();
    if (!XSDConstants.SCHEMA_FOR_SCHEMA_URI_2001.equals(schema.getTargetNamespace())) {
      return false;
    }
    return xsdPrimitiveTypesNames.contains(target.getName());
  }
 private void setXsdIncrementalBuild(final Resource resource, final boolean isIncrementalUpdate) {
   if (resource instanceof XSDResourceImpl) {
     final XSDResourceImpl xsdResource = (XSDResourceImpl) resource;
     final XSDSchema schema = xsdResource.getSchema();
     if (schema != null) {
       schema.setIncrementalUpdate(isIncrementalUpdate);
     }
   }
 }
 private boolean getXsdIncrementalBuild(final Resource resource) {
   if (resource instanceof XSDResourceImpl) {
     final XSDResourceImpl xsdResource = (XSDResourceImpl) resource;
     final XSDSchema schema = xsdResource.getSchema();
     if (schema != null) {
       return schema.isIncrementalUpdate();
     }
   }
   return false;
 }
  protected Object[] getXSDSchemaChildren(XSDSchema schema) {
    List<XSDElementDeclaration> declarations = new ArrayList<XSDElementDeclaration>();

    List<Object> attributeDeclarations = new ArrayList<Object>();
    if (null != xsdSchema) {
      for (XSDSchemaContent cnt : xsdSchema.getContents()) {
        if (cnt instanceof XSDInclude) {
          XSDInclude incu = (XSDInclude) cnt;
          String schemaLocation = incu.getSchemaLocation();
          XSDSchema schemaInc = createSchema(schemaLocation);
          addElementDeclarationFromSchema(schemaInc, declarations);
        } else if (cnt instanceof XSDAttributeDeclaration) {
          XSDAttributeDeclaration attriDec = (XSDAttributeDeclaration) cnt;
          attributeDeclarations.add(attriDec);
        }
      }
    }
    addElementDeclarationFromSchema(schema, declarations);

    Object[] schemaChildren =
        Util.filterOutDuplicatedElems(
            declarations.toArray(new XSDNamedComponent[declarations.size()]));
    attributeDeclarations.addAll(Arrays.asList(schemaChildren));

    return attributeDeclarations.toArray();
  }
  /**
   * Walk through all XSDDirectives for the specified XSDResource and attempt to resolve those that
   * are undefined.
   *
   * @param eResource
   * @param recurse
   * @param visited
   * @since 4.3
   */
  protected void resolveSchemaDirectives(
      final XSDResourceImpl eResource,
      final boolean recurse,
      final Set visited,
      final Set unresolvedResourceURIs) {

    if (eResource != null && !visited.contains(eResource)) {
      // The resource must be loaded to retrieve its contents
      if (!eResource.isLoaded()) {
        try {
          eResource.load(getContainer().getLoadOptions());
        } catch (IOException err) {
          String msg =
              ModelerCore.Util.getString(
                  "DefaultResourceFinder.Error_loading_resource", eResource); // $NON-NLS-1$
          ModelerCore.Util.log(IStatus.ERROR, msg);
        }
      }
      // Add this resource to the list of those visited
      visited.add(eResource);

      // Check all imports to see if they were resolved
      for (final Iterator i = eResource.getSchema().eContents().iterator(); i.hasNext(); ) {
        EObject eObj = (EObject) i.next();
        if (eObj instanceof XSDSchemaDirective) {
          XSDSchema resolvedSchema = resolveSchemaDirective((XSDSchemaDirective) eObj);

          // Log any unresolved schema directives
          if (resolvedSchema == null
              || resolvedSchema.eResource() == null
              || resolvedSchema.eResource().getResourceSet() == null) {
            URI unresolvedURI = URI.createURI(((XSDSchemaDirective) eObj).getSchemaLocation());
            unresolvedResourceURIs.add(unresolvedURI);
            continue;
          }

          // Follow the chain and resolve all directives for the schema being imported
          if (recurse)
            resolveSchemaDirectives(
                (XSDResourceImpl) resolvedSchema.eResource(),
                recurse,
                visited,
                unresolvedResourceURIs);
        }
      }
    }
  }
 private String getTargetNamespaceForResolve(
     final XSDElementDeclaration sourceComponent,
     final XSDSchema xsdSchema,
     final NamespaceResolverType namespaceResolverType) {
   return (namespaceResolverType == NamespaceResolverType.ELEMENT)
       ? sourceComponent.getResolvedElementDeclaration().getTargetNamespace()
       : xsdSchema.getTargetNamespace();
 }
 protected void addElementDeclarationFromSchema(
     XSDSchema schema, Collection<XSDElementDeclaration> declarations) {
   EList<XSDElementDeclaration> elementDeclarations = schema.getElementDeclarations();
   for (XSDElementDeclaration declaration : elementDeclarations) {
     if (declaration.eContainer().equals(schema)) {
       declarations.add(declaration);
     }
   }
 }
Esempio n. 11
0
  /**
   * Read an XSDSchema instance and create the node hierarchy under the given root node.
   *
   * @param schema the schema object; may not be null
   * @param encoding the encoding for the XSD; may be null if the encoding is not specified
   * @param contentSize the size of the XML Schema Document content; may not be negative
   * @param rootNode the root node that will be populated with the XML Schema Document information
   * @throws Exception if there is a probelm reading the XSD content
   */
  protected void process(XSDSchema schema, String encoding, long contentSize, Node rootNode)
      throws Exception {
    assert schema != null;

    logger.debug("Target namespace: '{0}'", schema.getTargetNamespace());
    rootNode.setProperty(SrampLexicon.CONTENT_TYPE, MimeTypeConstants.APPLICATION_XML);
    if (encoding != null) {
      rootNode.setProperty(SrampLexicon.CONTENT_ENCODING, encoding);
    }
    rootNode.setProperty(SrampLexicon.CONTENT_SIZE, contentSize);

    // Parse the annotations first to aggregate them all into a single 'sramp:description' property
    // ...
    @SuppressWarnings("unchecked")
    List<XSDAnnotation> annotations = schema.getAnnotations();
    processAnnotations(annotations, rootNode);
    processNonSchemaAttributes(schema, rootNode);

    // Parse the objects ...
    for (EObject obj : schema.eContents()) {
      if (obj instanceof XSDSimpleTypeDefinition) {
        processSimpleTypeDefinition((XSDSimpleTypeDefinition) obj, rootNode);
      } else if (obj instanceof XSDComplexTypeDefinition) {
        processComplexTypeDefinition((XSDComplexTypeDefinition) obj, rootNode);
      } else if (obj instanceof XSDElementDeclaration) {
        processElementDeclaration((XSDElementDeclaration) obj, rootNode);
      } else if (obj instanceof XSDAttributeDeclaration) {
        processAttributeDeclaration((XSDAttributeDeclaration) obj, rootNode, false);
      } else if (obj instanceof XSDImport) {
        processImport((XSDImport) obj, rootNode);
      } else if (obj instanceof XSDInclude) {
        processInclude((XSDInclude) obj, rootNode);
      } else if (obj instanceof XSDRedefine) {
        processRedefine((XSDRedefine) obj, rootNode);
      } else if (obj instanceof XSDAttributeGroupDefinition) {
        processAttributeGroupDefinition((XSDAttributeGroupDefinition) obj, rootNode);
      } else if (obj instanceof XSDAnnotation) {
        // already processed above ...
      }
    }

    // Resolve any outstanding, unresolved references ...
    resolveReferences();
  }
 private void parseNamespaceContainers(XSDSchema schema) {
   Iterator iterator = schema.getContents().iterator();
   while (iterator.hasNext()) {
     Object element = (Object) iterator.next();
     if (element instanceof XSDImport) {
       XSDImport importElement = (XSDImport) element;
       this.namespaceContainers.add(importElement.getNamespace());
     }
   }
 }
  /**
   * Resolve the specified XSDSchemaDirective and resolve against resources in the resource set
   *
   * @param eResource
   * @param recurse
   * @param visited
   * @since 4.3
   */
  protected XSDSchema resolveSchemaDirective(final XSDSchemaDirective directive) {
    XSDSchema resolvedSchema = null;
    if (directive != null) {
      resolvedSchema = directive.getResolvedSchema();

      // Import is not yet resolved, attempt to locate the reference ...
      if (resolvedSchema == null && directive instanceof XSDImportImpl) {
        resolvedSchema = ((XSDImportImpl) directive).importSchema();
      }

      // If the resolvedSchema reference exists but is an eProxy then attempt to resolve it
      if (resolvedSchema != null && resolvedSchema.eIsProxy()) {
        resolvedSchema = (XSDSchema) EcoreUtil.resolve(resolvedSchema, getContainer());
      }

      // Directive is not yet resolved, attempt to locate the referenced
      // XSDResource using the schema location information in the directive
      String location = directive.getSchemaLocation();
      XSDResourceImpl eResource = (XSDResourceImpl) directive.eResource();
      if (resolvedSchema == null && eResource != null && !CoreStringUtil.isEmpty(location)) {
        XSDResourceImpl refdResource = null;

        URI schemaLocationUri = UriHelper.makeAbsoluteUri(eResource.getURI(), location);
        // URI schemaLocationUri = getAbsoluteLocation(eResource.getURI(), location);
        refdResource = (XSDResourceImpl) findByURI(schemaLocationUri, false);

        // Update the directive with the resolved schema
        if (refdResource != null) {
          resolvedSchema = refdResource.getSchema();
          directive.setResolvedSchema(resolvedSchema);
          if (directive instanceof XSDImport) {
            ((XSDSchemaImpl) resolvedSchema).imported((XSDImport) directive);
          } else if (directive instanceof XSDInclude) {
            ((XSDSchemaImpl) resolvedSchema).included((XSDInclude) directive);
          } else if (directive instanceof XSDRedefine) {
            ((XSDSchemaImpl) resolvedSchema).redefined((XSDRedefine) directive);
          }
        }
      }
    }
    return resolvedSchema;
  }
Esempio n. 14
0
  /**
   * Given a schema, return the list of XSDSimpleTypeDefinitions found within it. Will not return
   * null, but may return an empty list
   *
   * @param schema
   * @return the user defined simple types.
   */
  public static List<XSDSimpleTypeDefinition> getUserDefinedSimpleTypes(XSDSchema schema) {
    if (schema == null) {
      return Collections.emptyList();
    }

    List<XSDSimpleTypeDefinition> result = new ArrayList<XSDSimpleTypeDefinition>();
    for (Object next : schema.getContents()) {
      if (next instanceof XSDSimpleTypeDefinition) result.add((XSDSimpleTypeDefinition) next);
    }
    return result;
  }
  /**
   * Add external resources referenced by the specified XSD resource to the resultant list
   *
   * @param eResource the resource to process for references
   * @param recurse if true, the result will include all direct and indirect dependent resources
   *     otherwise only the direct dependencies are returned.
   * @param includeExternal If true, external resource references will be included in the resulant
   *     array, otherwise they will be excluded from the result.
   * @param result the resultant list to add to
   */
  protected void addExternallyReferencedResourcesForXsd(
      final XSDResourceImpl eResource,
      final boolean recurse,
      final boolean includeExternal,
      final List result,
      final Set unresolvedResourceURIs) {
    if (eResource != null) {
      // Resolve all schema directives (import/include/redefine)
      Set visitedXsdResources = new HashSet();
      resolveSchemaDirectives(eResource, recurse, visitedXsdResources, unresolvedResourceURIs);

      // Add the resource referenced through the directive to the overall result
      XSDSchema schema = eResource.getSchema();
      for (final Iterator i = schema.eContents().iterator(); i.hasNext(); ) {
        EObject eObj = (EObject) i.next();
        if (eObj instanceof XSDSchemaDirective) {
          XSDSchema resolvedSchema = ((XSDSchemaDirective) eObj).getResolvedSchema();
          Resource rsrc = (resolvedSchema != null ? resolvedSchema.eResource() : null);
          if (rsrc != null && !result.contains(rsrc)) {
            if (!includeExternal && isExternalResource(rsrc)) {
              continue;
            }
            result.add(rsrc);
            if (recurse) {
              addExternallyReferencedResources(
                  rsrc, recurse, includeExternal, result, unresolvedResourceURIs);
            }
          }
        }
      }

      // Ensure that the schema for schema resource (e.g. "http://www.w3.org/2001/XMLSchema") is
      // added to the result;
      if (includeExternal) {
        Resource rsrc = schema.getSchemaForSchema().eResource();
        if (rsrc != null && !result.contains(rsrc)) {
          result.add(rsrc);
        }
      }
    }
  }
Esempio n. 16
0
 public static List<XSDSchema> allSchemas(XSDSchema s, List<String> includeUri) {
   Set<XSDSchema> result = Sets.newHashSet();
   result.add(s);
   for (XSDInclude inc : Iterables.filter(s.getContents(), XSDInclude.class)) {
     XSDSchema resolved = inc.getResolvedSchema();
     if (resolved == null) {
       resolved = resolve(inc, includeUri);
     }
     result.addAll(allSchemas(resolved, includeUri));
   }
   return Lists.newArrayList(result);
 }
  /*
   * Writes the xsd schema to the file at the given path, relative to the target folder.
   */
  private String writeXMLObj(
      IPath path, XSDSchema xsdSchema, String encoding, IProgressMonitor monitor)
      throws TransformerConfigurationException, TransformerException, URIException, IOException,
          CoreException {
    Transformer serializer = TransformerFactory.newInstance().newTransformer();
    Document document = xsdSchema.getDocument();
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.ENCODING, encoding);
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    Element e = xsdSchema.getElement();
    DOMSource domSource = new DOMSource(e);

    String[] targetURI = appendPathToURI(targetFolderURI, path);

    OutputStream os = uriFactory.newURI(targetURI[0]).getOutputStream();
    serializer.transform(domSource, new StreamResult(os));
    os.close();

    return targetURI[1];
  }
  /**
   * Check whether the schema is just used to import another schema.
   * http://ws-i.org/profiles/BasicProfile-1.2-WGD.html#WSDL_and_Schema_Import - R2105 All
   * xsd:schema elements contained in a wsdl:types element of a DESCRIPTION MUST have a
   * targetNamespace attribute with a valid and non-null value, UNLESS the xsd:schema element has
   * xsd:import and/or xsd:annotation as its only child element(s).
   *
   * @return empty list if schema is not WS-I R2105, otherwise schema's imports are returned.
   */
  public static List<XSDImport> getWsiImports(final XSDSchema schema) {
    final List<XSDImport> importedSchemas = new ArrayList<XSDImport>();
    if (schema == null
        || schema.getTargetNamespace() != null
            && !"".equals(schema.getTargetNamespace())) { // $NON-NLS-1$
      return importedSchemas;
    }

    for (final XSDSchemaContent schemaContent : schema.getContents()) {
      if (!(schemaContent instanceof XSDAnnotation) && !(schemaContent instanceof XSDImport)) {
        // not WS-I R2105 complaint schema
        importedSchemas.clear();
        return importedSchemas;
      }

      if (schemaContent instanceof XSDImport) {
        importedSchemas.add((XSDImport) schemaContent);
      }
    }
    return importedSchemas;
  }
  /**
   * Adds a new EMF {@link XSDSchema} in {@link Definition} with the specified namespace
   *
   * @param definition - wsdl where new schema is to be added
   * @param namespace - namespace of the new schema
   * @return - added schema object
   */
  public static XSDSchema addXSDSchema(final Definition definition, final String namespace) {
    Types types = definition.getETypes();
    if (null == types) {
      types = EmfWsdlUtils.getWSDLFactory().createTypes();
      definition.setTypes(types);
    }

    final XSDSchema xsdSchema = EmfXsdUtils.getXSDFactory().createXSDSchema();
    xsdSchema.setSchemaForSchemaQNamePrefix(EmfXsdUtils.XSD_PREFIX); // $NON-NLS-1$
    final Map<String, String> qNamePrefixToNamespaceMap = xsdSchema.getQNamePrefixToNamespaceMap();
    qNamePrefixToNamespaceMap.put(
        xsdSchema.getSchemaForSchemaQNamePrefix(), EmfXsdUtils.getSchemaForSchemaNS());

    final XSDSchemaExtensibilityElement schemaExtensibilityEntity =
        EmfWsdlUtils.getWSDLFactory().createXSDSchemaExtensibilityElement();
    schemaExtensibilityEntity.setSchema(xsdSchema);

    types.addExtensibilityElement(schemaExtensibilityEntity);
    schemaExtensibilityEntity.setEnclosingDefinition(definition);

    final String wsdlLocation = definition.getLocation();
    xsdSchema.setSchemaLocation(wsdlLocation);

    if (null != namespace && !"".equals(namespace.trim())) // $NON-NLS-1$
    xsdSchema.setTargetNamespace(namespace);

    return xsdSchema;
  }
  protected void addSchemaElements(List list, XSDSchema schema) {

    boolean builtInTypesSchema =
        XSDConstants.SCHEMA_FOR_SCHEMA_URI_2001.equals(schema.getTargetNamespace());

    if (builtInTypesSchema && (fFilter & INCLUDE_PRIMITIVES) > 0) {
      list.addAll(XSDUtils.getAdvancedPrimitives());
      return;
    }

    if ((fFilter & INCLUDE_ELEMENT_DECLARATIONS) > 0) {
      list.addAll(schema.getElementDeclarations());
    }

    if ((fFilter & INCLUDE_TYPES) == 0) {
      return;
    }

    List types = schema.getTypeDefinitions();
    Iterator i = types.iterator();
    boolean bAdd = false;

    while (i.hasNext()) {

      XSDTypeDefinition defn = (XSDTypeDefinition) i.next();

      bAdd =
          (((fFilter & INCLUDE_COMPLEX_TYPES) > 0) && (defn instanceof XSDComplexTypeDefinition)
              || ((fFilter & INCLUDE_SIMPLE_TYPES) > 0)
                  && (defn instanceof XSDSimpleTypeDefinition));

      if (bAdd) {
        list.add(defn);
      }
    }
  }
  IXSDModelRoot getXSDModelRoot(XSDSchema xsdSchema, IAdaptable adaptable) {
    if (adaptable != null) {
      ISchema schema = (ISchema) adaptable.getAdapter(ISchema.class);
      xsdSchema = schema == null ? xsdSchema : schema.getComponent();
    }

    clearEmptyKeys(xsdModelRootPool.keySet());
    Resource schemaResource = xsdSchema.eResource();
    final ModelRootObjectKey key = new ModelRootObjectKey(schemaResource, xsdSchema, adaptable);
    WeakReference<IXSDModelRoot> weakXSDModelRoot = xsdModelRootPool.get(key);
    IXSDModelRoot xsdModelRoot = weakXSDModelRoot == null ? null : weakXSDModelRoot.get();
    if (xsdModelRoot == null) {
      xsdModelRoot = new XSDModelRoot(xsdSchema, adaptable);
      xsdModelRootPool.put(key, new WeakReference<IXSDModelRoot>(xsdModelRoot));
    }
    return xsdModelRoot;
  }
 // TODO THIS THREE METHODS ARE REPEATED IN XSDTAG!!!!
 private void parseElementsFrom(XSDSchema schema) {
   this.parseNamespaceContainers(schema);
   for (Iterator it = schema.getElementDeclarations().iterator(); it.hasNext(); ) {
     XSDElementDeclaration elementDeclaration = (XSDElementDeclaration) it.next();
     if (this.documentStructureDeclaration.getPublicId() == null
         || elementDeclaration
             .getURI()
             .startsWith(this.documentStructureDeclaration.getPublicId())) {
       if (!elementDeclaration.isAbstract()) {
         this.possibleRoots.add(
             new XSDTagTypeDefinition(
                 elementDeclaration, this.documentStructureDeclaration.getNamespace(), this.tags));
       }
       this.handleLeaf(elementDeclaration);
       this.handleElementDeclaration(elementDeclaration);
     }
   }
 }
Esempio n. 23
0
  /**
   * Retrieves all the root Data types defined in the schema including complex types, user-defined
   * simple types and anonymous complex types. If there's an anonymous complex type definition (from
   * a root element declaration) then we return the element declaration's anonymous type.
   *
   * @param schema
   * @return list of type definitions.
   */
  public static List<XSDTypeDefinition> getAllDataTypes(XSDSchema schema) {
    if (schema == null) {
      return Collections.emptyList();
    }

    List<XSDTypeDefinition> bos = new ArrayList<XSDTypeDefinition>();

    for (Object item : schema.getContents()) {
      if (item instanceof XSDTypeDefinition) {
        bos.add((XSDTypeDefinition) item);
      } else if (item instanceof XSDElementDeclaration) {
        XSDElementDeclaration element = (XSDElementDeclaration) item;
        if (element.getAnonymousTypeDefinition() instanceof XSDComplexTypeDefinition) {
          bos.add(element.getAnonymousTypeDefinition());
        }
      }
    }
    return bos;
  }
  public String getXSDSchemaAsString() throws Exception {

    if (xsdSchema == null) {
      return ""; //$NON-NLS-1$
    }

    Document document = xsdSchema.getDocument();
    String schema = Util.nodeToString(document);

    // FIXES a bug in the XSD library that puts nillable attributes in
    // elements which are ref
    // That is illegal according to W3C §3.3.3 / 2.2 (and Xerces)
    Pattern p =
        Pattern.compile(
            "(<([a-z]+:)?element.*?)nillable=['|\"].*?['|\"](.*?ref=.*?>)"); //$NON-NLS-1$
    schema = p.matcher(schema).replaceAll("$1 $3"); // $NON-NLS-1$

    return schema;
  }
Esempio n. 25
0
  /**
   * @param location the XSDSchema object to add this type to.
   * @param typeName the name to give the newly created type.
   * @param baseType (optional) if not null, use this type as the base type of the new type.
   * @return
   */
  public static XSDSimpleTypeDefinition createAtomicSimpleTypeDefinintion(
      XSDSchema location, String typeName, XSDSimpleTypeDefinition baseType) {
    XSDSimpleTypeDefinition std =
        (XSDSimpleTypeDefinition)
            XSDFactory.eINSTANCE.create(XSDPackage.eINSTANCE.getXSDSimpleTypeDefinition());
    std.setName(typeName);
    // defect 18444 - make sure things are wrapped in transactions
    try {
      ModelerCore.getModelEditor().addValue(location, std, location.getContents());

      if (baseType != null) {
        ModelerCore.getDatatypeManager(std).setBasetypeDefinition(std, baseType);
      } else {
        XSDSimpleTypeDefinition defaultBaseType = getDefaultBaseType();
        ModelerCore.getDatatypeManager(std).setBasetypeDefinition(std, defaultBaseType);
      } // endif
    } catch (ModelerCoreException ex) {
      ModelerXsdUiConstants.Util.log(ex);
    } // endtry

    return std;
  }
  /*
   * Analyze the schema at the given URI, traverse its imports and includes.
   * The schema information is not stored in XMLObjectInfos because it's
   * either not neccessary (schema inlined in a wsdl) or it has already
   * been stored.
   */
  private void analyzeXSD(URI uri, XSDSchema schema) {

    if (schema == null) return;

    // look at the imports and includes

    for (Iterator it = schema.getContents().iterator(); it.hasNext(); ) {

      Object content = it.next();

      if (!(content instanceof XSDSchemaDirective)) continue;

      XSDSchemaDirective xsdSchemaDirective = (XSDSchemaDirective) content;
      String xsdSchemaDirectiveLocation = xsdSchemaDirective.getSchemaLocation();

      // analyze any relative imports and includes we find
      if (xsdSchemaDirectiveLocation != null && isRelative(xsdSchemaDirectiveLocation))
        try {
          analyzeXSD(uri.resolve(uriCreate(xsdSchemaDirectiveLocation)));
        } catch (Exception e) {
          // ignore any xsd's we cannot resolve
        }
    }
  }
Esempio n. 27
0
 public static XSDSimpleTypeDefinition resolvePrimitiveTypeDefinition(
     XSDSchema schema, String typeName) {
   return schema.getSchemaForSchema().resolveSimpleTypeDefinition(typeName);
 }
  protected Resource findResourceByImport(
      final XSDSchemaDirective theImport, final List eResources) {
    Resource result = null;
    if (theImport != null && eResources != null) {

      // An XSDSchemaDirective referencing an XSDResource instance will have
      // the relative path to that resource in its location
      final String schemaLocation = theImport.getSchemaLocation();
      if (!CoreStringUtil.isEmpty(schemaLocation) && theImport.eResource() != null) {

        // Check if the path represents a logic URI that can be found
        final URI uri = URI.createURI(schemaLocation);
        result = findByURI(uri, true);
        if (result != null && eResources.contains(result)) {
          return result;
        }
        result = null;

        XSDResourceImpl eResource = (XSDResourceImpl) theImport.eResource();
        URI baseLocationURI = eResource.getURI();
        // If the base resource URI was created as a file URI then it's path is encoded so before we
        // resolve the referenced resource we need to encode it's relative path
        URI schemaLocationURI = UriHelper.makeAbsoluteUri(baseLocationURI, schemaLocation);
        // URI schemaLocationURI = (baseLocationURI.isFile() ? URI.createURI(schemaLocation, false):
        // URI.createURI(schemaLocation));
        // if (baseLocationURI.isHierarchical() && !baseLocationURI.isRelative() &&
        // schemaLocationURI.isRelative()) {
        // schemaLocationURI = schemaLocationURI.resolve(baseLocationURI);
        // }
        result = findByURI(schemaLocationURI, true);
        if (result != null && eResources.contains(result)) {
          return result;
        }
        result = null;

        // Check if the resource name matches any resource in the list
        final String name = URI.createURI(schemaLocation).lastSegment();
        final Collection results = findResourcesByName(name, true, eResources);
        if (results.size() == 1) {
          result = (Resource) results.iterator().next();

        } else if (results.size() > 1) {
          // Ensure that all referenced schemas are resolved
          getExternallyReferencedResources(eResource, true, false);

          // Match the input XSDSchemaDirective to one in the resource
          for (final Iterator i = eResource.getSchema().eContents().iterator(); i.hasNext(); ) {
            EObject eObj = (EObject) i.next();
            if (eObj instanceof XSDSchemaDirective && theImport == eObj) {
              XSDSchema resolvedSchema = ((XSDSchemaDirective) eObj).getResolvedSchema();
              if (resolvedSchema != null) {
                Resource refResource = resolvedSchema.eResource();
                if (eResources.contains(refResource)) {
                  return refResource;
                }
              }
            }
          }
        }
      }
    }
    return result;
  }
Esempio n. 29
0
 protected void afterDoAction() {
   if (!omitTrack) {
     commitDocumentToCurrent(schema.getDocument());
   }
 }
Esempio n. 30
0
 protected void beforeDoAction() {
   schema = ((ISchemaContentProvider) page.getTreeViewer().getContentProvider()).getXsdSchema();
   if (!omitTrack) {
     commitDocumentToHistory(schema.getDocument());
   }
 }