Ejemplo n.º 1
0
 private static Element parseElement(XMLStreamReader xsr) throws XMLStreamException {
   // xsr points to a START_ELEMENT event. Create the element and read all its attributes
   // Then read all its children events
   Element element = new Element(xsr.getLocalName());
   // text that will be added to the element. Text can come in different events, so we add it here
   // and add it to the element at the end
   StringBuilder elementText = new StringBuilder();
   int attributeCount = xsr.getAttributeCount();
   for (int i = 0; i < attributeCount; i++) {
     element.putAttribute(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
   }
   while (xsr.hasNext()) {
     xsr.next();
     if (xsr.getEventType() == XMLStreamConstants.END_ELEMENT) {
       // element is closed. Move the cursor and return it
       // check if there is some text to add before (empty text is not added, but added text is not
       // trimmed)
       // we set empty text also if the element has no children
       if (!elementText.toString().trim().isEmpty() || !element.hasChildren()) {
         element.setText(elementText.toString());
       }
       //                xsr.next();
       return element;
     } else if (xsr.getEventType() == XMLStreamConstants.CHARACTERS) {
       // an attribute of the current element
       elementText.append(xsr.getText());
     } else if (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) {
       // new element begins -> read it recursively and add it to the current element
       element.addChild(parseElement(xsr));
     }
   }
   // we reached the end of the document without the tag end -> error parsing
   throw new XMLStreamException(
       "End of the document unexpectedly reached. Element " + element.getName() + " not closed");
 }
Ejemplo n.º 2
0
 /** Method to parse an XML Node in ACX files */
 private void procNodeACX() {
   int type = reader.getEventType();
   String name = "";
   if (reader.hasName()) {
     name = reader.getLocalName();
   }
   if (type == XMLStreamConstants.START_ELEMENT) {
     if (name.equals("char")) {
       acx_current_char = (int) (attrib("value").charAt(0));
     } else if (name.equals("equiv-char")) {
       if (!acx_map.containsKey(acx_current_char)) {
         HashSet<Integer> set = new HashSet<Integer>();
         acx_map.put(acx_current_char, set);
       }
       acx_map.get(acx_current_char).add((int) (attrib("value").charAt(0)));
     } else {
     }
   } else if (type == XMLStreamConstants.SPACE) {
   } else if (type == XMLStreamConstants.CHARACTERS) {
   } else if (type == XMLStreamConstants.END_DOCUMENT) {
   } else if (type == XMLStreamConstants.START_DOCUMENT) {
   } else if (type == XMLStreamConstants.END_ELEMENT) {
   } else if (type == XMLStreamConstants.COMMENT) {
   } else {
     throw new RuntimeException(
         "Error in ACX file ("
             + reader.getLocation().getLineNumber()
             + ","
             + reader.getLocation().getColumnNumber()
             + "): invalid node '<"
             + XMLPrint.getEventTypeString(reader.getEventType())
             + ">");
   }
 }
  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);
  }
 private boolean post(QName tagName, XMLStreamReader xsr, boolean result) {
   if (!tagName.equals(xsr.getName())) return foundFool();
   if (result) {
     if (xsr.getEventType() != XMLStreamConstants.END_ELEMENT) foundFool();
   } else {
     if (xsr.getEventType() != XMLStreamConstants.START_ELEMENT) foundFool();
   }
   return result;
 }
  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);
    }
  }
Ejemplo n.º 6
0
 public static void require(XMLStreamReader xmlStream, int eventType) throws XMLParsingException {
   if (xmlStream.getEventType() != eventType) {
     String msg =
         "Encountered a "
             + getEventTypeString(xmlStream.getEventType())
             + " event, but a "
             + getEventTypeString(eventType)
             + " event is required at this position.";
     throw new XMLParsingException(xmlStream, msg);
   }
 }
  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);
    }
  }
