Java Code Examples for javax.xml.stream.XMLStreamReader

The following examples show how to use javax.xml.stream.XMLStreamReader. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cosmo   Source File: DomReader.java    License: Apache License 2.0 6 votes vote down vote up
private static Element readElement(Document d, XMLStreamReader reader) throws XMLStreamException {
    Element e = null;

    String local = reader.getLocalName();
    String ns = reader.getNamespaceURI();
    if (ns != null && !ns.equals("")) {
        String prefix = reader.getPrefix();
        String qualified = prefix != null && !prefix.isEmpty() ? prefix + ":" + local : local;
        e = d.createElementNS(ns, qualified);
    } else {
        e = d.createElement(local);
    }

    for (int i = 0; i < reader.getAttributeCount(); i++) {
        Attr a = readAttribute(i, d, reader);
        if (a.getNamespaceURI() != null) {
            e.setAttributeNodeNS(a);
        } else {
            e.setAttributeNode(a);
        }
    }

    return e;
}
 
Example 2
Source Project: openjdk-jdk9   Source File: NamespaceTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testRootElementNamespace() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(rootElement)) {
                    Assert.assertTrue(sr.getNamespacePrefix(0).equals(prefix) && sr.getNamespaceURI(0).equals(namespaceURI));
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 3
Source Project: cosmo   Source File: DomReader.java    License: Apache License 2.0 6 votes vote down vote up
public static Node read(Reader in) throws ParserConfigurationException, XMLStreamException, IOException {
    XMLStreamReader reader = null;
    try {
        Document d = BUILDER_FACTORY.newDocumentBuilder().newDocument();
        reader = XML_INPUT_FACTORY.createXMLStreamReader(in);
        return readNode(d, reader);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (XMLStreamException e2) {
                LOG.warn("Unable to close XML reader", e2);
            }
        }
    }
}
 
Example 4
Source Project: flowable-engine   Source File: TaskXmlConverter.java    License: Apache License 2.0 6 votes vote down vote up
protected void convertCommonTaskAttributes(XMLStreamReader xtr, Task task) {
    task.setName(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_NAME));

    String isBlockingString = xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_IS_BLOCKING);
    if (StringUtils.isNotEmpty(isBlockingString)) {
        task.setBlocking(Boolean.valueOf(isBlockingString));
    }

    String isBlockingExpressionString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE,
        CmmnXmlConstants.ATTRIBUTE_IS_BLOCKING_EXPRESSION);
    if (StringUtils.isNotEmpty(isBlockingExpressionString)) {
        task.setBlockingExpression(isBlockingExpressionString);
    }

    String isAsyncString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE,
        CmmnXmlConstants.ATTRIBUTE_IS_ASYNCHRONOUS);
    if (StringUtils.isNotEmpty(isAsyncString)) {
        task.setAsync(Boolean.valueOf(isAsyncString.toLowerCase()));
    }

    String isExclusiveString = xtr.getAttributeValue(CmmnXmlConstants.FLOWABLE_EXTENSIONS_NAMESPACE,
        CmmnXmlConstants.ATTRIBUTE_IS_EXCLUSIVE);
    if (StringUtils.isNotEmpty(isExclusiveString)) {
        task.setExclusive(Boolean.valueOf(isExclusiveString));
    }
}
 
Example 5
public static OverloadSecurityIndex fromXml(String contingencyId, XMLStreamReader xmlsr) throws XMLStreamException {
    String text = null;
    while (xmlsr.hasNext()) {
        int eventType = xmlsr.next();
        switch (eventType) {
            case XMLEvent.CHARACTERS:
                text = xmlsr.getText();
                break;
            case XMLEvent.END_ELEMENT:
                if ("fx".equals(xmlsr.getLocalName())) {
                    return new OverloadSecurityIndex(contingencyId, Double.parseDouble(text));
                }
                break;
            default:
                break;
        }
    }
    throw new AssertionError("fx element not found");
}
 
