/**
   * An xpath expression may target a "client property" mapping (in xml land, an xml attribute
   * rather than a xml element).
   *
   * @throws Exception
   */
  @Test
  public void testPropertyNameWithXlinkAttribute() throws Exception {
    final String XMMLNS = "http://www.opengis.net/xmml";
    final Name typeName = new NameImpl(XMMLNS, "Borehole");

    AppSchemaDataAccess complexDs = (AppSchemaDataAccess) mappingDataStore;

    mapping = complexDs.getMappingByElement(typeName);

    NamespaceSupport namespaces = new NamespaceSupport();
    namespaces.declarePrefix("gml", GML.NAMESPACE);
    namespaces.declarePrefix("xmml", XMMLNS);
    namespaces.declarePrefix("xlink", XLINK.NAMESPACE);

    FilterFactory2 ff = new FilterFactoryImplNamespaceAware(namespaces);
    String xpathExpression = "sa:shape/geo:LineByVector/geo:origin/@xlink:href";
    PropertyName propNameExpression = ff.property(xpathExpression);

    visitor = new UnmappingFilterVisitor(mapping);

    List /* <Expression> */ unrolled = (List) propNameExpression.accept(visitor, null);
    assertNotNull(unrolled);
    assertEquals(1, unrolled.size());
    assertTrue(unrolled.get(0) instanceof Expression);
  }