Ejemplo n.º 8
0
 /**
  * Move the reader to the next {@link XMLStreamConstants #START_ELEMENT} or {@link
  * XMLStreamConstants #END_ELEMENT} event.
  *
  * @param xmlReader
  * @return event type
  * @throws XMLStreamException
  * @throws NoSuchElementException if the end of the document is reached
  */
 public static int nextElement(XMLStreamReader xmlReader)
     throws XMLStreamException, NoSuchElementException {
   xmlReader.next();
   while (xmlReader.getEventType() != END_DOCUMENT
       && !xmlReader.isStartElement()
       && !xmlReader.isEndElement()) {
     xmlReader.next();
   }
   if (xmlReader.getEventType() == END_DOCUMENT) {
     throw new NoSuchElementException();
   }
   return xmlReader.getEventType();
 }
Ejemplo n.º 9
0
  public LoggingEvents read(XMLStreamReader reader) throws XMLStreamException {
    LoggingEvents result = null;
    String rootNamespace = NAMESPACE_URI;
    int type = reader.getEventType();

    if (XMLStreamConstants.START_DOCUMENT == type) {
      reader.nextTag();
      type = reader.getEventType();
      rootNamespace = null;
    }
    if (XMLStreamConstants.START_ELEMENT == type
        && LOGGING_EVENTS_NODE.equals(reader.getLocalName())) {
      result = new LoggingEvents();
      String idxStr =
          StaxUtilities.readAttributeValue(reader, NAMESPACE_URI, START_INDEX_ATTRIBUTE);
      long idx = 0;
      if (idxStr != null) {
        idx = Long.parseLong(idxStr);
      }
      result.setStartIndex(idx);
      reader.nextTag();
      SourceIdentifier sourceId = sourceIdentifierReader.read(reader);
      if (sourceId != null) {
        result.setSource(sourceId);
        reader.require(
            XMLStreamConstants.END_ELEMENT,
            null,
            EventSourceSchemaConstants.SOURCE_IDENTIFIER_NODE);
        reader.nextTag();
      }

      List<LoggingEvent> events = null;
      for (; ; ) {
        LoggingEvent event = loggingEventReader.read(reader);
        if (event == null) {
          break;
        }
        reader.require(XMLStreamConstants.END_ELEMENT, null, LOGGING_EVENT_NODE);
        reader.nextTag();
        if (events == null) {
          events = new ArrayList<LoggingEvent>();
        }
        events.add(event);
      }
      result.setEvents(events);
      reader.require(XMLStreamConstants.END_ELEMENT, null, LOGGING_EVENTS_NODE);
    }
    return result;
  }
  public Object unmarshal0(XMLStreamReader reader, JaxBeanInfo expectedType) throws JAXBException {
    if (reader == null) {
      throw new IllegalArgumentException(Messages.format(Messages.NULL_READER));
    }

    int eventType = reader.getEventType();
    if (eventType != XMLStreamConstants.START_ELEMENT
        && eventType != XMLStreamConstants.START_DOCUMENT) {
      // TODO: convert eventType into event name
      throw new IllegalStateException(Messages.format(Messages.ILLEGAL_READER_STATE, eventType));
    }

    XmlVisitor h = createUnmarshallerHandler(null, false, expectedType);
    StAXConnector connector = StAXStreamConnector.create(reader, h);

    try {
      connector.bridge();
    } catch (XMLStreamException e) {
      throw handleStreamException(e);
    }

    Object retVal = h.getContext().getResult();
    h.getContext().clearResult();
    return retVal;
  }