Example 6
Source Project: jdk8u60   Source File: XMLStreamFilterImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** Creates a new instance of XMLStreamFilterImpl */

    public XMLStreamFilterImpl(XMLStreamReader reader,StreamFilter filter){
        fStreamReader = reader;
        this.fStreamFilter = filter;

        //this is debatable to initiate at an acceptable event,
        //but it's neccessary in order to pass the TCK and yet avoid skipping element
        try {
            if (fStreamFilter.accept(fStreamReader)) {
                fEventAccepted = true;
            } else {
                findNextEvent();
            }
        }catch(XMLStreamException xs){
            System.err.println("Error while creating a stream Filter"+xs);
        }
    }
 
Example 7
Source Project: openjdk-jdk9   Source File: NamespaceTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testChildElementNamespace() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        xif.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        InputStream is = new java.io.ByteArrayInputStream(getXML().getBytes());
        XMLStreamReader sr = xif.createXMLStreamReader(is);
        while (sr.hasNext()) {
            int eventType = sr.next();
            if (eventType == XMLStreamConstants.START_ELEMENT) {
                if (sr.getLocalName().equals(childElement)) {
                    QName qname = sr.getName();
                    Assert.assertTrue(qname.getPrefix().equals(prefix) && qname.getNamespaceURI().equals(namespaceURI)
                            && qname.getLocalPart().equals(childElement));
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example 8
/**
 * We don't really expect this to be used, but just to satisfy
 * the {@link Header} contract.
 *
 * So this is rather slow.
 */
private void parseAttributes() {
    try {
        XMLStreamReader reader = readHeader();

        attributes = new FinalArrayList<Attribute>();

        for (int i = 0; i < reader.getAttributeCount(); i++) {
            final String localName = reader.getAttributeLocalName(i);
            final String namespaceURI = reader.getAttributeNamespace(i);
            final String value = reader.getAttributeValue(i);

            attributes.add(new Attribute(namespaceURI,localName,value));
        }
    } catch (XMLStreamException e) {
        throw new WebServiceException("Unable to read the attributes for {"+nsUri+"}"+localName+" header",e);
    }
}
 
Example 9
Source Project: lams   Source File: MappingConfigParser.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse the <mapping> element
 * @param reader
 * @return
 * @throws XMLStreamException
 */
public List<MappingModuleEntry> parse(XMLStreamReader reader) throws XMLStreamException
{
   List<MappingModuleEntry> entries = new ArrayList<MappingModuleEntry>();
   while (reader.hasNext() && reader.nextTag() != END_ELEMENT)
   {
      final Element element = Element.forName(reader.getLocalName());
      MappingModuleEntry entry = null;
      if (element.equals(Element.MAPPING_MODULE))
      {
         entry = getEntry(reader);
      }
      else
         throw StaxParserUtil.unexpectedElement(reader);
      entries.add(entry);
   }
   return entries;
}
 
Example 10
Source Project: cloud-odata-java   Source File: XmlEntityConsumer.java    License: Apache License 2.0 6 votes vote down vote up
private XMLStreamReader createStaxReader(final Object content) throws XMLStreamException, EntityProviderException {
  XMLInputFactory factory = XMLInputFactory.newInstance();
  factory.setProperty(XMLInputFactory.IS_VALIDATING, false);
  factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);

  if (content == null) {
    throw new EntityProviderException(EntityProviderException.ILLEGAL_ARGUMENT
        .addContent("Got not supported NULL object as content to de-serialize."));
  }

  if (content instanceof InputStream) {
    XMLStreamReader streamReader = factory.createXMLStreamReader((InputStream) content, DEFAULT_CHARSET);
    // verify charset encoding set in content is supported (if not set UTF-8 is used as defined in 'http://www.w3.org/TR/2008/REC-xml-20081126/')
    String characterEncodingInContent = streamReader.getCharacterEncodingScheme();
    if (characterEncodingInContent != null && !DEFAULT_CHARSET.equalsIgnoreCase(characterEncodingInContent)) {
      throw new EntityProviderException(EntityProviderException.UNSUPPORTED_CHARACTER_ENCODING.addContent(characterEncodingInContent));
    }
    return streamReader;
  }
  throw new EntityProviderException(EntityProviderException.ILLEGAL_ARGUMENT
      .addContent("Found not supported content of class '" + content.getClass() + "' to de-serialize."));
}
 
Example 11
Source Project: ironjacamar   Source File: JCA10TestCase.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Read
 * @throws Exception In case of an error
 */
@Test
public void testRead() throws Exception
{
   RaParser parser = new RaParser();

   InputStream is = JCA10TestCase.class.getClassLoader().getResourceAsStream("../../resources/test/spec/ra-1.0.xml");
   assertNotNull(is);

   XMLInputFactory inputFactory = XMLInputFactory.newInstance();
   inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);

   XMLStreamReader xsr = inputFactory.createXMLStreamReader(is);

   Connector c = parser.parse(xsr);
   assertNotNull(c);

   is.close();
   checkConnector(c);
}
 
Example 12
private static boolean getBoolProp(XMLStreamReader r, String n) {
    try {
        Object o = r.getProperty(n);
        if(o instanceof Boolean)    return (Boolean)o;
        return false;
    } catch (Exception e) {
        // be defensive against broken StAX parsers since javadoc is not clear
        // about when an error happens
        return false;
    }
}
 
Example 13
@Override
public XMLStreamReader doCreate(String systemId, InputStream in, boolean rejectDTDs) {
    try {
        return xif.get().createXMLStreamReader(systemId,in);
    } catch (XMLStreamException e) {
        throw new XMLReaderException("stax.cantCreate",e);
    }
}
 
Example 14
Source Project: che   Source File: XMLTree.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Searches for the element start right bound index. TODO respect element attributes text content
 * while checking '<'
 */
private int elementRight(int left, XMLStreamReader reader) {
  int rightIdx = lastIndexOf(xml, '>', reader.getLocation().getCharacterOffset());
  int leftIdx = lastIndexOf(xml, '<', rightIdx);
  while (leftIdx > left) {
    rightIdx = lastIndexOf(xml, '>', rightIdx - 1);
    leftIdx = lastIndexOf(xml, '<', rightIdx);
  }
  return rightIdx;
}
 
Example 15
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;
}
 
