Example usage for javax.xml.stream XMLInputFactory IS_VALIDATING

List of usage examples for javax.xml.stream XMLInputFactory IS_VALIDATING

Introduction

In this page you can find the example usage for javax.xml.stream XMLInputFactory IS_VALIDATING.

Prototype

String IS_VALIDATING

To view the source code for javax.xml.stream XMLInputFactory IS_VALIDATING.

Click Source Link

Document

The property used to turn on/off implementation specific validation

Usage

From source file:com.autonomy.aci.client.services.impl.AbstractStAXProcessorTest.java

@Test
public void testXMLInputFactoryPropertyAccessors() throws NoSuchFieldException, IllegalAccessException {
    // Check for the default values...
    final AbstractStAXProcessor<?> abstractStAXProcessor = spy(AbstractStAXProcessor.class);
    assertThat(abstractStAXProcessor.isNamespaceAware(), is(false));
    assertThat(abstractStAXProcessor.isValidating(), is(false));
    assertThat(abstractStAXProcessor.isCoalescing(), is(false));
    assertThat(abstractStAXProcessor.isReplacingEntityReferences(), is(true));
    assertThat(abstractStAXProcessor.isSupportingExternalEntities(), is(false));
    assertThat(abstractStAXProcessor.isSupportDtd(), is(true));

    // Set new values via the property accessors...
    abstractStAXProcessor.setNamespaceAware(true);
    abstractStAXProcessor.setValidating(true);
    abstractStAXProcessor.setCoalescing(true);
    abstractStAXProcessor.setReplacingEntityReferences(false);
    abstractStAXProcessor.setSupportingExternalEntities(true);
    abstractStAXProcessor.setSupportDtd(false);

    final XMLInputFactory mockXmlInputFactory = mock(XMLInputFactory.class);
    final Field field = ReflectionTestUtils.getAccessibleField(AbstractStAXProcessor.class, "xmlInputFactory");
    field.set(abstractStAXProcessor, mockXmlInputFactory);

    // Check the values have changed...
    abstractStAXProcessor.process(when(mock(AciResponseInputStream.class).getContentType())
            .thenReturn("text/xml").<AciResponseInputStream>getMock());
    verify(mockXmlInputFactory).setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
    verify(mockXmlInputFactory).setProperty(XMLInputFactory.IS_VALIDATING, true);
    verify(mockXmlInputFactory).setProperty(XMLInputFactory.IS_COALESCING, true);
    verify(mockXmlInputFactory).setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
    verify(mockXmlInputFactory).setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, true);
    verify(mockXmlInputFactory).setProperty(XMLInputFactory.SUPPORT_DTD, false);
}

From source file:org.apereo.portal.io.xml.PortalDataKeyFileProcessor.java

PortalDataKeyFileProcessor(Map<PortalDataKey, IPortalDataType> dataKeyTypes,
        IPortalDataHandlerService.BatchImportOptions options) {
    this.dataKeyTypes = dataKeyTypes;
    this.options = options;

    this.xmlInputFactory = XMLInputFactory.newFactory();

    //Set the input buffer to 2k bytes. This appears to work for reading just enough to get the start element event for
    //all of the data files in a single read operation.
    this.xmlInputFactory.setProperty(WstxInputProperties.P_INPUT_BUFFER_LENGTH, 2000);
    this.xmlInputFactory.setProperty(XMLInputFactory2.P_LAZY_PARSING, true); //Do as little parsing as possible, just want basic info
    this.xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false); //Don't do any validation here
    this.xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); //Don't load referenced DTDs here
}

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

public XMLInfrastructure() {
    transformerFactory = TransformerFactory.newInstance();

    if (!transformerFactory.getClass().getName().contains("redirected")) {
        safeInputFactory = XMLInputFactory.newInstance();
        safeInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
        safeInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
    } else {//w  w  w.  java  2 s.  c om
        logger.warn("Somebody is playing games with the TransformerFactory...we cannot use it safely: {}",
                transformerFactory);
        safeInputFactory = null;
    }

    dbFactory = DocumentBuilderFactory.newInstance();

    // TODO: Probably don't need these available, since it's unlikely Maven can do much with them.
    dbFactory.setValidating(false);
    dbFactory.setXIncludeAware(false);
    dbFactory.setNamespaceAware(false);

    // TODO: Are these wise?? We're mainly interested in harvesting POM information, not preserving fidelity...
    dbFactory.setIgnoringComments(true);
    dbFactory.setExpandEntityReferences(false);
    dbFactory.setCoalescing(true);
}

From source file:org.jasig.portal.io.xml.PortalDataKeyFileProcessor.java

PortalDataKeyFileProcessor(Map<PortalDataKey, IPortalDataType> dataKeyTypes, BatchImportOptions options) {
    this.dataKeyTypes = dataKeyTypes;
    this.options = options;

    this.xmlInputFactory = XMLInputFactory.newFactory();

    //Set the input buffer to 2k bytes. This appears to work for reading just enough to get the start element event for
    //all of the data files in a single read operation.
    this.xmlInputFactory.setProperty(WstxInputProperties.P_INPUT_BUFFER_LENGTH, 2000);
    this.xmlInputFactory.setProperty(XMLInputFactory2.P_LAZY_PARSING, true); //Do as little parsing as possible, just want basic info
    this.xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false); //Don't do any validation here
    this.xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); //Don't load referenced DTDs here
}