Ejemplo n.º 11
0
  public static void parseCorrelations(
      XMLStreamReader input, Contextual<?> ctx, ExecCompilerContext context)
      throws XMLStreamException, ParserException {
    while (input.hasNext()) {
      int type = input.getEventType();
      switch (type) {
        case XMLStreamConstants.START_ELEMENT:
          ParserUtils.assertStart(input, CORRELATIONS);
          Contextual<Correlations> corrs =
              new Contextual<Correlations>(CORRELATIONS, Correlations.class, ctx);
          ParserUtils.setLocation(input, context.source().srcRef(), corrs);
          ctx.children().add(corrs);
          while (input.nextTag() == XMLStreamConstants.START_ELEMENT) {
            if (CORRELATION.equals(input.getName())) {
              Instructional<Correlation> corr =
                  new Instructional<Correlation>(CORRELATION, Correlation.class, corrs);
              ParserUtils.setLocation(input, context.source().srcRef(), corr);
              corrs.children().add(corr);
              while (input.nextTag() == XMLStreamConstants.START_ELEMENT) {
                context.parseContent(input, corr);
              }
            } else {
              context.parseContent(input, corrs);
            }
          }

          break;
        case XMLStreamConstants.END_ELEMENT:
          ParserUtils.assertEnd(input, CORRELATIONS);
          return;
      }
    }
  }
Ejemplo n.º 12
0
 public void parseFromParts(
     XMLStreamReader input, Contextual<Receive> receive, ExecCompilerContext context)
     throws XMLStreamException, ParserException {
   while (input.hasNext()) {
     int type = input.getEventType();
     switch (type) {
       case XMLStreamConstants.START_ELEMENT:
         ParserUtils.assertStart(input, FROMPARTS);
         Contextual<FromParts> fromParts =
             new Contextual<FromParts>(FROMPARTS, FromParts.class, receive);
         ParserUtils.setLocation(input, context.source().srcRef(), fromParts);
         receive.children().add(fromParts);
         while (input.nextTag() == XMLStreamConstants.START_ELEMENT) {
           if (FROMPART.equals(input.getName())) {
             Instructional<FromPart> fromPart =
                 new Instructional<FromPart>(FROMPART, FromPart.class, fromParts);
             ParserUtils.setLocation(input, context.source().srcRef(), fromPart);
             fromParts.children().add(fromPart);
             while (input.nextTag() == XMLStreamConstants.START_ELEMENT) {
               context.parseContent(input, fromPart);
             }
           } else {
             context.parseContent(input, fromParts);
           }
         }
         break;
       case XMLStreamConstants.END_ELEMENT:
         ParserUtils.assertEnd(input, FROMPARTS);
         return;
     }
   }
 }
Ejemplo n.º 13
0
  static String getNextElement(
      XMLStreamReader reader, String name, Map<String, String> attributes, boolean getElementText)
      throws XMLStreamException {
    if (!reader.hasNext()) {
      throw new XMLStreamException("Expected more elements", reader.getLocation());
    }
    int type = reader.next();
    while (reader.hasNext() && type != START_ELEMENT) {
      type = reader.next();
    }
    if (reader.getEventType() != START_ELEMENT) {
      throw new XMLStreamException("No <" + name + "> found");
    }
    if (!reader.getLocalName().equals("" + name + "")) {
      throw new XMLStreamException("<" + name + "> expected", reader.getLocation());
    }

    if (attributes != null) {
      for (int i = 0; i < reader.getAttributeCount(); i++) {
        String attr = reader.getAttributeLocalName(i);
        if (!attributes.containsKey(attr)) {
          throw new XMLStreamException("Unexpected attribute " + attr, reader.getLocation());
        }
        attributes.put(attr, reader.getAttributeValue(i));
      }
    }

    return getElementText ? reader.getElementText() : null;
  }
