javax.xml.stream.XMLEventReader Java Examples

The following examples show how to use javax.xml.stream.XMLEventReader. 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 File: AbstractMarshaller.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Template method for handling {@code StaxSource}s.
 * <p>This implementation delegates to {@code unmarshalXmlStreamReader} or
 * {@code unmarshalXmlEventReader}.
 * @param staxSource the {@code StaxSource}
 * @return the object graph
 * @throws XmlMappingException if the given source cannot be mapped to an object
 */
protected Object unmarshalStaxSource(Source staxSource) throws XmlMappingException {
	XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(staxSource);
	if (streamReader != null) {
		return unmarshalXmlStreamReader(streamReader);
	}
	else {
		XMLEventReader eventReader = StaxUtils.getXMLEventReader(staxSource);
		if (eventReader != null) {
			return unmarshalXmlEventReader(eventReader);
		}
		else {
			throw new IllegalArgumentException("StaxSource contains neither XMLStreamReader nor XMLEventReader");
		}
	}
}
 
Example #2
Source File: BufferedStringsTable.java    From excel-streaming-reader with Apache License 2.0 6 votes vote down vote up
@Override
public void readFrom(InputStream is) throws IOException {
  try {
    XMLEventReader xmlEventReader = StaxHelper.newXMLInputFactory().createXMLEventReader(is);

    while(xmlEventReader.hasNext()) {
      XMLEvent xmlEvent = xmlEventReader.nextEvent();

      if(xmlEvent.isStartElement() && xmlEvent.asStartElement().getName().getLocalPart().equals("si")) {
        list.add(parseCT_Rst(xmlEventReader));
      }
    }
  } catch(XMLStreamException e) {
    throw new IOException(e);
  }
}
 
Example #3
Source File: HttpClientParser.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected HttpClientConfig instantiateElement(XMLEventReader xmlEventReader, StartElement element) throws ParsingException {
    final HttpClientConfig config = new HttpClientConfig();

    final Boolean allowAnyHostname = StaxParserUtil.getBooleanAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_ALLOW_ANY_HOSTNAME);
    config.setAllowAnyHostname(allowAnyHostname == null ? false : allowAnyHostname);
    config.setClientKeystore(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_CLIENT_KEYSTORE));
    config.setClientKeystorePassword(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_CLIENT_KEYSTORE_PASSWORD));
    final Integer connPoolSize = StaxParserUtil.getIntegerAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_CONNECTION_POOL_SIZE);
    config.setConnectionPoolSize(connPoolSize == null ? 0 : connPoolSize);
    final Boolean disableTrustManager = StaxParserUtil.getBooleanAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_DISABLE_TRUST_MANAGER);
    config.setDisableTrustManager(disableTrustManager == null ? false : disableTrustManager);
    config.setProxyUrl(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_PROXY_URL));
    config.setTruststore(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_TRUSTSTORE));
    config.setTruststorePassword(StaxParserUtil.getAttributeValueRP(element, KeycloakSamlAdapterV1QNames.ATTR_TRUSTSTORE_PASSWORD));

    return config;
}
 
Example #4
Source File: AbstractMarshaller.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Template method for handling {@code StaxSource}s.
 * <p>This implementation delegates to {@code unmarshalXmlStreamReader} or
 * {@code unmarshalXmlEventReader}.
 * @param staxSource the {@code StaxSource}
 * @return the object graph
 * @throws XmlMappingException if the given source cannot be mapped to an object
 */
protected Object unmarshalStaxSource(Source staxSource) throws XmlMappingException {
	XMLStreamReader streamReader = StaxUtils.getXMLStreamReader(staxSource);
	if (streamReader != null) {
		return unmarshalXmlStreamReader(streamReader);
	}
	else {
		XMLEventReader eventReader = StaxUtils.getXMLEventReader(staxSource);
		if (eventReader != null) {
			return unmarshalXmlEventReader(eventReader);
		}
		else {
			throw new IllegalArgumentException("StaxSource contains neither XMLStreamReader nor XMLEventReader");
		}
	}
}
 