Example 16
public boolean bindingOperationOutputElements(EditableWSDLBoundOperation operation, XMLStreamReader reader) {
    for (WSDLParserExtension e : extensions) {
        if (e.bindingOperationOutputElements(operation, reader)) {
            return true;
        }
    }
    XMLStreamReaderUtil.skipElement(reader);
    return true;
}
 
Example 17
private void storeAttributes(XMLStreamReader reader) {
    int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        storeAttribute(reader.getAttributePrefix(i), reader.getAttributeNamespace(i), reader.getAttributeLocalName(i),
                reader.getAttributeType(i), reader.getAttributeValue(i));
    }
}
 
Example 18
Source Project: pentaho-kettle   Source File: XMLFormatter.java    License: Apache License 2.0 5 votes vote down vote up
public StartElementBuffer( XMLStreamReader rd ) {
  prefix = rd.getPrefix();
  namespace = rd.getNamespaceURI();
  localName = rd.getLocalName();
  for ( int i = 0; i < rd.getAttributeCount(); i++ ) {
    attrBuffer.add( new AttrBuffer( rd, i ) );
  }
}
 
Example 19
Source Project: secure-data-service   Source File: XmiReader.java    License: Apache License 2.0 5 votes vote down vote up
protected static final List<Attribute> readClassifierDotFeature(final XMLStreamReader reader)
        throws XMLStreamException {
    assertName(XmiElementName.CLASSIFIER_DOT_FEATURE, reader);
    final List<Attribute> attributes = new LinkedList<Attribute>();
    while (reader.hasNext()) {
        reader.next();
        switch (reader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT: {
                if (match(XmiElementName.ATTRIBUTE, reader)) {
                    attributes.add(assertNotNull(readAttribute(reader)));
                } else if (match(XmiElementName.OPERATION, reader)) {
                    skipElement(reader, false);
                } else {
                    throw new AssertionError(reader.getLocalName());
                }
                break;
            }
            case XMLStreamConstants.END_ELEMENT: {
                assertName(XmiElementName.CLASSIFIER_DOT_FEATURE, reader);
                return assertNotNull(attributes);
            }
            case XMLStreamConstants.CHARACTERS: {
                // Ignore.
                break;
            }
            default: {
                throw new AssertionError(reader.getEventType());
            }
        }
    }
    throw new AssertionError();
}
 