Ejemplo n.º 14
0
  private void parse() throws XMLStreamException {
    final InputStream stream = this.getClass().getResourceAsStream("cigars.xml");
    final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    final XMLStreamReader streamReader = inputFactory.createXMLStreamReader(stream);
    manufacturers = new HashMap<String, List<ParsedProduct>>();

    int manufacturerId = 1;
    while (streamReader.hasNext()) {
      streamReader.next();
      final int type = streamReader.getEventType();
      if (XMLEvent.START_ELEMENT == type) {
        final QName qName = streamReader.getName();
        if ("a".equals(qName.getLocalPart())) {
          UrlParser parser = new UrlParser(streamReader.getAttributeValue(0));
          parser.parse();
          if (parser.isValid()) {
            final String manufacturer = parser.getManufacturer();
            System.out.println("Id:" + parser.getId() + " , manufacture:" + manufacturer);

            List<ParsedProduct> products = manufacturers.get(manufacturer);
            if (products == null) {
              products = new ArrayList<ParsedProduct>();
              manufacturerId++;
              manufacturers.put(parser.getManufacturer(), products);
            }
            final String text = streamReader.getElementText();
            final ParsedProduct newProduct = new ParsedProduct(parser.getId(), text);
            products.add(newProduct);
            System.out.println(">>" + text);
          }
        }
      }
    }
  }
Ejemplo n.º 15
0
  @Test
  public void testTypeConversion() throws Exception {
    BufferManager bm = BufferManagerFactory.getStandaloneBufferManager();

    String str = "hello world";

    Object source = new StreamSource(new StringReader(str));
    XMLType xml =
        (XMLType)
            ConnectorWorkItem.convertToRuntimeType(
                bm, source, DataTypeManager.DefaultDataClasses.XML, null);
    assertEquals(str, xml.getString());

    source =
        new StAXSource(XMLType.getXmlInputFactory().createXMLEventReader(new StringReader("<a/>")));
    xml =
        (XMLType)
            ConnectorWorkItem.convertToRuntimeType(
                bm, source, DataTypeManager.DefaultDataClasses.XML, null);
    XMLInputFactory in = XMLType.getXmlInputFactory();
    XMLStreamReader reader = in.createXMLStreamReader(new StringReader(xml.getString()));
    assertEquals(XMLEvent.START_DOCUMENT, reader.getEventType());
    assertEquals(XMLEvent.START_ELEMENT, reader.next());
    assertEquals("a", reader.getLocalName());
    assertEquals(XMLEvent.END_ELEMENT, reader.next());

    byte[] bytes = str.getBytes(Streamable.ENCODING);
    source = new InputStreamFactory.BlobInputStreamFactory(BlobType.createBlob(bytes));
    BlobType blob =
        (BlobType)
            ConnectorWorkItem.convertToRuntimeType(
                bm, source, DataTypeManager.DefaultDataClasses.BLOB, null);

    assertArrayEquals(bytes, ObjectConverterUtil.convertToByteArray(blob.getBinaryStream()));
  }
Ejemplo n.º 16
0
  /**
   * Get the attributes associated with the given START_ELEMENT or ATTRIBUTE StAXevent.
   *
   * @return the StAX attributes converted to an org.xml.sax.Attributes
   */
  private Attributes getAttributes() {
    AttributesImpl attrs = new AttributesImpl();

    int eventType = staxStreamReader.getEventType();
    if (eventType != XMLStreamConstants.ATTRIBUTE
        && eventType != XMLStreamConstants.START_ELEMENT) {
      throw new InternalError("getAttributes() attempting to process: " + eventType);
    }

    // in SAX, namespace declarations are not part of attributes by default.
    // (there's a property to control that, but as far as we are concerned
    // we don't use it.) So don't add xmlns:* to attributes.

    // gather non-namespace attrs
    for (int i = 0; i < staxStreamReader.getAttributeCount(); i++) {
      String uri = staxStreamReader.getAttributeNamespace(i);
      if (uri == null) uri = "";
      String localName = staxStreamReader.getAttributeLocalName(i);
      String prefix = staxStreamReader.getAttributePrefix(i);
      String qName;
      if (prefix == null || prefix.length() == 0) qName = localName;
      else qName = prefix + ':' + localName;
      String type = staxStreamReader.getAttributeType(i);
      String value = staxStreamReader.getAttributeValue(i);

      attrs.addAttribute(uri, localName, qName, type, value);
    }

    return attrs;
  }