Example #5
Source File: SAMLSPSSODescriptorParser.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected SPSSODescriptorType instantiateElement(XMLEventReader xmlEventReader, StartElement element) throws ParsingException {
    List<String> protocolEnum = StaxParserUtil.getRequiredStringListAttributeValue(element, SAMLMetadataQNames.ATTR_PROTOCOL_SUPPORT_ENUMERATION);
    SPSSODescriptorType descriptor = new SPSSODescriptorType(protocolEnum);

    // Role descriptor optional arguments
    parseOptionalArguments(element, descriptor);

    // SPSSODecsriptor optional attributes
    Boolean authnRequestsSigned = StaxParserUtil.getBooleanAttributeValue(element, SAMLMetadataQNames.ATTR_AUTHN_REQUESTS_SIGNED);
    if (authnRequestsSigned != null) {
        descriptor.setAuthnRequestsSigned(authnRequestsSigned);
    }

    Boolean wantAssertionSigned = StaxParserUtil.getBooleanAttributeValue(element, SAMLMetadataQNames.ATTR_WANT_ASSERTIONS_SIGNED);
    if (wantAssertionSigned != null) {
        descriptor.setWantAssertionsSigned(wantAssertionSigned);
    }

    return descriptor;
}
 
Example #6
Source File: SAMLAuthnAuthorityDescriptorParser.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void processSubElement(XMLEventReader xmlEventReader, AuthnAuthorityDescriptorType target, SAMLMetadataQNames element, StartElement elementDetail) throws ParsingException {
    switch (element) {
    case AUTHN_QUERY_SERVICE:
        target.addAuthnQueryService(SAMLAuthnQueryServiceParser.getInstance().parse(xmlEventReader));
        break;

    case ASSERTION_ID_REQUEST_SERVICE:
        target.addAssertionIDRequestService(SAMLAssertinIDRequestServiceParser.getInstance().parse(xmlEventReader));
        break;

    case NAMEID_FORMAT:
        StaxParserUtil.advance(xmlEventReader);
        target.addNameIDFormat(StaxParserUtil.getElementText(xmlEventReader));
        break;

    default:
        super.processSubElement(xmlEventReader, target, element, elementDetail);
    }
}
 
Example #7
Source File: XmlPolicyModelUnmarshaller.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method checks if the storage type is supported and transforms it to XMLEventReader instance which is then returned.
 * Throws PolicyException if the transformation is not succesfull or if the storage type is not supported.
 *
 * @param storage An XMLEventReader instance.
 * @return The storage cast to an XMLEventReader.
 * @throws PolicyException If the XMLEventReader cast failed.
 */
private XMLEventReader createXMLEventReader(final Object storage)
        throws PolicyException {
    if (storage instanceof XMLEventReader) {
        return (XMLEventReader) storage;
    }
    else if (!(storage instanceof Reader)) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0022_STORAGE_TYPE_NOT_SUPPORTED(storage.getClass().getName())));
    }

    try {
        return XMLInputFactory.newInstance().createXMLEventReader((Reader) storage);
    } catch (XMLStreamException e) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0014_UNABLE_TO_INSTANTIATE_READER_FOR_STORAGE(), e));
    }

}
 