Exemplo n.º 2
0
  protected void start(Element element, XSDElementDeclaration declaration) throws SAXException {
    String uri = element.getNamespaceURI();
    String local = element.getLocalName();

    String qName = element.getLocalName();

    NamespaceSupport namespaces = this.namespaces;

    // declaration == null -> gml3 envelope encoding test failing
    // declaration.getSchema() == null -> wfs 2.0 feature collection encoding test failing
    if (namespaceAware
        && (declaration == null
            || declaration.isGlobal()
            || declaration.getSchema() == null
            || declaration.getSchema().getElementFormDefault() == XSDForm.QUALIFIED_LITERAL)) {
      uri = (uri != null) ? uri : namespaces.getURI("");
      qName = namespaces.getPrefix(uri) + ":" + qName;
    } else {
      uri = "";
    }

    DOMAttributes atts = new DOMAttributes(element.getAttributes(), namespaces);
    serializer.startElement(uri, local, qName, atts);

    // write out any text
    for (int i = 0; i < element.getChildNodes().getLength(); i++) {
      Node node = (Node) element.getChildNodes().item(i);

      if (node instanceof Text) {
        char[] ch = ((Text) node).getData().toCharArray();
        serializer.characters(ch, 0, ch.length);
      }
    }

    // write out any child elements
    for (int i = 0; i < element.getChildNodes().getLength(); i++) {
      Node node = (Node) element.getChildNodes().item(i);

      if (node instanceof Element) {
        Element child = (Element) node;
        start(
            child,
            Schemas.getChildElementDeclaration(
                declaration, new QName(child.getNamespaceURI(), child.getNodeName())));
        end(child);
      }
    }

    // push a new context for children, declaring the default prefix to be the one of this
    // element
    this.namespaces.pushContext();

    if (uri != null) {
      this.namespaces.declarePrefix("", uri);
    }
  }
  /**
   * There might be multiple mappings per propery name, like <code>gml:name[1] = att1</code>, <code>
   * gml:name2 = strConcat(att2, att3)</code>, <code>gml:name[3] = "sampleValue</code>.
   *
   * <p>In the BoreHole test mapping used here, the following mappings exist for gml:name:
   *
   * <ul>
   *   <li>gml:name[1] = strConcat( strConcat(QS, strConcat("/", RT)), strConcat(strConcat("/",
   *       NUMB), strConcat("/", BSUFF)) )
   *   <li>gml:name[2] = BGS_ID
   *   <li>gml:name[3] = NAME
   *   <li>gml:name[4] = ORIGINAL_N
   * </ul>
   *
   * This means the "unrolled" filter for <code>gml:name = "SWADLINCOTE"</code> should be <code>
   * strConcat( strConcat(QS, ...) = "SWADLINCOTE"
   *          OR BGS_ID = "SWADLINCOTE"
   *          OR NAME = "SWADLINCOTE"
   *          OR ORIGINAL_N = "SWADLINCOTE"</code>
   *
   * <p>
   *
   * @throws Exception
   */
  @Test
  public void testCompareFilterMultipleMappingsPerPropertyName() throws Exception {
    final String XMMLNS = "http://www.opengis.net/xmml";
    final Name typeName = new NameImpl(XMMLNS, "Borehole");

    AppSchemaDataAccess complexDs = (AppSchemaDataAccess) mappingDataStore;
    mapping = complexDs.getMappingByElement(typeName);

    NamespaceSupport namespaces = new NamespaceSupport();
    namespaces.declarePrefix("gml", GML.NAMESPACE);
    namespaces.declarePrefix("xmml", XMMLNS);

    FilterFactory2 ff = new FilterFactoryImplNamespaceAware(namespaces);
    PropertyIsEqualTo complexFilter = ff.equals(ff.property("gml:name"), ff.literal("SWADLINCOTE"));

    visitor = new UnmappingFilterVisitor(mapping);

    Filter unrolled = (Filter) complexFilter.accept(visitor, null);
    assertNotNull(unrolled);
    assertNotSame(complexFilter, unrolled);

    assertTrue(unrolled.getClass().getName(), unrolled instanceof org.opengis.filter.Or);

    Or oredFilter = (Or) unrolled;
    List children = oredFilter.getChildren();
    assertEquals(4, children.size());

    assertTrue(children.get(0) instanceof PropertyIsEqualTo);
    assertTrue(children.get(1) instanceof PropertyIsEqualTo);
    assertTrue(children.get(2) instanceof PropertyIsEqualTo);
    assertTrue(children.get(3) instanceof PropertyIsEqualTo);

    PropertyIsEqualTo filter1 = (PropertyIsEqualTo) children.get(0);
    PropertyIsEqualTo filter2 = (PropertyIsEqualTo) children.get(1);
    PropertyIsEqualTo filter3 = (PropertyIsEqualTo) children.get(2);
    PropertyIsEqualTo filter4 = (PropertyIsEqualTo) children.get(3);

    assertTrue(filter1.getExpression1() instanceof Function);
    assertTrue(filter2.getExpression1() instanceof PropertyName);
    assertTrue(filter3.getExpression1() instanceof PropertyName);
    assertTrue(filter4.getExpression1() instanceof PropertyName);

    assertTrue(filter1.getExpression2() instanceof Literal);
    assertTrue(filter2.getExpression2() instanceof Literal);
    assertTrue(filter3.getExpression2() instanceof Literal);
    assertTrue(filter4.getExpression2() instanceof Literal);

    assertEquals("BGS_ID", ((PropertyName) filter2.getExpression1()).getPropertyName());
    assertEquals("NAME", ((PropertyName) filter3.getExpression1()).getPropertyName());
    assertEquals("ORIGINAL_N", ((PropertyName) filter4.getExpression1()).getPropertyName());
  }
  /**
   * Look up the index of an attribute by Namespace name.
   *
   * @param uri The Namespace URI, or the empty string if the name has no Namespace URI.
   * @param localName The attribute's local name.
   * @return The index of the attribute, or -1 if it does not appear in the list.
   */
  public int getIndex(String uri, String localName) {
    Vector attributes;
    int size;
    Attribute attribute;
    String string;
    int ret;

    ret = -1;

    attributes = mTag.getAttributesEx();
    if (null != attributes) {
      size = attributes.size();
      for (int i = 1; i < size; i++) {
        attribute = (Attribute) attributes.elementAt(i);
        string = attribute.getName();
        if (null != string) // not whitespace
        {
          mSupport.processName(string, mParts, true);
          if (uri.equals(mParts[0]) & localName.equalsIgnoreCase(mParts[1])) {
            ret = i;
            i = size; // exit fast
          }
        }
      }
    }

    return (ret);
  }
  /**
   * Build the SAX attributes object based upon Java's String map. This convenience method will
   * build, or add to an existing attributes object, the attributes detailed in the AttributeMap.
   *
   * @param namespaces SAX Helper class to keep track of namespaces able to determine the correct
   *     prefix for a given namespace URI.
   * @param attributes An existing SAX AttributesImpl object to add attributes too. If the value is
   *     null then a new attributes object will be created to house the attributes.
   * @param attributeMap A map of attributes and values.
   * @return
   */
  private AttributesImpl map2sax(
      Namespace elementNamespace,
      NamespaceSupport namespaces,
      AttributesImpl attributes,
      AttributeMap attributeMap) {

    if (attributes == null) attributes = new AttributesImpl();
    if (attributeMap != null) {
      // Figure out the namespace issue
      Namespace namespace = attributeMap.getNamespace();
      String URI;
      if (namespace != null) URI = namespace.URI;
      else URI = WingConstants.DRI.URI;

      String prefix = namespaces.getPrefix(URI);

      // copy each one over.
      for (String name : attributeMap.keySet()) {
        String value = attributeMap.get(name);
        if (value == null) continue;

        // If the indended namespace is the element's namespace then we
        // leave
        // off the namespace declaration because w3c say's its redundent
        // and breaks lots of xsl stuff.
        if (elementNamespace.URI.equals(URI))
          attributes.addAttribute("", name, name, "CDATA", value);
        else attributes.addAttribute(URI, name, qName(prefix, name), "CDATA", value);
      }
    }
    return attributes;
  }
Exemplo n.º 6
0
 public static boolean hasDefaultMetacardFieldForPrefixedString(
     String propertyName, NamespaceSupport namespaceSupport) {
   if (propertyName.contains(":") && !isXpathPropertyName(propertyName)) {
     String prefix = propertyName.substring(0, propertyName.indexOf(":"));
     String localName = propertyName.substring(propertyName.indexOf(":") + 1);
     if (namespaceSupport != null && namespaceSupport.getURI(prefix) != null) {
       String uri = namespaceSupport.getURI(prefix);
       QName qname = new QName(uri, localName, prefix);
       return hasDefaultMetacardFieldFor(qname);
     } else {
       return hasDefaultMetacardFieldFor(localName);
     }
   } else {
     return hasDefaultMetacardFieldFor(propertyName);
   }
 }