Ejemplo n.º 17
0
 private static Element parse(XMLStreamReader xsr) throws XMLStreamException {
   // we skip the events until we reach the root element
   while (xsr.getEventType() != XMLStreamConstants.START_ELEMENT) {
     xsr.next();
   }
   return parseElement(xsr);
 }
Ejemplo n.º 18
0
 /**
  * Creates printable (debug) information about the event that the cursor of the given <code>
  * XMLStreamReader</code> currently points at.
  *
  * @param xmlStream
  * @return printable information
  */
 public static final String getCurrentEventInfo(XMLStreamReader xmlStream) {
   String s = getEventTypeString(xmlStream.getEventType());
   if (xmlStream.getEventType() == START_ELEMENT || xmlStream.getEventType() == END_ELEMENT) {
     s += ": " + xmlStream.getName();
   }
   Location location = xmlStream.getLocation();
   s +=
       " at line "
           + location.getLineNumber()
           + ", column "
           + location.getColumnNumber()
           + " (character offset "
           + xmlStream.getLocation().getCharacterOffset()
           + ")";
   return s;
 }
Ejemplo n.º 19
0
 protected static XMLStreamReader2 constructStreamReaderForFile(XMLInputFactory f, String filename)
     throws IOException, XMLStreamException {
   File inf = new File(filename);
   XMLStreamReader sr = f.createXMLStreamReader(inf.toURL().toString(), new FileReader(inf));
   assertEquals(sr.getEventType(), START_DOCUMENT);
   return (XMLStreamReader2) sr;
 }
Ejemplo n.º 20
0
  /**
   * Method that not only gets currently available text from the reader, but also checks that its
   * consistenly accessible using different (basic) StAX methods.
   */
  protected static String getAndVerifyText(XMLStreamReader sr) throws XMLStreamException {
    /* 05-Apr-2006, TSa: Although getText() is available for DTD
     *   and ENTITY_REFERENCE, getTextXxx() are not. Thus, can not
     *   do more checks for those types.
     */
    int type = sr.getEventType();
    if (type == ENTITY_REFERENCE || type == DTD) {
      return sr.getText();
    }

    int expLen = sr.getTextLength();
    /* Hmmh. It's only ok to return empty text for DTD event... well,
     * maybe also for CDATA, since empty CDATA blocks are legal?
     */
    /* !!! 01-Sep-2004, TSa:
     *  note: theoretically, in coalescing mode, it could be possible
     *  to have empty CDATA section(s) get converted to CHARACTERS,
     *  which would be empty... may need to enhance this to check that
     *  mode is not coalescing? Or something
     */
    if (type == CHARACTERS) {
      assertTrue("Stream reader should never return empty Strings.", (expLen > 0));
    }
    String text = sr.getText();
    assertNotNull("getText() should never return null.", text);
    assertEquals(
        "Expected text length of " + expLen + ", got " + text.length(), expLen, text.length());
    char[] textChars = sr.getTextCharacters();
    int start = sr.getTextStart();
    String text2 = new String(textChars, start, expLen);
    assertEquals(text, text2);
    return text;
  }
  /**
   * Populates the object from the XMLStreamReader
   *
   * @param xmlr the XMLStreamReader to read from
   * @throws XMLStreamException if there is an error parsing the stream
   * @throws ParseException if there is an error in parsing a date
   * @throws URISyntaxException if the uri is invalid
   */
  protected static BlobContainerAttributes readBlobContainerAttributes(final XMLStreamReader xmlr)
      throws XMLStreamException, ParseException, URISyntaxException {
    int eventType = xmlr.getEventType();

    final BlobContainerAttributes attributes = new BlobContainerAttributes();

    while (xmlr.hasNext()) {
      eventType = xmlr.next();
      final String name = xmlr.getName().toString();
      if (eventType == XMLStreamConstants.START_ELEMENT) {
        if (name.equals(BlobConstants.PROPERTIES)) {
          attributes.setProperties(BlobDeserializationHelper.readBlobContainerProperties(xmlr));
          xmlr.require(XMLStreamConstants.END_ELEMENT, null, BlobConstants.PROPERTIES);
        } else if (name.equals(Constants.URL_ELEMENT)) {
          attributes.setUri(new URI(Utility.readElementFromXMLReader(xmlr, Constants.URL_ELEMENT)));
        } else if (name.equals(Constants.NAME_ELEMENT)) {
          attributes.setName(Utility.readElementFromXMLReader(xmlr, Constants.NAME_ELEMENT));
        } else if (name.equals(Constants.METADATA_ELEMENT)) {
          // parse metadata
          attributes.setMetadata(DeserializationHelper.parseMetadateFromXML(xmlr));
          xmlr.require(XMLStreamConstants.END_ELEMENT, null, Constants.METADATA_ELEMENT);
        }
      } else if (eventType == XMLStreamConstants.END_ELEMENT
          && name.equals(BlobConstants.CONTAINER_ELEMENT)) {
        break;
      }
    }

    return attributes;
  }
 /**
  * Construct a new instance of the {@code StaxStreamXmlReader} that reads from the given {@code
  * XMLStreamReader}. The supplied stream reader must be in {@code
  * XMLStreamConstants.START_DOCUMENT} or {@code XMLStreamConstants.START_ELEMENT} state.
  *
  * @param reader the {@code XMLEventReader} to read from
  * @throws IllegalStateException if the reader is not at the start of a document or element
  */
 StaxStreamXMLReader(XMLStreamReader reader) {
   Assert.notNull(reader, "'reader' must not be null");
   int event = reader.getEventType();
   if (!(event == XMLStreamConstants.START_DOCUMENT
       || event == XMLStreamConstants.START_ELEMENT)) {
     throw new IllegalStateException("XMLEventReader not at start of document or element");
   }
   this.reader = reader;
 }