Example #8
Source File: Bug6489890.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test0() {
    try {
        XMLInputFactory xif = XMLInputFactory.newInstance();

        XMLStreamReader xsr = xif.createXMLStreamReader(getClass().getResource("sgml.xml").toString(), getClass().getResourceAsStream("sgml.xml"));

        XMLEventReader xer = xif.createXMLEventReader(xsr);

        Assert.assertTrue(xer.peek().getEventType() == XMLEvent.START_DOCUMENT);
        Assert.assertTrue(xer.peek() == xer.nextEvent());
        xsr.close();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
 
Example #9
Source File: SAML11ParserUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Parse Attribute value
 *
 * @param xmlEventReader
 *
 * @return
 *
 * @throws ParsingException
 */
public static Object parseAttributeValue(XMLEventReader xmlEventReader) throws ParsingException {
    StartElement startElement = StaxParserUtil.getNextStartElement(xmlEventReader);
    StaxParserUtil.validate(startElement, JBossSAMLConstants.ATTRIBUTE_VALUE.get());

    Attribute type = startElement.getAttributeByName(new QName(JBossSAMLURIConstants.XSI_NSURI.get(), "type", "xsi"));
    if (type == null) {
        return StaxParserUtil.getElementText(xmlEventReader);
    }

    String typeValue = StaxParserUtil.getAttributeValue(type);
    if (typeValue.contains(":string")) {
        return StaxParserUtil.getElementText(xmlEventReader);
    }

    throw logger.parserUnknownXSI(typeValue);
}
 
Example #10
Source File: RsaKeyValueParser.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
protected void processSubElement(XMLEventReader xmlEventReader, RSAKeyValueType target, XmlDSigQNames element, StartElement elementDetail) throws ParsingException {
    String text;
    switch (element) {
        case MODULUS:
            StaxParserUtil.advance(xmlEventReader);
            text = StaxParserUtil.getElementText(xmlEventReader);
            target.setModulus(text.getBytes(GeneralConstants.SAML_CHARSET));
            break;

        case EXPONENT:
            StaxParserUtil.advance(xmlEventReader);
            text = StaxParserUtil.getElementText(xmlEventReader);
            target.setExponent(text.getBytes(GeneralConstants.SAML_CHARSET));
            break;

        default:
            throw LOGGER.parserUnknownTag(StaxParserUtil.getElementName(elementDetail), elementDetail.getLocation());
    }
}
 
Example #11
Source File: XmlPolicyModelUnmarshaller.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Method checks if the storage type is supported and transforms it to XMLEventReader instance which is then returned.
 * Throws PolicyException if the transformation is not succesfull or if the storage type is not supported.
 *
 * @param storage An XMLEventReader instance.
 * @return The storage cast to an XMLEventReader.
 * @throws PolicyException If the XMLEventReader cast failed.
 */
private XMLEventReader createXMLEventReader(final Object storage)
        throws PolicyException {
    if (storage instanceof XMLEventReader) {
        return (XMLEventReader) storage;
    }
    else if (!(storage instanceof Reader)) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0022_STORAGE_TYPE_NOT_SUPPORTED(storage.getClass().getName())));
    }

    try {
        return XMLInputFactory.newInstance().createXMLEventReader((Reader) storage);
    } catch (XMLStreamException e) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0014_UNABLE_TO_INSTANTIATE_READER_FOR_STORAGE(), e));
    }

}
 
Example #12
Source File: AbstractDOMDocumentSerializer.java    From jettison with Apache License 2.0 6 votes vote down vote up
public void serialize(Element el) throws IOException {
	if (output == null)
		throw new IllegalStateException("OutputStream cannot be null");

	try {
		DOMSource source = new DOMSource(el);
		XMLInputFactory readerFactory = XMLInputFactory.newInstance();
		XMLStreamReader streamReader = readerFactory
				.createXMLStreamReader(source);
		XMLEventReader eventReader = readerFactory
				.createXMLEventReader(streamReader);

		XMLEventWriter eventWriter = writerFactory
				.createXMLEventWriter(output);
		eventWriter.add(eventReader);
		eventWriter.close();
	} catch (XMLStreamException ex) {
		IOException ioex = new IOException("Cannot serialize: " + el);
		ioex.initCause(ex);
		throw ioex;
	}
}
 
Example #13
Source File: StaxUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return the {@link XMLEventReader} for the given StAX Source.
 * @param source a JAXP 1.4 {@link StAXSource}
 * @return the {@link XMLEventReader}
 * @throws IllegalArgumentException if {@code source} isn't a JAXP 1.4 {@link StAXSource}
 * or custom StAX Source
 */
@Nullable
public static XMLEventReader getXMLEventReader(Source source) {
	if (source instanceof StAXSource) {
		return ((StAXSource) source).getXMLEventReader();
	}
	else if (source instanceof StaxSource) {
		return ((StaxSource) source).getXMLEventReader();
	}
	else {
		throw new IllegalArgumentException("Source '" + source + "' is neither StaxSource nor StAXSource");
	}
}
 
Example #14
Source File: SearchHandle.java    From java-client-api with Apache License 2.0 5 votes vote down vote up
private void handleSimilar(XMLEventReader reader, StartElement element)
  throws XMLStreamException
{
  if (currSummary.similarUris == null) {
    currSummary.similarUris = new ArrayList<>();
  }
  currSummary.similarUris.add(reader.getElementText());
}
 
