コード例 #1
0
  public void writePayloadTo(XMLStreamWriter writer) throws XMLStreamException {
    if (payloadLocalName == null) {
      return;
    } // no body
    assert unconsumed();
    XMLStreamReaderToXMLStreamWriter conv = new XMLStreamReaderToXMLStreamWriter();
    while (reader.getEventType() != XMLStreamConstants.END_DOCUMENT) {
      String name = reader.getLocalName();
      String nsUri = reader.getNamespaceURI();

      // after previous conv.bridge() call the cursor will be at
      // END_ELEMENT. Check if its not soapenv:Body then move to next
      // ELEMENT
      if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
        if (!name.equals("Body") || !nsUri.equals(soapVersion.nsUri)) {
          XMLStreamReaderUtil.nextElementContent(reader);
          if (reader.getEventType() == XMLStreamConstants.END_DOCUMENT) {
            break;
          }
          name = reader.getLocalName();
          nsUri = reader.getNamespaceURI();
        }
      }
      if (name.equals("Body") && nsUri.equals(soapVersion.nsUri)
          || (reader.getEventType() == XMLStreamConstants.END_DOCUMENT)) {
        break;
      }
      conv.bridge(reader, writer);
    }
    reader.close();
    XMLStreamReaderFactory.recycle(reader);
  }
コード例 #2
0
  @SuppressWarnings("unchecked")
  protected ExtensionElement parseExtensionElement(XMLStreamReader xtr) throws Exception {
    ExtensionElement extensionElement = new ExtensionElement();
    extensionElement.setName(xtr.getLocalName());
    if (StringUtils.isNotEmpty(xtr.getNamespaceURI())) {
      extensionElement.setNamespace(xtr.getNamespaceURI());
    }
    if (StringUtils.isNotEmpty(xtr.getPrefix())) {
      extensionElement.setNamespacePrefix(xtr.getPrefix());
    }

    BpmnXMLUtil.addCustomAttributes(xtr, extensionElement, defaultElementAttributes);

    boolean readyWithExtensionElement = false;
    while (readyWithExtensionElement == false && xtr.hasNext()) {
      xtr.next();
      if (xtr.isCharacters()) {
        if (StringUtils.isNotEmpty(xtr.getText().trim())) {
          extensionElement.setElementText(xtr.getText().trim());
        }
      } else if (xtr.isStartElement()) {
        ExtensionElement childExtensionElement = parseExtensionElement(xtr);
        extensionElement.addChildElement(childExtensionElement);
      } else if (xtr.isEndElement()
          && extensionElement.getName().equalsIgnoreCase(xtr.getLocalName())) {
        readyWithExtensionElement = true;
      }
    }
    return extensionElement;
  }
コード例 #3
0
  public void testDOMSource() throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();

    InputSource source = new InputSource(new StringReader(xml));
    Document doc = builder.parse(source);

    // Fails when using DOMWrappingReader
    XMLStreamReader reader = getInputFactory().createXMLStreamReader(new DOMSource(doc));

    reader.next(); // root
    assertEquals(0, reader.getAttributeCount());
    assertEquals(1, reader.getNamespaceCount());
    assertEquals("http://testnamespace/", reader.getNamespaceURI());
    assertEquals("ns2", reader.getPrefix());
    assertEquals("root", reader.getLocalName());

    reader.next(); // arg0
    reader.next(); // obj

    assertEquals("obj", reader.getLocalName());
    assertEquals(
        "ns2:mycomplextype",
        reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"));
    assertEquals("http://testnamespace/", reader.getNamespaceURI("ns2"));
    assertEquals("http://testnamespace/", reader.getNamespaceContext().getNamespaceURI("ns2"));

    assertEquals("ns2", reader.getNamespaceContext().getPrefix("http://testnamespace/"));
  }