Exemplo n.º 7
0
 /**
  * Create the qName for the element with the given localName and namespace prefix.
  *
  * @param namespace (May be null) The namespace prefix.
  * @param localName (Required) The element's local name.
  * @return
  */
 private String qName(Namespace namespace, String localName) {
   String prefix = namespaces.getPrefix(namespace.URI);
   if (prefix == null || prefix.equals("")) {
     return localName;
   } else {
     return prefix + ":" + localName;
   }
 }
 public static String getDefaultMetacardFieldForPrefixedString(
     String propertyName, NamespaceSupport namespaceSupport) {
   String name;
   if (propertyName.contains(":")) {
     String prefix = propertyName.substring(0, propertyName.indexOf(":"));
     String localName = propertyName.substring(propertyName.indexOf(":") + 1);
     if (namespaceSupport != null && namespaceSupport.getURI(prefix) != null) {
       String uri = namespaceSupport.getURI(prefix);
       QName qname = new QName(uri, localName, prefix);
       name = getDefaultMetacardFieldFor(qname);
     } else {
       name = getDefaultMetacardFieldFor(localName);
     }
   } else {
     name = getDefaultMetacardFieldFor(propertyName);
   }
   return name;
 }
 /**
  * Send the SAX events to start this element.
  *
  * @param contentHandler (Required) The registered contentHandler where SAX events should be
  *     routed too.
  * @param namespaces (Required) SAX Helper class to keep track of namespaces able to determine the
  *     correct prefix for a given namespace URI.
  * @param namespace (Required) The namespace of this element.
  * @param name (Required) The local name of this element.
  * @param attributes (May be null) Attributes for this element
  */
 protected void startElement(
     ContentHandler contentHandler,
     NamespaceSupport namespaces,
     Namespace namespace,
     String name,
     AttributeMap attributes)
     throws SAXException {
   String prefix = namespaces.getPrefix(namespace.URI);
   contentHandler.startElement(
       namespace.URI, name, qName(prefix, name), map2sax(namespace, namespaces, attributes));
 }
Exemplo n.º 10
0
  /**
   * Copy the namespace declarations from the NamespaceSupport object. Take care to call
   * resolveInheritedNamespaceDecls. after all namespace declarations have been added.
   *
   * @param nsSupport non-null reference to NamespaceSupport from the ContentHandler.
   * @param excludeXSLDecl true if XSLT namespaces should be ignored.
   * @throws TransformerException
   */
  public void setPrefixes(NamespaceSupport nsSupport, boolean excludeXSLDecl)
      throws TransformerException {

    Enumeration decls = nsSupport.getDeclaredPrefixes();

    while (decls.hasMoreElements()) {
      String prefix = (String) decls.nextElement();

      if (null == m_declaredPrefixes) m_declaredPrefixes = new Vector();

      String uri = nsSupport.getURI(prefix);

      if (excludeXSLDecl && uri.equals(Constants.S_XSLNAMESPACEURL)) continue;

      // System.out.println("setPrefixes - "+prefix+", "+uri);
      XMLNSDecl decl = new XMLNSDecl(prefix, uri, false);

      m_declaredPrefixes.addElement(decl);
    }
  }
Exemplo n.º 11
0
    public String getQName(int index) {
      Node n = atts.item(index);

      if (namespaces != null) {
        String uri = n.getNamespaceURI();
        String prefix = (uri != null) ? namespaces.getPrefix(uri) : null;

        if (prefix != null) {
          return prefix + ":" + n.getLocalName();
        }
      }

      return n.getLocalName();
    }
Exemplo n.º 12
0
  protected void end(Element element) throws SAXException {
    // push off last context
    namespaces.popContext();

    String uri = element.getNamespaceURI();
    String local = element.getLocalName();

    String qName = element.getLocalName();

    if ((element.getPrefix() != null) && !"".equals(element.getPrefix())) {
      qName = element.getPrefix() + ":" + qName;
    }

    serializer.endElement(uri, local, qName);
  }
Exemplo n.º 13
0
  /**
   * End of an element.
   *
   * @param uri namespace of the element.
   * @param localName local name of the element.
   * @param qName qualified name of the element.
   * @throws SAXException passed through.
   */
  @Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    if (allowElements) {
      // check if we are past the minimum level requirements
      if (minimumElementLevel < currentElementLevel) {
        if (defaultURI != null && (uri == null || "".equals(uri))) {
          // No namespace provided, use the default namespace.
          String prefix = namespaces.getPrefix(defaultURI);

          if (!(prefix == null || "".equals(prefix))) {
            qName = prefix + ":" + localName;
          }

          contentHandler.endElement(defaultURI, localName, qName);
        } else {
          // Let the event pass through unmodified.
          contentHandler.endElement(uri, localName, localName);
        }
      }
      currentElementLevel--;
    }
  }