Example #15
Source File: ExternalAttachmentsUnmarshaller.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void processStartTag(final StartElement element, final StartElement parent,
        final XMLEventReader reader, final Map<URI, Policy> map)
        throws PolicyException {
    try {
        final QName name = element.getName();
        if (parent == null) {
            if (!name.equals(POLICIES)) {
                throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<Policies>", name, element.getLocation())));
            }
        } else {
            final QName parentName = parent.getName();
            if (parentName.equals(POLICIES)) {
                if (!name.equals(POLICY_ATTACHMENT)) {
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<PolicyAttachment>", name, element.getLocation())));
                }
            } else if (parentName.equals(POLICY_ATTACHMENT)) {
                if (name.equals(POLICY)) {
                    readPolicy(reader);
                    return;
                } else if (!name.equals(APPLIES_TO)) {
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<AppliesTo> or <Policy>", name, element.getLocation())));
                }
            } else if (parentName.equals(APPLIES_TO)) {
                if (!name.equals(URI)) {
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<URI>", name, element.getLocation())));
                }
            } else {
                throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0090_UNEXPECTED_ELEMENT(name, element.getLocation())));
            }
        }
        reader.nextEvent();
        this.unmarshal(reader, element);
    } catch (XMLStreamException e) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0088_FAILED_PARSE(element.getLocation()), e));
    }
}
 
Example #16
Source File: ListBasedXMLEventReaderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private List<XMLEvent> readEvents(String xml) throws XMLStreamException {
	XMLEventReader reader = this.inputFactory.createXMLEventReader(new StringReader(xml));
	List<XMLEvent> events = new ArrayList<>();
	while (reader.hasNext()) {
		events.add(reader.nextEvent());
	}
	return events;
}
 
Example #17
Source File: RestXMLResponseParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private MessagePart parseChildMessage(XMLEventReader reader) throws XMLStreamException {
    MessagePart msg = new MessagePart();
    int level = 0;
    while (reader.hasNext() && (level > -1)) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            if (level++ == 0) {
                StartElement element = event.asStartElement();
                String elementName = element.getName().getLocalPart();
                if (ENTRY.equals(elementName)) {
                    Map<String, String> m = getMapEntry(element);
                    String key = m.get("key");
                    String value = m.get("value");
                    switch (key) {
                        case "message":
                            msg.setMessage(value);
                            break;
                        case "properties":
                            msg.props = parseProperties(reader);
                            break;
                        case "children":
                            msg.children = parseChildrenMessages(reader);
                            break;
                    }
                }
            }
        } else {
            level--;
        }
    }
    return msg;
}
 
Example #18
Source File: SAMLAuthnAuthorityDescriptorParser.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected AuthnAuthorityDescriptorType instantiateElement(XMLEventReader xmlEventReader, StartElement element) throws ParsingException {
    List<String> protocolEnum = StaxParserUtil.getRequiredStringListAttributeValue(element, SAMLMetadataQNames.ATTR_PROTOCOL_SUPPORT_ENUMERATION);
    AuthnAuthorityDescriptorType descriptor = new AuthnAuthorityDescriptorType(protocolEnum);

    parseOptionalArguments(element, descriptor);

    return descriptor;
}
 
Example #19
Source File: PooledUnmarshaller.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Same as {@link #unmarshal(XMLEventReader, TransformVersion)}, but delegating to the unmarshaller
 * methods returning a JAXB element instead than the one returning the object.
 */
private <T> JAXBElement<T> unmarshal(XMLEventReader input, final TransformVersion version, final Class<T> declaredType)
        throws XMLStreamException, JAXBException
{
    input = new TransformingReader(input, version);
    final Context context = begin();
    final JAXBElement<T> object;
    try {
        object = unmarshaller.unmarshal(input, declaredType);
    } finally {
        context.finish();
    }
    input.close();              // Despite its name, this method does not close the underlying input stream.
    return object;
}
 
Example #20
Source File: XStreamMarshaller.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected Object unmarshalXmlEventReader(XMLEventReader eventReader) throws XmlMappingException {
	try {
		XMLStreamReader streamReader = StaxUtils.createEventStreamReader(eventReader);
		return unmarshalXmlStreamReader(streamReader);
	}
	catch (XMLStreamException ex) {
		throw convertXStreamException(ex, false);
	}
}
 
Example #21
Source File: ExternalAttachmentsUnmarshaller.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static Map<URI, Policy> unmarshal(final Reader source) throws PolicyException {
    LOGGER.entering(source);
    try {
        XMLEventReader reader = XML_INPUT_FACTORY.get().createXMLEventReader(source);
        ExternalAttachmentsUnmarshaller instance = new ExternalAttachmentsUnmarshaller();
        final Map<URI, Policy> map = instance.unmarshal(reader, null);
        LOGGER.exiting(map);
        return Collections.unmodifiableMap(map);
    } catch (XMLStreamException ex) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0086_FAILED_CREATE_READER(source)), ex);
    }
}
 