コード例 #4
0
  public void writePayloadTo(
      ContentHandler contentHandler, ErrorHandler errorHandler, boolean fragment)
      throws SAXException {
    assert unconsumed();
    try {
      if (payloadLocalName == null) {
        return;
      } // no body

      XMLStreamReaderToContentHandler conv =
          new XMLStreamReaderToContentHandler(reader, contentHandler, true, fragment);

      while (reader.getEventType() != XMLStreamConstants.END_DOCUMENT) {
        String name = reader.getLocalName();
        String nsUri = reader.getNamespaceURI();

        // after previous conv.bridge() call the cursor will be at
        // END_ELEMENT. Check if its not soapenv:Body then move to next
        // ELEMENT
        if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
          if (!name.equals("Body") || !nsUri.equals(soapVersion.nsUri)) {
            XMLStreamReaderUtil.nextElementContent(reader);
            if (reader.getEventType() == XMLStreamConstants.END_DOCUMENT) {
              break;
            }
            name = reader.getLocalName();
            nsUri = reader.getNamespaceURI();
          }
        }
        if (name.equals("Body") && nsUri.equals(soapVersion.nsUri)
            || (reader.getEventType() == XMLStreamConstants.END_DOCUMENT)) {
          break;
        }

        conv.bridge();
      }
      reader.close();
      XMLStreamReaderFactory.recycle(reader);
    } catch (XMLStreamException e) {
      Location loc = e.getLocation();
      if (loc == null) {
        loc = DummyLocation.INSTANCE;
      }

      SAXParseException x =
          new SAXParseException(
              e.getMessage(),
              loc.getPublicId(),
              loc.getSystemId(),
              loc.getLineNumber(),
              loc.getColumnNumber(),
              e);
      errorHandler.error(x);
    }
  }
コード例 #5
0
ファイル: StaxMateTestBase.java プロジェクト: tblong/StaxMate
 protected void assertElem(XMLStreamReader sr, String expURI, String expLN)
     throws XMLStreamException {
   assertEquals(expLN, sr.getLocalName());
   String actURI = sr.getNamespaceURI();
   if (expURI == null || expURI.length() == 0) {
     if (actURI != null && actURI.length() > 0) {
       fail("Expected no namespace, got URI '" + actURI + "'");
     }
   } else {
     assertEquals(expURI, sr.getNamespaceURI());
   }
 }
コード例 #6
0
 public String getNamespaceURI(int index) {
   if (state == STATE_START_DOCUMENT || state == STATE_END_DOCUMENT) {
     throw new IllegalStateException();
   } else {
     return parent.getNamespaceURI(index);
   }
 }
コード例 #7
0
    public static RigStateType parse(final XMLStreamReader reader) throws Exception {
      RigStateType object = null;
      new HashMap<Object, Object>();

      String prefix = "";
      String namespaceuri = "";
      try {
        while (!reader.isStartElement() && !reader.isEndElement()) {
          reader.next();
        }

        while (!reader.isEndElement()) {
          if (reader.isStartElement() || reader.hasText()) {
            final String content = reader.getElementText();
            if (content.indexOf(":") > 0) {
              prefix = content.substring(0, content.indexOf(":"));
              namespaceuri = reader.getNamespaceURI(prefix);
              object = RigStateType.Factory.fromString(content, namespaceuri);
            } else {
              object = RigStateType.Factory.fromString(content, "");
            }
          } else {
            reader.next();
          }
        }
      } catch (final XMLStreamException e) {
        throw new Exception(e);
      }

      return object;
    }
コード例 #8
0
 /**
  * Gets an attribute value in the current context from their name
  *
  * @param s the name of the attribute
  * @return the value of the attribute
  */
 private String attrib(String s) {
   String value = reader.getAttributeValue(reader.getNamespaceURI(), s);
   if (value == null) {
     value = "";
   }
   return value;
 }
コード例 #9
0
ファイル: CachedCxfPayload.java プロジェクト: sryll/camel
 public String getNamespaceURI(int index) {
   if (index < prefixes.length) {
     return nsmap.get(prefixes[index]);
   } else {
     return reader.getNamespaceURI(index - prefixes.length);
   }
 }
コード例 #10
0
ファイル: StAXBuilder.java プロジェクト: a13m/wsdl2c
 /**
  * Method getNamespaceUri.
  *
  * @param index
  * @return Returns String.
  * @throws OMException
  */
 public String getNamespaceUri(int index) throws OMException {
   try {
     return parser.getNamespaceURI(index);
   } catch (Exception e) {
     throw new OMException(e);
   }
 }