Ejemplo n.º 23
0
  public void testEncodingXmlStreamReader() throws Exception {
    TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM.reset();

    XMLStreamReader reader = null;
    XMLStreamWriter writer = null;
    ByteArrayOutputStream output = null;
    try {
      // enter text encoded with Latin1
      reader =
          context
              .getTypeConverter()
              .mandatoryConvertTo(
                  XMLStreamReader.class, TEST_XML_WITH_XML_HEADER_ISO_8859_1_AS_BYTE_ARRAY_STREAM);

      output = new ByteArrayOutputStream();
      // ensure UTF-8 encoding
      Exchange exchange = new DefaultExchange(context);
      exchange.setProperty(Exchange.CHARSET_NAME, UTF_8.name());
      writer =
          context.getTypeConverter().mandatoryConvertTo(XMLStreamWriter.class, exchange, output);
      // copy to writer
      while (reader.hasNext()) {
        reader.next();
        switch (reader.getEventType()) {
          case XMLEvent.START_DOCUMENT:
            writer.writeStartDocument();
            break;
          case XMLEvent.END_DOCUMENT:
            writer.writeEndDocument();
            break;
          case XMLEvent.START_ELEMENT:
            writer.writeStartElement(reader.getName().getLocalPart());
            break;
          case XMLEvent.CHARACTERS:
            writer.writeCharacters(reader.getText());
            break;
          case XMLEvent.END_ELEMENT:
            writer.writeEndElement();
            break;
          default:
            break;
        }
      }
    } finally {
      if (reader != null) {
        reader.close();
      }
      if (writer != null) {
        writer.close();
      }
    }
    assertNotNull(output);

    String result = new String(output.toByteArray(), UTF_8.name());

    assertEquals(TEST_XML, result);
  }
Ejemplo n.º 24
0
 @Override
 public String getPayloadAttributeValue(String attName) {
   if (lazySource.isPayloadStreamReader()) {
     XMLStreamReader reader = lazySource.readPayload();
     if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
       return reader.getAttributeValue(null, attName);
     }
   }
   return null;
 }