From source file:org.jmecsoftware.plugins.tests.utils.StaxParser.java

/**
 * Stax parser for a given stream handler and iso control chars set awarness to on.
 * The iso control chars in the xml file will be replaced by simple spaces, usefull for
 * potentially bogus XML files to parse, this has a small perfs overhead so use it only when necessary
 *
 * @param streamHandler              the xml stream handler
 * @param isoControlCharsAwareParser true or false
 *//*from   w w w  .  j av  a  2 s.c o  m*/
public StaxParser(XmlStreamHandler streamHandler, boolean isoControlCharsAwareParser) {
    this.streamHandler = streamHandler;
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    if (xmlFactory instanceof WstxInputFactory) {
        WstxInputFactory wstxInputfactory = (WstxInputFactory) xmlFactory;
        wstxInputfactory.configureForLowMemUsage();
        wstxInputfactory.getConfig().setUndeclaredEntityResolver(new UndeclaredEntitiesXMLResolver());
    }
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
    this.isoControlCharsAwareParser = isoControlCharsAwareParser;
    inf = new SMInputFactory(xmlFactory);
}

From source file:org.sakaiproject.nakamura.auth.cas.CasAuthenticationHandler.java

private String retrieveCredentials(String responseBody) {
    String username = null;/* w w  w . jav  a  2s.  c  o m*/
    String pgtIou = null;
    String failureCode = null;
    String failureMessage = null;

    try {
        XMLInputFactory xmlInputFactory = new WstxInputFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
        xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
        XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(new StringReader(responseBody));

        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();

            // process the event if we're starting an element
            if (event.isStartElement()) {
                StartElement startEl = event.asStartElement();
                QName startElName = startEl.getName();
                String startElLocalName = startElName.getLocalPart();
                LOGGER.debug(responseBody);

                /*
                 * Example of failure XML
                <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
                  <cas:authenticationFailure code='INVALID_REQUEST'>
                    &#039;service&#039; and &#039;ticket&#039; parameters are both required
                  </cas:authenticationFailure>
                </cas:serviceResponse>
                */
                if ("authenticationFailure".equalsIgnoreCase(startElLocalName)) {
                    // get code of the failure
                    Attribute code = startEl.getAttributeByName(QName.valueOf("code"));
                    failureCode = code.getValue();

                    // get the message of the failure
                    event = eventReader.nextEvent();
                    assert event.isCharacters();
                    Characters chars = event.asCharacters();
                    failureMessage = chars.getData();
                    break;
                }

                /*
                 * Example of success XML
                <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
                  <cas:authenticationSuccess>
                    <cas:user>NetID</cas:user>
                  </cas:authenticationSuccess>
                </cas:serviceResponse>
                */
                if ("authenticationSuccess".equalsIgnoreCase(startElLocalName)) {
                    // skip to the user tag start
                    while (eventReader.hasNext()) {
                        event = eventReader.nextTag();
                        if (event.isEndElement()) {
                            if (eventReader.hasNext()) {
                                event = eventReader.nextTag();
                            } else {
                                break;
                            }
                        }
                        assert event.isStartElement();
                        startEl = event.asStartElement();
                        startElName = startEl.getName();
                        startElLocalName = startElName.getLocalPart();
                        if (proxy && "proxyGrantingTicket".equals(startElLocalName)) {
                            event = eventReader.nextEvent();
                            assert event.isCharacters();
                            Characters chars = event.asCharacters();
                            pgtIou = chars.getData();
                            LOGGER.debug("XML parser found pgt: {}", pgtIou);
                        } else if ("user".equals(startElLocalName)) {
                            // move on to the body of the user tag
                            event = eventReader.nextEvent();
                            assert event.isCharacters();
                            Characters chars = event.asCharacters();
                            username = chars.getData();
                            LOGGER.debug("XML parser found user: {}", username);
                        } else {
                            LOGGER.error("Found unexpected element [{}] while inside 'authenticationSuccess'",
                                    startElName);
                            break;
                        }
                        if (username != null && (!proxy || pgtIou != null)) {
                            break;
                        }
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error(e.getMessage(), e);
    }

    if (failureCode != null || failureMessage != null) {
        LOGGER.error("Error response from server code={} message={}", failureCode, failureMessage);
    }
    String pgt = pgts.get(pgtIou);
    if (pgt != null) {
        savePgt(username, pgt, pgtIou);
    } else {
        LOGGER.debug("Caching '{}' as the IOU for '{}'", pgtIou, username);
        pgtIOUs.put(pgtIou, username);
    }
    return username;
}

From source file:org.sakaiproject.nakamura.auth.cas.CasAuthenticationHandler.java

private String getProxyTicketFromXml(String responseBody) {
    String ticket = null;//from   w w  w.  j a v a 2 s .co m

    try {
        XMLInputFactory xmlInputFactory = new WstxInputFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
        xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
        XMLEventReader eventReader = xmlInputFactory.createXMLEventReader(new StringReader(responseBody));
        LOGGER.debug(responseBody);

        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();

            // process the event if we're starting an element
            if (event.isStartElement()) {
                StartElement startEl = event.asStartElement();
                QName startElName = startEl.getName();
                String startElLocalName = startElName.getLocalPart();

                // Example XML
                // <cas:serviceResponse>
                // <cas:proxySuccess>
                // <cas:proxyTicket>PT-957-ZuucXqTZ1YcJw81T3dxf</cas:proxyTicket>
                // </cas:proxySuccess>
                // </cas:serviceResponse>

                if ("proxySuccess".equalsIgnoreCase(startElLocalName)) {
                    event = eventReader.nextTag();
                    assert event.isStartElement();
                    startEl = event.asStartElement();
                    startElName = startEl.getName();
                    startElLocalName = startElName.getLocalPart();
                    if ("proxyTicket".equalsIgnoreCase(startElLocalName)) {
                        event = eventReader.nextEvent();
                        assert event.isCharacters();
                        Characters chars = event.asCharacters();
                        ticket = chars.getData();
                    } else {
                        LOGGER.error("Found unexpected element [{}] while inside 'proxySuccess'", startElName);
                        break;
                    }
                }
            }
        }
    } catch (XMLStreamException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return ticket;
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

@Activate
protected void activate(ComponentContext context) {
    xmlInputFactory = new WstxInputFactory();
    xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
    xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);

    // process properties into http methods
    Dictionary<?, ?> props = context.getProperties();

    hmacHeader = PropertiesUtil.toString(props.get(HMAC_HEADER), DEFAULT_HMAC_HEADER);
    searchUrl = PropertiesUtil.toString(props.get(SEARCH_URL), DEFAULT_SEARCH_URL);
    documentUrl = PropertiesUtil.toString(props.get(DOCUMENT_URL), DEFAULT_DOCUMENT_URL);
    updateUrl = PropertiesUtil.toString(props.get(UPDATE_URL), DEFAULT_UPDATE_URL);
    metadataUrl = PropertiesUtil.toString(props.get(METADATA_URL), DEFAULT_METADATA_URL);
    removeUrl = PropertiesUtil.toString(props.get(REMOVE_URL), DEFAULT_REMOVE_URL);

    hmacHeader = PropertiesUtil.toString(props.get(HMAC_HEADER), DEFAULT_HMAC_HEADER);
    sharedKey = PropertiesUtil.toString(props.get(SHARED_KEY), null);
}

From source file:org.sakaiproject.nakamura.importer.ImportSiteArchiveServlet.java

/**
 * {@inheritDoc}/*w  w  w  .j  a  v  a  2s .c o m*/
 * 
 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
 */
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    xmlInputFactory = new WstxInputFactory();
    xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);
    xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false);
    sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
}