Exemplo n.º 14
0
  public void encode(Object object, QName name, ContentHandler handler)
      throws IOException, SAXException {

    // maintain a stack of (encoding,element declaration pairs)
    Stack encoded = null;

    try {
      serializer = handler;

      if (!inline) {
        serializer.startDocument();
      }

      if (namespaceAware) {
        // write out all the namespace prefix value mappings
        for (Enumeration e = namespaces.getPrefixes(); e.hasMoreElements(); ) {
          String prefix = (String) e.nextElement();
          String uri = namespaces.getURI(prefix);

          if ("xml".equals(prefix)) {
            continue;
          }
          serializer.startPrefixMapping(prefix, uri);
        }
        for (Iterator itr = schema.getQNamePrefixToNamespaceMap().entrySet().iterator();
            itr.hasNext(); ) {
          Map.Entry entry = (Map.Entry) itr.next();
          String pre = (String) entry.getKey();
          String ns = (String) entry.getValue();

          if (XSDUtil.SCHEMA_FOR_SCHEMA_URI_2001.equals(ns)) {
            continue;
          }

          serializer.startPrefixMapping(pre, ns);
          serializer.endPrefixMapping(pre);

          namespaces.declarePrefix((pre != null) ? pre : "", ns);
        }

        // ensure a default namespace prefix set
        if (namespaces.getURI("") == null) {
          namespaces.declarePrefix("", schema.getTargetNamespace());
        }
      }

      // create the document
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();

      try {
        doc = docFactory.newDocumentBuilder().newDocument();
      } catch (ParserConfigurationException e) {
        new IOException().initCause(e);
      }

      encoded = new Stack();

      // add the first entry
      XSDElementDeclaration root = index.getElementDeclaration(name);

      if (root == null) {
        // check for context hint, this is only used when running the encoder
        // in test mode
        QName typeDefintion =
            (QName) context.getComponentInstance("http://geotools.org/typeDefinition");

        if (typeDefintion != null) {
          XSDTypeDefinition type = index.getTypeDefinition(typeDefintion);

          if (type == null) {
            throw new NullPointerException();
          }

          // create a mock element declaration
          root = XSDFactory.eINSTANCE.createXSDElementDeclaration();
          root.setName(name.getLocalPart());
          root.setTargetNamespace(name.getNamespaceURI());
          root.setTypeDefinition(type);
        }
      }

      if (root == null) {
        String msg = "Could not find element declaration for:" + name;
        throw new IllegalArgumentException(msg);
      }

      encoded.add(new EncodingEntry(object, root, null));

      while (!encoded.isEmpty()) {
        EncodingEntry entry = (EncodingEntry) encoded.peek();

        if (entry.encoding != null) {
          // element has been started, get the next child
          if (!entry.children.isEmpty()) {
            Object[] child = (Object[]) entry.children.get(0);
            XSDElementDeclaration element = (XSDElementDeclaration) child[0];
            Iterator itr = (Iterator) child[1];

            if (itr.hasNext()) {
              Object next = itr.next();
              if (next == null) {
                logger.warning("Iterator returned null for " + element.getName());
              }

              // here we check for instanceof EncoderDelegate
              if (next instanceof EncoderDelegate) {
                // do not add entry to the stack, just delegate to encode
                try {
                  ((EncoderDelegate) next).encode(handler);
                } catch (Exception e) {
                  throw new RuntimeException(e);
                }
              } else {
                // add the next object to be encoded to the stack
                encoded.push(new EncodingEntry(next, element, entry));
              }
            } else {
              // iterator done, close it
              Object source = child[2];
              closeIterator(itr, source);

              // this child is done, remove from child list
              entry.children.remove(0);
            }
          } else {
            // no more children, finish the element
            end(entry.encoding);
            encoded.pop();

            // clean up the entry
            entry.object = null;
            entry.element = null;
            entry.encoding = null;
            entry.children = null;
            entry.parent = null;
          }
        } else {
          // start the encoding of the entry

          // first make sure the element is not abstract
          if (entry.element.isAbstract()) {
            // look for a non abstract substitute - substitution groups are subject to
            // changes over time, so we make a copy to avoid being hit with a
            // ConcurrentModificationException
            List sub = safeCopy(entry.element.getSubstitutionGroup());

            if (sub.size() > 0) {
              // match up by type
              List matches = new ArrayList();

              for (Iterator s = sub.iterator(); s.hasNext(); ) {
                XSDElementDeclaration e = (XSDElementDeclaration) s.next();

                if (e == null || e.equals(entry.element)) {
                  continue;
                }

                if (e.getName() == null) {
                  continue;
                }

                // look up hte binding
                Binding binding =
                    bindingLoader.loadBinding(
                        new QName(e.getTargetNamespace(), e.getName()), context);

                if (binding == null) {
                  // try the type
                  XSDTypeDefinition type = e.getType();

                  if (type == null || type.getName() == null) {
                    continue;
                  }

                  binding =
                      bindingLoader.loadBinding(
                          new QName(type.getTargetNamespace(), type.getName()), context);
                }

                if (binding == null) {
                  continue;
                }

                if (binding.getType() == null) {
                  logger.warning("Binding: " + binding.getTarget() + " returns null type.");
                  continue;
                }

                // match up the type
                if (binding.getType().isAssignableFrom(entry.object.getClass())) {
                  // we have a match, store as an (element,binding) tuple
                  matches.add(new Object[] {e, binding});
                }
              }

              // if one, we are gold
              if (matches.size() == 1) {
                entry.element = (XSDElementDeclaration) ((Object[]) matches.get(0))[0];
              }
              // if multiple we have a problem
              else if (matches.size() > 0) {
                if (logger.isLoggable(Level.FINE)) {
                  StringBuffer msg = new StringBuffer("Found multiple non-abstract bindings for ");
                  msg.append(entry.element.getName()).append(": ");

                  for (Iterator m = matches.iterator(); m.hasNext(); ) {
                    msg.append(m.next().getClass().getName());
                    msg.append(", ");
                  }

                  logger.fine(msg.toString());
                }

                // try sorting by the type of the binding
                Collections.sort(
                    matches,
                    new Comparator() {
                      public int compare(Object o1, Object o2) {
                        Object[] match1 = (Object[]) o1;
                        Object[] match2 = (Object[]) o2;

                        Binding b1 = (Binding) match1[1];
                        Binding b2 = (Binding) match2[1];

                        if (b1.getType() != b2.getType()) {
                          if (b2.getType().isAssignableFrom(b1.getType())) {
                            return -1;
                          }

                          if (b1.getType().isAssignableFrom(b2.getType())) {
                            return 1;
                          }
                        }

                        // use binding comparability
                        if (b1 instanceof Comparable) {
                          return ((Comparable) b1).compareTo(b2);
                        }

                        if (b2 instanceof Comparable) {
                          return -1 * ((Comparable) b2).compareTo(b1);
                        }

                        return 0;
                      }
                    });
              }

              if (matches.size() > 0) {
                entry.element = (XSDElementDeclaration) ((Object[]) matches.get(0))[0];
              }

              // if zero, just use the abstract element
            }
          }

          if (entry.element.isAbstract()) {
            logger.fine(entry.element.getName() + " is abstract");
          }

          entry.encoding =
              entry.parent != null
                  ? (Element) encode(entry.object, entry.element, entry.parent.element.getType())
                  : (Element) encode(entry.object, entry.element);

          // add any more attributes
          List attributes = index.getAttributes(entry.element);

          for (Iterator itr = attributes.iterator(); itr.hasNext(); ) {
            XSDAttributeDeclaration attribute = (XSDAttributeDeclaration) itr.next();

            // do not encode the attribute if it has already been
            // encoded by the parent
            String ns = attribute.getTargetNamespace();
            String local = attribute.getName();

            if ((entry.encoding.getAttributeNS(ns, local) != null)
                && !"".equals(entry.encoding.getAttributeNS(ns, local))) {
              continue;
            }

            // get the object(s) for this attribute
            GetPropertyExecutor executor = new GetPropertyExecutor(entry.object, attribute);

            BindingVisitorDispatch.walk(object, bindingWalker, entry.element, executor, context);

            if (executor.getChildObject() != null) {
              // encode the attribute
              Attr attr = (Attr) encode(executor.getChildObject(), attribute);

              if (attr != null) {
                entry.encoding.setAttributeNodeNS(attr);
              }
            }
          }

          // write out the leading edge of the element
          if (schemaLocations != null) {
            // root element, add schema locations if set
            if (!schemaLocations.isEmpty()) {
              // declare the schema instance mapping
              serializer.startPrefixMapping("xsi", XSDUtil.SCHEMA_INSTANCE_URI_2001);
              serializer.endPrefixMapping("xsi");
              namespaces.declarePrefix("xsi", XSDUtil.SCHEMA_INSTANCE_URI_2001);

              StringBuffer schemaLocation = new StringBuffer();

              for (Iterator e = schemaLocations.entrySet().iterator(); e.hasNext(); ) {
                Map.Entry tuple = (Map.Entry) e.next();
                String namespaceURI = (String) tuple.getKey();
                String location = (String) tuple.getValue();

                schemaLocation.append(namespaceURI + " " + location);

                if (e.hasNext()) {
                  schemaLocation.append(" ");
                }
              }

              entry.encoding.setAttributeNS(
                  XSDUtil.SCHEMA_INSTANCE_URI_2001,
                  "xsi:schemaLocation",
                  schemaLocation.toString());
            }

            schemaLocations = null;
          }

          start(entry.encoding, entry.element);

          // TODO: this method of getting at properties wont maintain order very well, need
          // to come up with a better system that is capable of hanlding feature types
          for (Iterator pe = propertyExtractors.iterator(); pe.hasNext(); ) {
            PropertyExtractor propertyExtractor = (PropertyExtractor) pe.next();

            if (propertyExtractor.canHandle(entry.object)) {
              List extracted = propertyExtractor.properties(entry.object, entry.element);
              O:
              for (Iterator e = extracted.iterator(); e.hasNext(); ) {
                Object[] tuple = (Object[]) e.next();
                XSDParticle particle = (XSDParticle) tuple[0];
                XSDElementDeclaration child = (XSDElementDeclaration) particle.getContent();

                // check for a comment
                if ((child != null)
                    && (COMMENT.getNamespaceURI().equals(child.getTargetNamespace()))
                    && COMMENT.getLocalPart().equals(child.getName())) {
                  comment(child.getElement());

                  continue;
                }

                if (child.isElementDeclarationReference()) {
                  child = child.getResolvedElementDeclaration();
                }

                // do not encode the element if the parent has already
                // been encoded by the parent
                String ns = child.getTargetNamespace();
                String local = child.getName();

                for (int i = 0; i < entry.encoding.getChildNodes().getLength(); i++) {
                  Node node = entry.encoding.getChildNodes().item(i);

                  if (node instanceof Element) {
                    if (ns != null) {
                      if (ns.equals(node.getNamespaceURI()) && local.equals(node.getLocalName())) {
                        continue O;
                      }
                    } else {
                      if (local.equals(node.getLocalName())) {
                        continue O;
                      }
                    }
                  }
                }

                Object obj = tuple[1];

                if (obj == null) {
                  if (particle.getMinOccurs() == 0) {
                    // cool
                  } else {
                    // log an error
                    logger.fine("Property " + ns + ":" + local + " not found but minoccurs > 0 ");
                  }

                  // skip this regardless
                  continue;
                }

                // figure out the maximum number of occurences
                int maxOccurs = 1;

                if (particle.isSetMaxOccurs()) {
                  maxOccurs = particle.getMaxOccurs();
                } else {
                  // look the containing group
                  if (particle.eContainer() instanceof XSDModelGroup) {
                    XSDModelGroup group = (XSDModelGroup) particle.eContainer();

                    if (group.eContainer() instanceof XSDParticle) {
                      XSDParticle cParticle = (XSDParticle) group.eContainer();

                      if (cParticle.isSetMaxOccurs()) {
                        maxOccurs = cParticle.getMaxOccurs();
                      }
                    }
                  }
                }

                if ((maxOccurs == -1) || (maxOccurs > 1)) {
                  // may have a collection or array, unwrap it
                  Iterator iterator = null;

                  if (obj instanceof Iterator) {
                    iterator = (Iterator) obj;
                  } else if (obj.getClass().isArray()) {
                    Object[] array = (Object[]) obj;
                    iterator = Arrays.asList(array).iterator();
                  } else if (obj instanceof Collection) {
                    Collection collection = (Collection) obj;
                    iterator = collection.iterator();
                  } else if (obj instanceof FeatureCollection) {
                    FeatureCollection collection = (FeatureCollection) obj;
                    iterator = collection.iterator();
                  } else {
                    iterator = new SingleIterator(obj);
                  }

                  entry.children.add(new Object[] {child, iterator, obj});
                } else {
                  // only one, just add the object
                  entry.children.add(new Object[] {child, new SingleIterator(obj), obj});
                }
              }
            }
          }
        }
      }

      if (!inline) {
        serializer.endDocument();
      }

    } finally {
      // cleanup
      index.destroy();

      // close any iterators still present in the stack, this will only occur in an exception
      // case
      if (encoded != null) {
        while (!encoded.isEmpty()) {
          EncodingEntry entry = (EncodingEntry) encoded.pop();
          if (!entry.children.isEmpty()) {
            Object[] child = (Object[]) entry.children.get(0);
            Iterator itr = (Iterator) child[1];
            try {
              closeIterator(itr, child[2]);
            } catch (Exception e) {
              // ignore, we are already in an error case.
            }
          }
        }
      }
      // TODO: there are probably other refences to elements of XSDScheam objects, we should
      // kill them too
    }
  }
 @Override
 public void registerNamespaces(NamespaceSupport namespaces) {
   namespaces.declarePrefix("inspire_vs", VS_NAMESPACE);
   namespaces.declarePrefix("inspire_common", COMMON_NAMESPACE);
 }