コード例 #11
0
 /**
  * Processes elements and its sub-elements.
  *
  * @param reader XML stream reader
  * @throws XMLStreamException Thrown if problem occurred while reading XML stream.
  * @throws SQLException Thrown if problem occurred while communicating with database.
  */
 private static void processElement(final XMLStreamReader reader)
     throws XMLStreamException, SQLException {
   switch (reader.getNamespaceURI()) {
     case Namespaces.VYMENNY_FORMAT_TYPY:
       switch (reader.getLocalName()) {
         case "VymennyFormat":
           exchangeFormatConvertor.convert(reader);
           break;
         default:
           XMLUtils.processUnsupported(reader);
       }
       break;
     case Namespaces.SPECIALNI_VYMENNY_FORMAT_TYPY:
       switch (reader.getLocalName()) {
         case "SpecialniVymennyFormat":
           specialExchangeFormatConvertor.convert(reader);
           break;
         default:
           XMLUtils.processUnsupported(reader);
       }
       break;
     default:
       XMLUtils.processUnsupported(reader);
   }
 }
コード例 #12
0
ファイル: CachedCxfPayload.java プロジェクト: sryll/camel
 @Override
 public String getNamespaceURI(String prefix) {
   String nsuri = reader.getNamespaceURI();
   if (nsuri == null) {
     nsuri = nsmap.get(prefix);
   }
   return nsuri;
 }
コード例 #13
0
 /**
  * Method that can be used to verify that the current element pointed to by the stream reader does
  * not belong to a namespace.
  */
 protected static void assertElemNotInNamespace(XMLStreamReader sr) throws XMLStreamException {
   String uri = sr.getNamespaceURI();
   if (uri == null) {
     fail("Excepted empty String to indicate \"no namespace\": got null");
   } else if (uri.length() != 0) {
     fail("Excepted no (null) namespace URI: got '" + uri + "'");
   }
 }
コード例 #14
0
  @SuppressWarnings("unchecked")
  @Scheduled(fixedRate = 1000)
  public void processDATEXIIUpdateXML() {
    working = true;
    if (logger.isTraceEnabled()) {
      logger.trace("Polling for messages");
    }
    String xml;
    synchronized (messageQueue) {
      xml = messageQueue.poll();
    }
    while (xml != null) {
      try {
        byte[] bytes = xml.getBytes();
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

        XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = null;
        boolean foundBody = false;
        xsr = xif.createXMLStreamReader(bais);
        while (!foundBody && xsr.hasNext()) {
          if (xsr.next() == XMLStreamConstants.START_ELEMENT
              && "http://schemas.xmlsoap.org/soap/envelope/".equals(xsr.getNamespaceURI())
              && "Body".equals(xsr.getLocalName())) {
            foundBody = true;
            xsr.next();
          }
        }

        JAXBElement<D2LogicalModel> root;
        Unmarshaller unmarshaller = jaxbService.createUnmarshaller();
        if (foundBody) {
          root = (JAXBElement<D2LogicalModel>) unmarshaller.unmarshal(xsr);
        } else {
          InputStream inputStream = new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8));
          root = (JAXBElement<D2LogicalModel>) unmarshaller.unmarshal(inputStream);
        }
        D2LogicalModel d2lm = root.getValue();
        FeedType feedType = getFeedType(d2lm);
        DATEXIIProcessService datexiiProcessService =
            datexiiProcessServiceFactory.getDATEXIIProcessService(feedType);
        if (datexiiProcessService != null) {
          datexiiProcessService.processMessage(d2lm);
        }

      } catch (JAXBException e) {
        logger.error("Failed to process XML", e);
      } catch (XMLStreamException e) {
        logger.error("XMLStreamException", e);
      }
      synchronized (messageQueue) {
        xml = messageQueue.poll();
      }
    }
    working = false;
  }