From source file:org.sakaiproject.nakamura.proxy.RSSProxyPostProcessor.java

@Activate
protected void activate(Map<?, ?> props) {
    eventsThreshold = PropertiesUtil.toInteger(props.get(EVENTS_THRESHOLD), DEFAULT_EVENTS_THRESHOLD);
    maxLength = PropertiesUtil.toInteger(props.get(MAX_LENGTH), DEFAULT_MAX_LENGTH);

    xmlInputFactory = new WstxInputFactory();
    xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, true);
    xmlInputFactory.setProperty(XMLInputFactory.IS_VALIDATING, false);

    contentTypes = new ArrayList<String>();
    contentTypes.add("application/rss+xml");
    contentTypes.add("application/rdf+xml");
    contentTypes.add("application/atom+xml");
    contentTypes.add("text/xml");
    contentTypes.add("application/xhtml+xml");
    contentTypes.add("application/xml");
    contentTypes.add("text/plain");

    // Formats are stored as:
    //   key = First tag after prologue. Include version if pertinent.
    //   value = Set of required tags.
    formats = new HashMap<String, Set<String>>();

    // RSS 0.91/*from   w w  w.  ja va2s . c  o m*/
    HashSet<String> rss091 = new HashSet<String>();
    rss091.add("channel");
    rss091.add("title");
    rss091.add("description");
    rss091.add("link");
    rss091.add("language");
    formats.put("rss-0.91", rss091);

    // RSS 1.0
    HashSet<String> rss10 = new HashSet<String>();
    rss10.add("channel");
    rss10.add("title");
    rss10.add("description");
    rss10.add("link");
    formats.put("rdf", rss10);

    // RSS 2.0
    HashSet<String> rss20 = new HashSet<String>();
    rss20.add("channel");
    rss20.add("title");
    rss20.add("description");
    rss20.add("link");
    formats.put("rss-2.0", rss20);

    // ATOM 1.0
    HashSet<String> atom10 = new HashSet<String>();
    atom10.add("id");
    atom10.add("title");
    atom10.add("updated");
    formats.put("feed", atom10);
}