Exemplo n.º 16
0
  /**
   * Render the complete METS document.
   *
   * @param context session context.
   * @param contentHandler XML content handler.
   * @param lexicalHandler XML lexical handler.
   * @throws org.dspace.app.xmlui.wing.WingException passed through.
   * @throws org.xml.sax.SAXException passed through.
   * @throws org.dspace.content.crosswalk.CrosswalkException passed through.
   * @throws java.io.IOException passed through.
   * @throws java.sql.SQLException passed through.
   */
  public final void renderMETS(
      Context context, ContentHandler contentHandler, LexicalHandler lexicalHandler)
      throws WingException, SAXException, CrosswalkException, IOException, SQLException {
    this.contentHandler = contentHandler;
    this.lexicalHandler = lexicalHandler;
    this.namespaces = new NamespaceSupport();

    // Declare our namespaces
    namespaces.pushContext();
    namespaces.declarePrefix("mets", METS.URI);
    namespaces.declarePrefix("xlink", XLINK.URI);
    namespaces.declarePrefix("xsi", XSI.URI);
    namespaces.declarePrefix("dim", DIM.URI);
    contentHandler.startPrefixMapping("mets", METS.URI);
    contentHandler.startPrefixMapping("xlink", XLINK.URI);
    contentHandler.startPrefixMapping("xsi", XSI.URI);
    contentHandler.startPrefixMapping("dim", DIM.URI);

    // Send the METS element
    AttributeMap attributes = new AttributeMap();
    attributes.put("ID", getMETSID());
    attributes.put("PROFILE", getMETSProfile());
    attributes.put("LABEL", getMETSLabel());
    String objid = getMETSOBJID();
    if (objid != null) {
      attributes.put("OBJID", objid);
    }

    // Include the link for editing the item
    objid = getMETSOBJEDIT();
    if (objid != null) {
      attributes.put("OBJEDIT", objid);
    }

    startElement(METS, "METS", attributes);

    // If the user requested no specific sections then render them all.
    boolean all = (sections.isEmpty());

    if (all || sections.contains("metsHdr")) {
      renderHeader();
    }
    if (all || sections.contains("dmdSec")) {
      renderDescriptiveSection();
    }
    if (all || sections.contains("amdSec")) {
      renderAdministrativeSection();
    }
    if (all || sections.contains("fileSec")) {
      renderFileSection(context);
    }
    if (all || sections.contains("structMap")) {
      renderStructureMap();
    }
    if (all || sections.contains("structLink")) {
      renderStructuralLink();
    }
    if (all || sections.contains("behaviorSec")) {
      renderBehavioralSection();
    }

    // FIXME: this is not a met's section, it should be removed
    if (all || sections.contains("extraSec")) {
      renderExtraSections();
    }

    endElement(METS, "METS");
    contentHandler.endPrefixMapping("mets");
    contentHandler.endPrefixMapping("xlink");
    contentHandler.endPrefixMapping("dim");
    namespaces.popContext();
  }