コード例 #15
0
ファイル: TxTestParser.java プロジェクト: rmaucher/metadata
 @Override
 protected void processElement(TxTest metaData, XMLStreamReader reader) throws XMLStreamException {
   if (reader.getNamespaceURI().equals("urn:tx-timeout-test")) {
     final String localName = reader.getLocalName();
     if (localName.equals("timeout")) metaData.setTimeout(Long.valueOf(reader.getElementText()));
     else if (localName.equals("unit"))
       metaData.setUnit(TimeUnit.valueOf(reader.getElementText().toUpperCase()));
     else throw unexpectedElement(reader);
   } else super.processElement(metaData, reader);
 }
コード例 #16
0
    /**
     * static method to create the object Precondition: If this object is an element, the current or
     * next start element starts this object and any intervening reader events are ignorable If this
     * object is not an element, it is a complex type and the reader is at the event just after the
     * outer start element Postcondition: If this object is an element, the reader is positioned at
     * its end element If this object is a complex type, the reader is positioned at the end element
     * of its outer element
     */
    public static DebugLevel parse(javax.xml.stream.XMLStreamReader reader)
        throws java.lang.Exception {
      DebugLevel object = null;
      // initialize a hash map to keep values
      java.util.Map attributeMap = new java.util.HashMap();
      java.util.List extraAttributeList =
          new java.util.ArrayList<org.apache.axiom.om.OMAttribute>();

      int event;
      java.lang.String nillableValue = null;
      java.lang.String prefix = "";
      java.lang.String namespaceuri = "";
      try {

        while (!reader.isStartElement() && !reader.isEndElement()) reader.next();

        // Note all attributes that were handled. Used to differ normal attributes
        // from anyAttributes.
        java.util.Vector handledAttributes = new java.util.Vector();

        while (!reader.isEndElement()) {
          if (reader.isStartElement() || reader.hasText()) {

            nillableValue =
                reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "nil");
            if ("true".equals(nillableValue) || "1".equals(nillableValue)) {
              throw new org.apache.axis2.databinding.ADBException(
                  "The element: " + "DebugLevel" + "  cannot be null");
            }

            java.lang.String content = reader.getElementText();

            if (content.indexOf(":") > 0) {
              // this seems to be a Qname so find the namespace and send
              prefix = content.substring(0, content.indexOf(":"));
              namespaceuri = reader.getNamespaceURI(prefix);
              object = DebugLevel.Factory.fromString(content, namespaceuri);
            } else {
              // this seems to be not a qname send and empty namespace incase of it is
              // check is done in fromString method
              object = DebugLevel.Factory.fromString(content, "");
            }

          } else {
            reader.next();
          }
        } // end of while loop

      } catch (javax.xml.stream.XMLStreamException e) {
        throw new java.lang.Exception(e);
      }

      return object;
    }
コード例 #17
0
 public String getNamespaceURI(String prefix) {
   // It is not clear whether this method is allowed in all states.
   // The XMLStreamReader Javadoc suggest it is, but Woodstox doesn't
   // allow it on states other than START_ELEMENT and END_ELEMENT.
   // We emulate behavior of Woodstox.
   if (state == STATE_START_DOCUMENT || state == STATE_END_DOCUMENT) {
     throw new IllegalStateException();
   } else {
     return parent.getNamespaceURI(prefix);
   }
 }