Ejemplo n.º 25
0
 @Override
 public String getPayloadAttributeValue(QName attName) {
   if (lazySource.isPayloadStreamReader()) {
     XMLStreamReader reader = lazySource.readPayload();
     if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) {
       return reader.getAttributeValue(attName.getNamespaceURI(), attName.getLocalPart());
     }
   }
   return null;
 }
Ejemplo n.º 26
0
 public static void skipToRequiredElement(XMLStreamReader reader, QName elementName)
     throws XMLStreamException {
   while (!reader.isStartElement() || !elementName.equals(reader.getName())) {
     if (reader.getEventType() == END_DOCUMENT) {
       throw new XMLParsingException(
           reader, "Required element " + elementName + " was not found.");
     }
     reader.next();
   }
 }
  /**
   * Parses the input stream containing the response body of the list queues request result and
   * populates the class data.
   *
   * @param serviceClient A {@link CloudQueueClient} object associated with the storage service.
   * @throws XMLStreamException If the input stream cannot be read or parsed as a list queues
   *     response.
   * @throws StorageException
   */
  public void parseResponse(final CloudQueueClient serviceClient)
      throws XMLStreamException, StorageException {
    final XMLStreamReader xmlr = Utility.createXMLStreamReaderFromStream(this.streamRef);
    String tempParseString = null;

    // Start document
    int eventType = xmlr.getEventType();
    xmlr.require(XMLStreamConstants.START_DOCUMENT, null, null);

    // 1. get enumerationResults Header
    eventType = xmlr.next();
    xmlr.require(XMLStreamConstants.START_ELEMENT, null, "EnumerationResults");

    // check if there are more events in the input stream
    while (xmlr.hasNext()) {
      eventType = xmlr.next();

      if (eventType == XMLStreamConstants.START_ELEMENT
          || eventType == XMLStreamConstants.END_ELEMENT) {
        final String name = xmlr.getName().toString();
        if (eventType == XMLStreamConstants.START_ELEMENT
            && name.equals(Constants.MAX_RESULTS_ELEMENT)) {
          tempParseString = Utility.readElementFromXMLReader(xmlr, Constants.MAX_RESULTS_ELEMENT);
          this.maxResults = Integer.parseInt(tempParseString);
        } else if (eventType == XMLStreamConstants.START_ELEMENT
            && name.equals(Constants.MARKER_ELEMENT)) {
          this.marker = Utility.readElementFromXMLReader(xmlr, Constants.MARKER_ELEMENT);
        } else if (eventType == XMLStreamConstants.START_ELEMENT
            && name.equals(Constants.NEXT_MARKER_ELEMENT)) {
          this.nextMarker = Utility.readElementFromXMLReader(xmlr, Constants.NEXT_MARKER_ELEMENT);
        } else if (eventType == XMLStreamConstants.START_ELEMENT
            && name.equals(Constants.PREFIX_ELEMENT)) {
          this.prefix = Utility.readElementFromXMLReader(xmlr, Constants.PREFIX_ELEMENT);
        } else if (eventType == XMLStreamConstants.START_ELEMENT
            && name.equals(QueueConstants.QUEUES_ELEMENT)) {
          try {
            this.queues = QueueDeserializationHelper.readQueues(xmlr, serviceClient);
          } catch (final URISyntaxException e) {
            throw new XMLStreamException(e);
          } catch (final ParseException e) {
            throw new XMLStreamException(e);
          }

          xmlr.require(XMLStreamConstants.END_ELEMENT, null, QueueConstants.QUEUES_ELEMENT);
          // eventType = xmlr.next();
        } else if (eventType == XMLStreamConstants.END_ELEMENT
            && "EnumerationResults".equals(name)) {
          break;
        }
      }
    }

    this.isParsed = true;
  }
  /**
   * Reads PageRanges from the XMLStreamReader, reader must be at Start element of PageRangeElement
   *
   * @param xmlr the XMLStreamReader to read from
   * @return the PageRange from the stream.
   * @throws XMLStreamException if there is an error parsing the stream
   * @throws ParseException if there is an error in parsing a date
   * @throws URISyntaxException if the uri is invalid
   * @throws StorageException
   */
  public static ArrayList<PageRange> readPageRanges(final XMLStreamReader xmlr)
      throws XMLStreamException, StorageException {
    int eventType = xmlr.getEventType();
    final ArrayList<PageRange> retRanges = new ArrayList<PageRange>();

    xmlr.require(XMLStreamConstants.START_ELEMENT, null, BlobConstants.PAGE_RANGE_ELEMENT);

    // check if there are more events in the input stream
    while (xmlr.hasNext() && BlobConstants.PAGE_RANGE_ELEMENT.equals(xmlr.getName().toString())) {
      long startOffset = -1;
      long endOffset = -1;

      // Read a Page Range
      while (xmlr.hasNext()) {
        eventType = xmlr.next();
        final String name = xmlr.getName().toString();

        if (eventType == XMLStreamConstants.START_ELEMENT) {
          if (name.equals(BlobConstants.START_ELEMENT)) {
            final String sizeString =
                Utility.readElementFromXMLReader(xmlr, BlobConstants.START_ELEMENT);
            startOffset = Long.parseLong(sizeString);
          } else if (name.equals(Constants.END_ELEMENT)) {
            final String sizeString = Utility.readElementFromXMLReader(xmlr, Constants.END_ELEMENT);
            endOffset = Long.parseLong(sizeString);
          } else {
            throw new StorageException(
                StorageErrorCodeStrings.INVALID_XML_DOCUMENT,
                "The response received is invalid or improperly formatted.",
                Constants.HeaderConstants.HTTP_UNUSED_306,
                null,
                null);
          }
        } else if (eventType == XMLStreamConstants.END_ELEMENT) {
          if (startOffset == -1 || endOffset == -1) {
            throw new StorageException(
                StorageErrorCodeStrings.INVALID_XML_DOCUMENT,
                "The response received is invalid or improperly formatted.",
                Constants.HeaderConstants.HTTP_UNUSED_306,
                null,
                null);
          }

          final PageRange pageRef = new PageRange(startOffset, endOffset);
          retRanges.add(pageRef);
          break;
        }
      }

      eventType = xmlr.next();
    }

    return retRanges;
  }