Example 20
Source Project: davmail   Source File: ResolveNamesMethod.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void handlePhoneNumbers(XMLStreamReader reader, Item responseItem) throws XMLStreamException {
    while (reader.hasNext() && !XMLStreamUtil.isEndTag(reader, "PhoneNumbers")) {
        reader.next();
        if (XMLStreamUtil.isStartTag(reader)) {
            String tagLocalName = reader.getLocalName();
            if ("Entry".equals(tagLocalName)) {
                String key = getAttributeValue(reader, "Key");
                String value = XMLStreamUtil.getElementText(reader);
                responseItem.put(key, value);
            }
        }
    }
}
 
Example 21
Source Project: cloud-odata-java   Source File: XmlPropertyConsumerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void readIntegerPropertyWithEmptyMapping() throws Exception {
  String xml = "<Age xmlns=\"" + Edm.NAMESPACE_D_2007_08 + "\">67</Age>";
  XMLStreamReader reader = createReaderForTest(xml, true);
  final EdmProperty property = (EdmProperty) MockFacade.getMockEdm().getEntityType("RefScenario", "Employee").getProperty("Age");

  Map<String, Object> typeMappings = new HashMap<String, Object>();
  Map<String, Object> resultMap = new XmlPropertyConsumer().readProperty(reader, property, false, typeMappings);

  assertEquals(Integer.valueOf(67), resultMap.get("Age"));
}
 
Example 22
public static String getElementText(XMLStreamReader reader) {
    try {
        return reader.getElementText();
    } catch (XMLStreamException e) {
        throw wrapException(e);
    }
}
 
Example 23
public boolean portElements(EditableWSDLPort port, XMLStreamReader reader) {
    for (WSDLParserExtension e : extensions) {
        if(e.portElements(port,reader))
            return true;
    }
    //extension is not understood by any WSDlParserExtension
    //Check if it must be understood.
    if(isRequiredExtension(reader)) {
        port.addNotUnderstoodExtension(reader.getName(),getLocator(reader));
    }
    XMLStreamReaderUtil.skipElement(reader);
    return true;
}
 
Example 24
protected static void failWithLocalName(String key, XMLStreamReader reader, String arg) {
    throw new ServerRtException(
            key,
            reader.getLocation().getLineNumber(),
            reader.getLocalName(),
            arg);
}
 
Example 25
@Override
public boolean bindingOperationFaultElements(final EditableWSDLBoundFault fault, final XMLStreamReader reader) {
    LOGGER.entering();
    final boolean result = processSubelement(fault, reader, getHandlers4BindingFaultOpMap());
    LOGGER.exiting(result);
    return result;
}
 
Example 26
Source Project: cxf   Source File: StaxUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCopy() throws Exception {

    // do the stream copying
    String soapMessage = "./resources/headerSoapReq.xml";
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(getTestStream(soapMessage));
    XMLStreamWriter writer = StaxUtils.createXMLStreamWriter(baos);
    StaxUtils.copy(reader, writer);
    writer.flush();
    baos.flush();

    // write output to a string
    String output = baos.toString();
    baos.close();

    // re-read the input xml doc to a string
    String input = IOUtils.toString(getTestStream(soapMessage));

    // seach for the first begin of "<soap:Envelope" to escape the apache licenses header
    int beginIndex = input.indexOf("<soap:Envelope");
    input = input.substring(beginIndex);
    beginIndex = output.indexOf("<soap:Envelope");
    output = output.substring(beginIndex);

    output = output.replace("\r\n", "\n");
    input = input.replace("\r\n", "\n");

    // compare the input and output string
    assertEquals(input, output);
}
 
Example 27
Source Project: java-client-api   Source File: BasicJavaClientREST.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Convert XMLStreamReader To String
 * 
 * @param XMLStreamReader
 * @return String
 * @throws XMLStreamException
 *           , TransformerException, IOException,
 *           ParserConfigurationException, SAXException
 */