コード例 #18
0
  /**
   * Creates a {@link StreamMessage} from a {@link XMLStreamReader} that points at the start element
   * of the payload, and headers.
   *
   * <p>This method creaets a {@link Message} from a payload.
   *
   * @param headers if null, it means no headers. if non-null, it will be owned by this message.
   * @param reader points at the start element/document of the payload (or the end element of the
   *     &lt;s:Body> if there's no payload)
   */
  public VerifiedStreamMessage(
      @Nullable HeaderList headers,
      @NotNull AttachmentSet attachmentSet,
      @NotNull XMLStreamReader reader,
      @NotNull SOAPVersion soapVersion,
      Map<String, String> bodyEnvNs) {
    super(soapVersion);
    this.headers = headers;
    this.attachmentSet = attachmentSet;
    this.reader = reader;
    this.bodyEnvNs = bodyEnvNs;

    if (reader.getEventType() == START_DOCUMENT) {
      XMLStreamReaderUtil.nextElementContent(reader);
    }

    // if the reader is pointing to the end element </soapenv:Body> then its empty message
    // or no payload
    if (reader.getEventType() == XMLStreamConstants.END_ELEMENT) {
      String body = reader.getLocalName();
      String nsUri = reader.getNamespaceURI();
      assert body != null;
      assert nsUri != null;
      // if its not soapenv:Body then throw exception, we received malformed stream
      if (body.equals("Body") && nsUri.equals(soapVersion.nsUri)) {
        this.payloadLocalName = null;
        this.payloadNamespaceURI = null;
      } else { // TODO: i18n and also we should be throwing better message that this
        throw new WebServiceException("Malformed stream: {" + nsUri + "}" + body);
      }
    } else {
      this.payloadLocalName = reader.getLocalName();
      this.payloadNamespaceURI = reader.getNamespaceURI();
    }

    // use the default infoset representation for headers
    int base = soapVersion.ordinal() * 3;
    this.envelopeTag = DEFAULT_TAGS[base];
    this.headerTag = DEFAULT_TAGS[base + 1];
    this.bodyTag = DEFAULT_TAGS[base + 2];
  }
コード例 #19
0
  public Message copy() {
    try {
      // copy the payload
      XMLStreamReader clone;
      XMLStreamReader clonedReader;

      if (hasPayload()) {
        assert unconsumed();
        consumedAt = null; // but we don't want to mark it as consumed
        MutableXMLStreamBuffer xsb = new MutableXMLStreamBuffer();

        // the boolean value tells the first body part is written.
        // based on this we do the right thing
        StreamReaderBufferCreator c = new StreamReaderBufferCreator(xsb);
        while (reader.getEventType() != XMLStreamConstants.END_DOCUMENT) {
          String name = reader.getLocalName();
          String nsUri = reader.getNamespaceURI();
          if (name.equals("Body") && nsUri.equals(soapVersion.nsUri)
              || (reader.getEventType() == XMLStreamConstants.END_DOCUMENT)) {
            break;
          }
          c.create(reader);
        }
        XMLStreamReaderFactory.recycle(reader);

        reader = xsb.readAsXMLStreamReader();
        reader = new VerifiedMessageXMLStreamReader(reader, bodyEnvNs);
        clone = xsb.readAsXMLStreamReader();
        clonedReader = new VerifiedMessageXMLStreamReader(clone, bodyEnvNs);
        // advance to the start tag of the first element
        proceedToRootElement(reader);
        proceedToRootElement(clonedReader);
      } else {
        // it's tempting to use EmptyMessageImpl, but it doesn't presere the infoset
        // of <envelope>,<header>, and <body>, so we need to stick to StreamMessage.
        clone = reader;
        clonedReader = reader;
      }

      return new VerifiedStreamMessage(
          envelopeTag,
          headerTag,
          attachmentSet,
          HeaderList.copy(headers),
          bodyTag,
          clone,
          soapVersion,
          this.bodyEnvNs);
    } catch (XMLStreamException e) {
      throw new WebServiceException("Failed to copy a message", e);
    }
  }
コード例 #20
0
    /**
     * static method to create the object Precondition: If this object is an element, the current or
     * next start element starts this object and any intervening reader events are ignorable If this
     * object is not an element, it is a complex type and the reader is at the event just after the
     * outer start element Postcondition: If this object is an element, the reader is positioned at
     * its end element If this object is a complex type, the reader is positioned at the end element
     * of its outer element
     */
    public static EnumMWSAttributeFormCategories_type0 parse(
        javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
      EnumMWSAttributeFormCategories_type0 object = null;
      // initialize a hash map to keep values
      java.util.Map attributeMap = new java.util.HashMap();
      java.util.List extraAttributeList = new java.util.ArrayList();

      int event;
      java.lang.String nillableValue = null;
      java.lang.String prefix = "";
      java.lang.String namespaceuri = "";
      try {

        while (!reader.isStartElement() && !reader.isEndElement()) reader.next();

        // Note all attributes that were handled. Used to differ normal
        // attributes
        // from anyAttributes.
        java.util.Vector handledAttributes = new java.util.Vector();

        while (!reader.isEndElement()) {
          if (reader.isStartElement() || reader.hasText()) {

            java.lang.String content = reader.getElementText();

            if (content.indexOf(":") > 0) {
              // this seems to be a Qname so find the namespace
              // and send
              prefix = content.substring(0, content.indexOf(":"));
              namespaceuri = reader.getNamespaceURI(prefix);
              object =
                  EnumMWSAttributeFormCategories_type0.Factory.fromString(content, namespaceuri);
            } else {
              // this seems to be not a qname send and empty
              // namespace incase of it is
              // check is done in fromString method
              object = EnumMWSAttributeFormCategories_type0.Factory.fromString(content, "");
            }

          } else {
            reader.next();
          }
        } // end of while loop

      } catch (javax.xml.stream.XMLStreamException e) {
        throw new java.lang.Exception(e);
      }

      return object;
    }