Ejemplo n.º 29
0
 public static Map<String, String> parse(
     XMLStreamReader streamReader, EndCondition endCondition, String... tags)
     throws XMLStreamException {
   Map<String, String> mapping = new HashMap<String, String>();
   while (streamReader.hasNext() && !endCondition.mustExit(streamReader)) {
     streamReader.next();
     if (XMLStreamReader.START_ELEMENT == streamReader.getEventType()) {
       String localPart = streamReader.getName().getLocalPart();
       for (String tag : tags) {
         if (tag.equals(localPart)) {
           streamReader.next();
           if (XMLStreamReader.CHARACTERS == streamReader.getEventType()) {
             mapping.put(tag, streamReader.getText());
           }
         }
       }
     }
   }
   return mapping;
 }
Ejemplo n.º 30
0
 public static void requireStartElement(XMLStreamReader xmlStream, QName elName) {
   if (xmlStream.getEventType() != START_ELEMENT) {
     String msg =
         "Found a '"
             + getEventTypeString(xmlStream.getEventType())
             + "' event, but one of the following elements is required at this position: '"
             + elName
             + "'.";
     throw new XMLParsingException(xmlStream, msg);
   }
   if (!elName.equals(xmlStream.getName())) {
     String msg =
         "Found a '"
             + xmlStream.getName()
             + "' element, but one of the following elements is required at this position: '"
             + elName
             + "'.";
     throw new XMLParsingException(xmlStream, msg);
   }
 }