Exemplo n.º 17
0
 /**
  * Look up an attribute's local name by index.
  *
  * @param index The attribute index (zero-based).
  * @return The local name, or the empty string if Namespace processing is not being performed, or
  *     null if the index is out of range.
  * @see #getLength
  */
 public String getLocalName(int index) {
   mSupport.processName(getQName(index), mParts, true);
   return (mParts[1]);
 }
Exemplo n.º 18
0
    @Override
    public void encode(Object o) throws IllegalArgumentException {
      // register namespaces provided by extended capabilities
      NamespaceSupport namespaces = getNamespaceSupport();
      namespaces.declarePrefix("wcscrs", "http://www.opengis.net/wcs/service-extension/crs/1.0");
      namespaces.declarePrefix(
          "int", "http://www.opengis.net/WCS_service-extension_interpolation/1.0");
      namespaces.declarePrefix("gml", "http://www.opengis.net/gml/3.2");
      namespaces.declarePrefix("gmlcov", "http://www.opengis.net/gmlcov/1.0");
      namespaces.declarePrefix("swe", "http://www.opengis.net/swe/2.0");
      namespaces.declarePrefix("xlink", "http://www.w3.org/1999/xlink");
      namespaces.declarePrefix("xsi", "http://www.w3.org/2001/XMLSchema-instance");

      for (WCS20CoverageMetadataProvider cp : extensions) {
        cp.registerNamespaces(namespaces);
      }

      // is this a GridCoverage?
      if (!(o instanceof GridCoverage2D)) {
        throw new IllegalArgumentException(
            "Provided object is not a GridCoverage2D:"
                + (o != null ? o.getClass().toString() : "null"));
      }
      final GridCoverage2D gc2d = (GridCoverage2D) o;
      // we are going to use this name as an ID
      final String gcName = gc2d.getName().toString(Locale.getDefault());

      // get the crs and look for an EPSG code
      final CoordinateReferenceSystem crs = gc2d.getCoordinateReferenceSystem2D();
      List<String> axesNames =
          GMLTransformer.this.envelopeDimensionsMapper.getAxesNames(gc2d.getEnvelope2D(), true);

      // lookup EPSG code
      Integer EPSGCode = null;
      try {
        EPSGCode = CRS.lookupEpsgCode(crs, false);
      } catch (FactoryException e) {
        throw new IllegalStateException("Unable to lookup epsg code for this CRS:" + crs, e);
      }
      if (EPSGCode == null) {
        throw new IllegalStateException("Unable to lookup epsg code for this CRS:" + crs);
      }
      final String srsName = GetCoverage.SRS_STARTER + EPSGCode;
      // handle axes swap for geographic crs
      final boolean axisSwap = CRS.getAxisOrder(crs).equals(AxisOrder.EAST_NORTH);

      final AttributesImpl attributes = new AttributesImpl();
      helper.registerNamespaces(getNamespaceSupport(), attributes);

      // using Name as the ID
      attributes.addAttribute(
          "", "gml:id", "gml:id", "", gc2d.getName().toString(Locale.getDefault()));
      start("gml:RectifiedGridCoverage", attributes);

      // handle domain
      final StringBuilder builder = new StringBuilder();
      for (String axisName : axesNames) {
        builder.append(axisName).append(" ");
      }
      String axesLabel = builder.substring(0, builder.length() - 1);
      try {
        GeneralEnvelope envelope = new GeneralEnvelope(gc2d.getEnvelope());
        handleBoundedBy(envelope, axisSwap, srsName, axesLabel, null);
      } catch (IOException ex) {
        throw new WCS20Exception(ex);
      }

      // handle domain
      builder.setLength(0);
      axesNames =
          GMLTransformer.this.envelopeDimensionsMapper.getAxesNames(gc2d.getEnvelope2D(), false);
      for (String axisName : axesNames) {
        builder.append(axisName).append(" ");
      }
      axesLabel = builder.substring(0, builder.length() - 1);
      handleDomainSet(gc2d.getGridGeometry(), gc2d.getDimension(), gcName, srsName, axisSwap);

      // handle rangetype
      handleRangeType(gc2d);

      // handle coverage function
      final GridEnvelope2D ge2D = gc2d.getGridGeometry().getGridRange2D();
      handleCoverageFunction(ge2D, axisSwap);

      // handle range
      handleRange(gc2d);

      // handle metadata OPTIONAL
      try {
        handleMetadata(null, null);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      end("gml:RectifiedGridCoverage");
    }
Exemplo n.º 19
0
 /**
  * Look up the index of an attribute by XML qualified (prefixed) name.
  *
  * @param qName The qualified (prefixed) name.
  * @return The index of the attribute, or -1 if it does not appear in the list.
  */
 public int getIndex(String qName) {
   mSupport.processName(qName, mParts, true);
   return (getIndex(mParts[0], mParts[1]));
 }
Exemplo n.º 20
0
 /**
  * Look up an attribute's value by XML qualified (prefixed) name.
  *
  * <p>See {@link #getValue(int) getValue(int)} for a description of the possible values.
  *
  * @param qName The XML qualified name.
  * @return The attribute value as a string, or null if the attribute is not in the list or if
  *     qualified names are not available.
  */
 public String getValue(String qName) {
   mSupport.processName(qName, mParts, true);
   return (getValue(mParts[0], mParts[1]));
 }
  public void startDocument() throws SAXException {
    super.startDocument();

    nsSupport.reset();
    enabledExtensions.clear();
  }
 public void startPrefixMapping(String prefix, String uri) throws SAXException {
   super.startPrefixMapping(prefix, uri);
   nsSupport.pushContext();
   nsSupport.declarePrefix(prefix, uri);
 }
 /**
  * Send the SAX events to end this element.
  *
  * @param contentHandler (Required) The registered contentHandler where SAX events should be
  *     routed too.
  * @param namespaces (Required) SAX Helper class to keep track of namespaces able to determine the
  *     correct prefix for a given namespace URI.
  * @param namespace (Required) The namespace of this element.
  * @param name (Required) The local name of this element.
  */
 protected void endElement(
     ContentHandler contentHandler, NamespaceSupport namespaces, Namespace namespace, String name)
     throws SAXException {
   String prefix = namespaces.getPrefix(namespace.URI);
   contentHandler.endElement(namespace.URI, name, qName(prefix, name));
 }
 public void endPrefixMapping(String prefix) throws SAXException {
   super.endPrefixMapping(prefix);
   nsSupport.popContext();
 }
Exemplo n.º 25
0
  static {
    // prepare the common namespace support
    NAMESPACES = new NamespaceSupport();
    NAMESPACES.declarePrefix("csw", CSW.NAMESPACE);
    NAMESPACES.declarePrefix("rim", "urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0");
    NAMESPACES.declarePrefix("dc", DC.NAMESPACE);
    NAMESPACES.declarePrefix("dct", DCT.NAMESPACE);
    NAMESPACES.declarePrefix("ows", OWS.NAMESPACE);
    NAMESPACES.declarePrefix("ogc", OGC.NAMESPACE);

    // prepare the CSW record related types
    FeatureTypeFactory typeFactory = new FeatureTypeFactoryImpl();
    TypeBuilder builder = new TypeBuilder(typeFactory);

    // create the SimpleLiteral type
    builder.setNamespaceURI(DC.SimpleLiteral.getNamespaceURI());
    builder.name("scheme");
    builder.bind(URI.class);
    AttributeType schemeType = builder.attribute();
    builder.setNamespaceURI(DC.SimpleLiteral.getNamespaceURI());
    builder.name("value");
    builder.bind(Object.class);
    AttributeType valueType = builder.attribute();
    builder.setNillable(true);
    builder.addAttribute("scheme", schemeType);
    builder.addAttribute("value", valueType);
    builder.setName("SimpleLiteral");
    SIMPLE_LITERAL = builder.complex();

    builder.setNamespaceURI(OWS.NAMESPACE);
    builder.setName("BoundingBoxType");
    builder.setBinding(MultiPolygon.class);
    builder.crs(DEFAULT_CRS);
    AttributeType bboxType = builder.geometry();

    EmfComplexFeatureReader reader = EmfComplexFeatureReader.newInstance();

    SchemaIndex index = null;
    try {
      index = reader.parse(new URL("http://schemas.opengis.net/csw/2.0.2/record.xsd"));
    } catch (IOException e) {
      // this is fatal
      throw new RuntimeException("Failed to parse CSW Record Schemas", e);
    }

    FeatureTypeRegistry featureTypeRegistry =
        new FeatureTypeRegistry(
            NAMESPACES, typeFactory, new RecordFeatureTypeRegistryHelper("RecordType"));

    featureTypeRegistry.register(SIMPLE_LITERAL);

    featureTypeRegistry.register(bboxType);

    featureTypeRegistry.addSchemas(index);

    RECORD_TYPE =
        (FeatureType)
            featureTypeRegistry.getAttributeType(new NameImpl(CSW.NAMESPACE, "RecordType"));

    RECORD_DESCRIPTOR =
        featureTypeRegistry.getDescriptor(new NameImpl(CSW.NAMESPACE, "Record"), null);

    RECORD_BBOX_DESCRIPTOR = (AttributeDescriptor) RECORD_TYPE.getDescriptor(RECORD_BBOX_NAME);
    DC_ELEMENT = (AttributeDescriptor) RECORD_TYPE.getDescriptor(DC_ELEMENT_NAME);

    // ---

    // setup the list of names for brief and summary records
    BRIEF_ELEMENTS =
        createNameList(NAMESPACES, "dc:identifier", "dc:title", "dc:type", "ows:BoundingBox");
    SUMMARY_ELEMENTS =
        createNameList(
            NAMESPACES,
            "dc:identifier",
            "dc:title",
            "dc:type",
            "dc:subject",
            "dc:format",
            "dc:relation",
            "dct:modified",
            "dct:abstract",
            "dct:spatial",
            "ows:BoundingBox");

    // create the xpath extender that fill adapt dc:title to dc:title/dc:value
    PATH_EXTENDER = new CRSRecordProjectyPathAdapter(NAMESPACES);
    // qualified the xpath in the filters
    NSS_QUALIFIER = new NamespaceQualifier(NAMESPACES);
    // applies the default CRS to geometry filters coming from the outside
    CRS_DEFAULTER = new DefaultCRSFilterVisitor(FF, DEFAULT_CRS);
    // transforms geometry filters into the internal representation
    CRS_REPROJECTOR = new ReprojectingFilterVisitor(FF, RECORD_TYPE);

    // build queriables list
    QUERIABLES =
        createNameList(
            NAMESPACES,
            "dc:contributor",
            "dc:source",
            "dc:language",
            "dc:title",
            "dc:subject",
            "dc:creator",
            "dc:type",
            "ows:BoundingBox",
            "dct:modified",
            "dct:abstract",
            "dc:relation",
            "dc:date",
            "dc:identifier",
            "dc:publisher",
            "dc:format",
            "csw:AnyText",
            "dc:rights");
  }