コード例 #21
0
 public void test1() throws Exception {
   URL fileurl = getResource("hello_literal_identity.wsdl");
   WSDLModel doc =
       RuntimeWSDLParser.parse(
           fileurl, new StreamSource(fileurl.toExternalForm()), getResolver(), true, null);
   WSDLService service = doc.getService(new QName("urn:test", "Hello"));
   WSDLPort port = service.getFirstPort();
   WSEndpointReference wsepr = port.getExtension(WSEndpointReference.class);
   QName q = new QName("http://schemas.xmlsoap.org/ws/2006/02/addressingidentity", "Identity");
   WSEndpointReference.EPRExtension eprExtn = wsepr.getEPRExtension(q);
   XMLStreamReader xsr = eprExtn.readAsXMLStreamReader();
   if (xsr.getEventType() == XMLStreamConstants.START_DOCUMENT) xsr.next();
   assertEquals(q.getNamespaceURI(), xsr.getNamespaceURI());
   assertEquals(q.getLocalPart(), xsr.getLocalName());
 }
コード例 #22
0
 /**
  * ns4 is declared on Envelope and Body and is used in faultcode. So making sure the correct ns4
  * is picked up for payload source
  */
 public void testPayloadSource1() throws Exception {
   String soap18Msg =
       "<S:Envelope xmlns:S='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns4='A'>"
           + "<S:Body xmlns:ns4='http://schemas.xmlsoap.org/soap/envelope/'>"
           + "<S:Fault>"
           + "<faultcode>ns4:Server</faultcode>"
           + "<faultstring>com.sun.istack.XMLStreamException2</faultstring>"
           + "</S:Fault>"
           + "</S:Body>"
           + "</S:Envelope>";
   Message message = useStreamCodec(soap18Msg);
   Source source = message.readPayloadAsSource();
   InputStream is = getInputStream(source);
   XMLStreamReader xsr = XMLInputFactory.newInstance().createXMLStreamReader(is);
   xsr.next();
   xsr.next();
   assertEquals("http://schemas.xmlsoap.org/soap/envelope/", xsr.getNamespaceURI("ns4"));
 }
コード例 #23
0
ファイル: XMLStreamUtils.java プロジェクト: deegree/deegree3
 /**
  * @param xmlStream
  * @param s may not be null
  * @return a parsed qname
  */
 public static QName asQName(XMLStreamReader xmlStream, String s) {
   QName result = null;
   int colonIdx = s.indexOf(':');
   if (colonIdx < 0) {
     result = new QName(s);
   } else if (colonIdx == s.length() - 1) {
     throw new XMLParsingException(xmlStream, "Invalid QName '" + s + "': no local name.");
   } else {
     String prefix = s.substring(0, colonIdx);
     String localPart = s.substring(colonIdx + 1);
     String nsUri = xmlStream.getNamespaceURI(prefix);
     if (nsUri == null) {
       throw new XMLParsingException(
           xmlStream, "Invalid QName '" + s + "': prefix '" + prefix + "' is unbound.");
     }
     result = new QName(nsUri, localPart, prefix);
   }
   return result;
 }