Example #22
Source File: RestXMLResponseParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Parse implementation for XML REST response.
 * <p>
 * This implementation is based on Stax parser. Currently REST admin service
 * does not use any schema for XML responses so this implementation is based
 * on the code that generates the response on server side.
 * <p>
 * @param in {@link InputStream} with XML REST response.
 * @return Response returned by REST administration service.
 */
@Override
public RestActionReport parse(InputStream in) {
    //System.out.println("FACTORY: " + factory);
    try {
        XMLEventReader reader = factory.createFilteredReader(factory.createXMLEventReader(in), filter);
        if (reader.hasNext() && MAP.equals(reader.nextEvent().asStartElement().getName().getLocalPart())) {
            return parseReport(reader);
        } else {
            return null;
        }
    } catch (XMLStreamException ex) {
        throw new PayaraIdeException("Unable to parse XML Rest response.", ex);
    }
}
 
Example #23
Source File: SkipDTDTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void runReader(XMLInputFactory factory, int offset) throws XMLStreamException {
    StringReader stringReader = new StringReader(createXMLDocument(offset));
    XMLEventReader reader = factory.createXMLEventReader(stringReader);

    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        System.out.println("Event Type: " + event.getEventType());
    }
}
 
Example #24
Source File: ExternalAttachmentsUnmarshaller.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void processStartTag(final StartElement element, final StartElement parent,
        final XMLEventReader reader, final Map<URI, Policy> map)
        throws PolicyException {
    try {
        final QName name = element.getName();
        if (parent == null) {
            if (!name.equals(POLICIES)) {
                throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<Policies>", name, element.getLocation())));
            }
        } else {
            final QName parentName = parent.getName();
            if (parentName.equals(POLICIES)) {
                if (!name.equals(POLICY_ATTACHMENT)) {
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<PolicyAttachment>", name, element.getLocation())));
                }
            } else if (parentName.equals(POLICY_ATTACHMENT)) {
                if (name.equals(POLICY)) {
                    readPolicy(reader);
                    return;
                } else if (!name.equals(APPLIES_TO)) {
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<AppliesTo> or <Policy>", name, element.getLocation())));
                }
            } else if (parentName.equals(APPLIES_TO)) {
                if (!name.equals(URI)) {
                    throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0089_EXPECTED_ELEMENT("<URI>", name, element.getLocation())));
                }
            } else {
                throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0090_UNEXPECTED_ELEMENT(name, element.getLocation())));
            }
        }
        reader.nextEvent();
        this.unmarshal(reader, element);
    } catch (XMLStreamException e) {
        throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0088_FAILED_PARSE(element.getLocation()), e));
    }
}
 
Example #25
Source File: JAXBEncoderDecoderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMarshallIntoStaxStreamWriter() throws Exception {
    GreetMe obj = new GreetMe();
    obj.setRequestType("Hello");
    QName elName = new QName(wrapperAnnotation.targetNamespace(),
                             wrapperAnnotation.localName());
    MessagePartInfo part = new MessagePartInfo(elName, null);
    part.setElement(true);
    part.setElementQName(elName);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLOutputFactory opFactory = XMLOutputFactory.newInstance();
    opFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.TRUE);
    FixNamespacesXMLStreamWriter writer = new FixNamespacesXMLStreamWriter(opFactory.createXMLStreamWriter(baos));

    assertNull(writer.getMarshaller());

    Marshaller m = context.createMarshaller();
    JAXBEncoderDecoder.marshall(m, obj, part, writer);
    assertEquals(m, writer.getMarshaller());
    writer.flush();
    writer.close();

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    XMLInputFactory ipFactory = XMLInputFactory.newInstance();
    XMLEventReader reader = ipFactory.createXMLEventReader(bais);

    Unmarshaller um = context.createUnmarshaller();
    Object val = um.unmarshal(reader, GreetMe.class);
    assertTrue(val instanceof JAXBElement);
    val = ((JAXBElement<?>)val).getValue();
    assertTrue(val instanceof GreetMe);
    assertEquals(obj.getRequestType(),
                 ((GreetMe)val).getRequestType());
}
 