public String convertXMLStreamReaderToString(XMLStreamReader reader) throws XMLStreamException, TransformerException, IOException, ParserConfigurationException, SAXException {
  String str = null;
  while (reader.hasNext())
  {
    reader.next();
    int a = reader.getEventType();
    if (reader.hasText())
      if (reader.getText() != "null")
        str = str + reader.getText().trim();
  }
  return str;
}
 
Example 28
public void readRequest(Message msg, Object[] args) throws JAXBException, XMLStreamException {
    if (dynamicWrapper) {
        readWrappedRequest(msg, args);
    } else {
        if (parts.length>0) {
            if (!msg.hasPayload()) {
                throw new WebServiceException("No payload. Expecting payload with "+wrapperName+" element");
            }
            XMLStreamReader reader = msg.readPayload();
            XMLStreamReaderUtil.verifyTag(reader, wrapperName);
            Object wrapperBean = wrapper.unmarshal(reader, (msg.getAttachments() != null) ?
                    new AttachmentUnmarshallerImpl(msg.getAttachments()): null);

            try {
                for (PartBuilder part : parts) {
                    part.readRequest(args,wrapperBean);
                }
            } catch (DatabindingException e) {
                // this can happen when the set method throw a checked exception or something like that
                throw new WebServiceException(e);    // TODO:i18n
            }

            // we are done with the body
            reader.close();
            XMLStreamReaderFactory.recycle(reader);
        } else {
            msg.consume();
        }
    }
}
 
Example 29
private static void parsePath(final XMLStreamReader reader, final boolean include, final List<FilterSpecification> filters)
        throws XMLStreamException {
    String path = null;
    final Set<Attribute> required = EnumSet.of(Attribute.PATH);
    final int count = reader.getAttributeCount();
    for (int i = 0; i < count; i++) {
        final Attribute attribute = Attribute.of(reader.getAttributeName(i));
        required.remove(attribute);
        switch (attribute) {
            case PATH:
                path = reader.getAttributeValue(i);
                break;
            default:
                throw unexpectedContent(reader);
        }
    }
    if (!required.isEmpty()) {
        throw missingAttributes(reader.getLocation(), required);
    }

    final boolean literal = path.indexOf('*') == -1 && path.indexOf('?') == -1;
    if (literal) {
        if (path.charAt(path.length() - 1) == '/') {
            filters.add(new FilterSpecification(PathFilters.isChildOf(path), include));
        } else {
            filters.add(new FilterSpecification(PathFilters.is(path), include));
        }
    } else {
        filters.add(new FilterSpecification(PathFilters.match(path), include));
    }

    // consume remainder of element
    parseNoContent(reader);
}
 
Example 30
Source Project: activiti6-boot2   Source File: MessageFlowParser.java    License: Apache License 2.0 5 votes vote down vote up
public void parse(XMLStreamReader xtr, BpmnModel model) throws Exception {
  String id = xtr.getAttributeValue(null, ATTRIBUTE_ID);
  if (StringUtils.isNotEmpty(id)) {
    MessageFlow messageFlow = new MessageFlow();
    messageFlow.setId(id);

    String name = xtr.getAttributeValue(null, ATTRIBUTE_NAME);
    if (StringUtils.isNotEmpty(name)) {
      messageFlow.setName(name);
    }

    String sourceRef = xtr.getAttributeValue(null, ATTRIBUTE_FLOW_SOURCE_REF);
    if (StringUtils.isNotEmpty(sourceRef)) {
      messageFlow.setSourceRef(sourceRef);
    }

    String targetRef = xtr.getAttributeValue(null, ATTRIBUTE_FLOW_TARGET_REF);
    if (StringUtils.isNotEmpty(targetRef)) {
      messageFlow.setTargetRef(targetRef);
    }

    String messageRef = xtr.getAttributeValue(null, ATTRIBUTE_MESSAGE_REF);
    if (StringUtils.isNotEmpty(messageRef)) {
      messageFlow.setMessageRef(messageRef);
    }

    model.addMessageFlow(messageFlow);
  }
}