コード例 #24
0
  @Override
  protected void processElement(final XMLStreamReader reader, final Pou item)
      throws XMLStreamException {
    switch (reader.getNamespaceURI()) {
      case NAMESPACE:
        switch (reader.getLocalName()) {
          case "Geometrie":
            Utils.processGeometrie(reader, getConnection(), item, NAMESPACE);
            break;
          case "GlobalniIdNavrhuZmeny":
            item.setNzIdGlobalni(Long.parseLong(reader.getElementText()));
            break;
          case "IdTransakce":
            item.setIdTransRuian(Long.parseLong(reader.getElementText()));
            break;
          case "Kod":
            item.setKod(Integer.parseInt(reader.getElementText()));
            break;
          case "Nazev":
            item.setNazev(reader.getElementText());
            break;
          case "Nespravny":
            item.setNespravny(Boolean.valueOf(reader.getElementText()));
            break;
          case "Orp":
            item.setOrpKod(Utils.getOrpKod(reader, NAMESPACE));
            break;
          case "PlatiOd":
            item.setPlatiOd(Utils.parseTimestamp(reader.getElementText()));
            break;
          case "SpravniObecKod":
            item.setSpravniObecKod(Integer.parseInt(reader.getElementText()));
            break;
          default:
            XMLUtils.processUnsupported(reader);
        }

        break;
      default:
        XMLUtils.processUnsupported(reader);
    }
  }
コード例 #25
0
  private void handleStartElement() throws XMLStreamException {

    try {
      // start namespace bindings
      int nsCount = staxStreamReader.getNamespaceCount();
      for (int i = 0; i < nsCount; i++) {
        saxHandler.startPrefixMapping(
            fixNull(staxStreamReader.getNamespacePrefix(i)),
            fixNull(staxStreamReader.getNamespaceURI(i)));
      }

      // fire startElement
      QName qName = staxStreamReader.getName();
      String prefix = qName.getPrefix();
      String rawname;
      if (prefix == null || prefix.length() == 0) rawname = qName.getLocalPart();
      else rawname = prefix + ':' + qName.getLocalPart();
      Attributes attrs = getAttributes();
      saxHandler.startElement(qName.getNamespaceURI(), qName.getLocalPart(), rawname, attrs);
    } catch (SAXException e) {
      throw new XMLStreamException2(e);
    }
  }
コード例 #26
0
ファイル: StaxNavigatorImpl.java プロジェクト: mto/staxnav
    private Element(XMLStreamReader stream, Element parent) throws XMLStreamException {
      // We assume that the stream points to the start of the modelled element
      if (stream.getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new AssertionError();
      }

      //
      QName name = stream.getName();
      Location location = stream.getLocation();

      //
      Map<String, String> attributes = Collections.emptyMap();
      Map<QName, String> qualifiedAttributes = Collections.emptyMap();
      int attributeCount = stream.getAttributeCount();
      for (int i = 0; i < attributeCount; i++) {
        String attributeValue = stream.getAttributeValue(i);
        QName attributeName = stream.getAttributeName(i);
        if (XMLConstants.NULL_NS_URI.equals(attributeName.getNamespaceURI())) {
          if (attributes.isEmpty()) {
            attributes = new HashMap<String, String>();
          }
          attributes.put(attributeName.getLocalPart(), attributeValue);
        } else {
          if (qualifiedAttributes.isEmpty()) {
            qualifiedAttributes = new HashMap<QName, String>();
          }
          qualifiedAttributes.put(attributeName, attributeValue);
        }
      }

      //
      Map<String, String> namespaces;
      int namespaceCount = stream.getNamespaceCount();
      if (namespaceCount > 0) {
        namespaces = new HashMap<String, String>();
        for (int i = 0; i < namespaceCount; i++) {
          String namespacePrefix = stream.getNamespacePrefix(i);
          if (namespacePrefix == null) {
            namespacePrefix = "";
          }
          String namespaceURI = stream.getNamespaceURI(i);
          namespaces.put(namespacePrefix, namespaceURI);
        }
      } else {
        namespaces = Collections.emptyMap();
      }

      // When we leave we assume that we are positionned on the next element start or the document
      // end
      StringBuilder sb = null;
      String chunk = null;
      Object content = null;
      while (true) {
        stream.next();
        int type = stream.getEventType();
        if (type == XMLStreamConstants.END_DOCUMENT || type == XMLStreamConstants.START_ELEMENT) {
          break;
        } else if (type == XMLStreamConstants.CHARACTERS) {
          if (chunk == null) {
            chunk = stream.getText();
          } else {
            if (sb == null) {
              sb = new StringBuilder(chunk);
            }
            sb.append(stream.getText());
          }
        } else if (type == XMLStreamConstants.END_ELEMENT) {
          if (sb != null) {
            content = sb;
          } else {
            content = chunk;
          }
          break;
        }
      }

      //
      int depth = 1 + (parent != null ? parent.getDepth() : 0);

      //
      this.parent = parent;
      this.name = name;
      this.depth = depth;
      this.content = content;
      this.attributes = attributes;
      this.qualifiedAttributes = qualifiedAttributes;
      this.namespaces = namespaces;
      this.location = location;
    }