Example #26
Source File: ExternalAttachmentsUnmarshaller.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private void readPolicy(final XMLEventReader reader) throws PolicyException {
    final PolicySourceModel policyModel = POLICY_UNMARSHALLER.unmarshalModel(reader);
    final PolicyModelTranslator translator = PolicyModelTranslator.getTranslator();
    final Policy policy = translator.translate(policyModel);
    if (this.currentUri != null) {
        map.put(this.currentUri, policy);
        this.currentUri = null;
        this.currentPolicy = null;
    }
    else {
        this.currentPolicy = policy;
    }
}
 
Example #27
Source File: MessageUtil.java    From fastweixin with Apache License 2.0 5 votes vote down vote up
/**
 * Event为scancode_push, scancode_waitmsg时触发
 * @param reader reader
 * @return 读取结果
 * @throws XMLStreamException XML解析异常
 */
protected static Map<String, Object> eventScanCodePush(XMLEventReader reader) throws XMLStreamException{
    Map<String, Object> scanCodePush = new HashMap<String, Object>();
    while(reader.hasNext()){
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            String tagName = event.asStartElement().getName()
                    .toString();
            scanCodePush.put(tagName, reader.getElementText());
        }
    }
    return scanCodePush;
}
 
Example #28
Source File: AuditConfigParser.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private AuditProviderEntry getEntry(XMLEventReader xmlEventReader) throws XMLStreamException
{
   XMLEvent xmlEvent = xmlEventReader.nextEvent(); 
   Map<String, Object> options = new HashMap<String,Object>();
   
   
   String codeName = null; 
   
   //We got the login-module element
   StartElement policyModuleElement = (StartElement) xmlEvent;
   //We got the login-module element
   Iterator<Attribute> attrs = policyModuleElement.getAttributes();
   while(attrs.hasNext())
   {
      Attribute attribute = attrs.next();
      
      QName attQName = attribute.getName();
      String attributeValue = StaxParserUtil.getAttributeValue(attribute);
      if("code".equals(attQName.getLocalPart()))
      {
         codeName = attributeValue; 
      } 
   } 
   //See if there are options
   ModuleOptionParser moParser = new ModuleOptionParser();
   options.putAll(moParser.parse(xmlEventReader));
   
   AuditProviderEntry entry =  new AuditProviderEntry(codeName, options);  
   return entry;
}
 
Example #29
Source File: StreamingSheetTest.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    OPCPackage pkg = OPCPackage.open(StreamingSheetTest.class.getResourceAsStream("../dates.xlsx"));
    XSSFReader reader = new XSSFReader(pkg);

    ReadOnlySharedStringsTable sst = new ReadOnlySharedStringsTable(pkg);
    StylesTable styles = reader.getStylesTable();

    Iterator<InputStream> iter = reader.getSheetsData();
    XMLEventReader parser = XMLInputFactory.newInstance().createXMLEventReader(iter.next());
    final StreamingSheetReader streamingSheetReader = new StreamingSheetReader(sst, styles, parser, 10);
    streamingSheet = new StreamingSheet("name", streamingSheetReader);
}
 
Example #30
Source File: XMLUtilities.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc }
 */
@Override
protected Set<String> retrieveAllLinkNames(final InputStream is) throws Exception {
  final Set<String> links = new HashSet<String>();

  final XMLEventReader reader = getEventReader(is);

  try {

    int startDepth = 0;

    while (true) {
      final Map.Entry<Integer, XMLElement> linkInfo =
          extractElement(reader, null,
              Collections.<String> singletonList(Constants.get(ConstantKey.LINK)), startDepth, 2, 2);

      startDepth = linkInfo.getKey();

      links.add(linkInfo.getValue().getStart().getAttributeByName(new QName("title")).getValue());
    }
  } catch (Exception ignore) {
    // ignore
  } finally {
    reader.close();
    IOUtils.closeQuietly(is);
  }

  return links;
}