コード例 #27
0
ファイル: ObrContentProvider.java プロジェクト: JSlain/bnd
  public CheckResult checkStream(String name, InputStream stream) throws IOException {
    XMLStreamReader reader = null;
    try {
      XMLInputFactory inputFactory = XMLInputFactory.newInstance();

      inputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
      inputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
      inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);

      reader = inputFactory.createXMLStreamReader(stream);
      ParserState state = ParserState.beforeRoot;

      while (reader.hasNext()) {
        int type = reader.next();
        String localName;

        switch (type) {
          case PROCESSING_INSTRUCTION:
            if (PI_TARGET_STYLESHEET.equals(reader.getPITarget())
                && PI_DATA_STYLESHEET.equals(reader.getPIData()))
              return new CheckResult(accept, "Recognised stylesheet", null);
            break;
          case START_ELEMENT:
            localName = reader.getLocalName();
            switch (state) {
              case beforeRoot:
                String nsUri = reader.getNamespaceURI();
                if (nsUri != null)
                  return CheckResult.fromBool(
                      NS_URI.equals(nsUri),
                      "Correct namespace on root element",
                      "Incorrect namespace on root element: " + nsUri,
                      null);
                if (!TAG_REPOSITORY.equals(localName))
                  return new CheckResult(reject, "Incorrect root element name", null);
                state = ParserState.inRoot;
                break;
              case inRoot:
                if (TAG_RESOURCE.equals(localName)) {
                  state = ParserState.inResource;
                } else if (!TAG_REFERRAL.equals(localName)) {
                  return new CheckResult(
                      reject,
                      String.format(
                          "Incorrect element '%s', expected '%s' or '%s'.",
                          localName, TAG_RESOURCE, TAG_REFERRAL),
                      null);
                }
                break;
              case inResource:
                if (TAG_CAPABILITY.equals(localName)) {
                  state = ParserState.inCapability;
                }
                break;
              case inCapability:
                return CheckResult.fromBool(
                    TAG_PROPERTY.equals(localName),
                    "Found 'p' tag inside 'capability'",
                    String.format(
                        "Incorrect element '%s' inside '%s'; expected '%s'.",
                        localName, TAG_CAPABILITY, TAG_PROPERTY),
                    null);
            }
            break;
          case END_ELEMENT:
            localName = reader.getLocalName();
            if (state == ParserState.inResource && TAG_RESOURCE.equals(localName))
              state = ParserState.inRoot;
            if (state == ParserState.inCapability && TAG_CAPABILITY.equals(localName))
              state = ParserState.inResource;
            break;
        }
      }
      return new CheckResult(undecided, "Reached end of stream", null);
    } catch (XMLStreamException e) {
      return new CheckResult(reject, "Invalid XML", e);
    } finally {
      if (reader != null)
        try {
          reader.close();
        } catch (XMLStreamException e) {
        }
    }
  }
コード例 #28
0
 public String getNamespaceURI() {
   return streamReader.getNamespaceURI();
 }
コード例 #29
0
 public String getNamespaceURI(final int index) {
   return streamReader.getNamespaceURI(index);
 }
コード例 #30
0
 public String getNamespaceURI(final String prefix) {
   return streamReader.getNamespaceURI(prefix);
 }