Example usage for javax.xml.stream XMLInputFactory setProperty

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

Introduction

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

Prototype

public abstract void setProperty(java.lang.String name, Object value) throws java.lang.IllegalArgumentException;

Source Link

Document

Allows the user to set specific feature/property on the underlying implementation.

Usage

From source file:org.opentestsystem.delivery.AccValidator.handlers.ValidationHandler.java

public void validateXmlAccs(String filePath, String xsdPath) throws ValidationException {
    try {//from w  w w .ja  v a  2  s .com
        InputStream xmlInput = new FileInputStream(new File(filePath));
        InputStream xsdInput = new FileInputStream(new File(xsdPath));

        String text = null;
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        XMLStreamReader reader = factory.createXMLStreamReader(xmlInput);

        boolean firstSelect = true;
        MasterResourceAccommodation masterResource = null;
        List<MasterResourceAccommodation> resourceFamiltyMasterResourceAccommodations = null;
        AccommodationText accommodationText = null;
        List<AccommodationText> accommodationTexts = null;
        AccommodationOption accommodationOption = null;
        List<AccommodationOption> accommodationOptions = null;
        AccFamilySubject familySubject = null;
        List<AccFamilySubject> familySubjects = null;
        ResourceFamily resourceFamily = null;
        List<String> grades = null;

        while (reader.hasNext()) {
            int Event = reader.next();
            switch (Event) {
            case XMLStreamConstants.START_ELEMENT: {
                switch (reader.getLocalName()) {
                case "MasterResourceFamily":
                    _masterResourceAccommodations = new ArrayList<MasterResourceAccommodation>();

                    break;
                case "SingleSelectResource":
                    masterResource = new MasterResourceAccommodation();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    accommodationOptions = new ArrayList<AccommodationOption>();
                    break;

                case "MultiSelectResource":
                    masterResource = new MasterResourceAccommodation();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    accommodationOptions = new ArrayList<AccommodationOption>();
                    break;
                case "EditResource":
                    masterResource = new MasterResourceAccommodation();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    accommodationOptions = new ArrayList<AccommodationOption>();
                    break;
                case "ResourceFamily":
                    masterResource = new MasterResourceAccommodation();
                    familySubjects = new ArrayList<AccFamilySubject>();
                    resourceFamily = new ResourceFamily();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    accommodationText = new AccommodationText();
                    resourceFamiltyMasterResourceAccommodations = new ArrayList<MasterResourceAccommodation>();
                    grades = new ArrayList<String>();
                    break;
                case "Subject":
                    familySubject = new AccFamilySubject();
                    break;
                case "Selection":
                    if (firstSelect) {
                        masterResource.setHeader(accommodationTexts);
                        accommodationOption = new AccommodationOption();
                        accommodationTexts = new ArrayList<AccommodationText>();
                    } else {
                        accommodationOption = new AccommodationOption();
                    }
                    firstSelect = false;
                    break;

                case "Text":
                    accommodationText = new AccommodationText();

                    break;
                default:
                    break;
                }
                break;
            }
            case XMLStreamConstants.CHARACTERS: {
                String nodeValue = getContents(reader.getText());
                if (nodeValue.length() > 0) {
                    text = nodeValue;
                }
                break;
            }
            case XMLStreamConstants.END_ELEMENT: {
                switch (reader.getLocalName()) {
                case "Code":
                    if (accommodationOption == null) {
                        if (familySubject == null) {
                            masterResource.setCode(text);
                        } else {
                            familySubject.setCode(text);
                        }
                    } else {
                        accommodationOption.setCode(text);
                    }
                    text = null;
                    break;
                case "Order":
                    if (accommodationOption == null) {
                        masterResource.setOrder(Integer.valueOf(text));
                    } else {
                        accommodationOption.setOrder(Integer.valueOf(text));
                    }
                    text = null;
                    break;
                case "MutuallyExclusive":
                    accommodationOption.setMutuallyExclusive(true);
                    text = null;
                    break;
                case "DefaultSelection":
                    masterResource.setDefaultSelection(text);
                    text = null;
                    break;
                case "Disabled":
                    masterResource.setDisabled(true);
                    text = null;
                    break;
                case "Language":
                    accommodationText.setLanguage(text);
                    text = null;
                    break;
                case "Label":
                    accommodationText.setLabel(text);
                    text = null;
                    break;
                case "Description":
                    accommodationText.setDescription(text);
                    text = null;
                    break;
                case "Message":
                    accommodationText.setMessage(text);
                    text = null;
                    break;
                case "Text":
                    accommodationTexts.add(accommodationText);
                    text = null;
                    break;
                case "Selection":
                    accommodationOption.setText(accommodationTexts);
                    accommodationOptions.add(accommodationOption);
                    accommodationOption = new AccommodationOption();
                    accommodationTexts = new ArrayList<AccommodationText>();
                    text = null;
                    break;
                case "SingleSelectResource":
                    masterResource.setResourceType("SingleSelectResource");
                    if (accommodationTexts.size() > 0) {
                        masterResource.setHeader(accommodationTexts);
                    }
                    masterResource.setOptions(accommodationOptions);
                    if (resourceFamily == null) {
                        _masterResourceAccommodations.add(masterResource);
                    } else {
                        resourceFamiltyMasterResourceAccommodations.add(masterResource);
                    }
                    masterResource = null;
                    accommodationOption = null;
                    accommodationOption = null;
                    firstSelect = true;
                    text = null;
                    break;
                case "MultiSelectResource":
                    masterResource.setResourceType("MultiSelectResource");
                    if (accommodationTexts.size() > 0) {
                        masterResource.setHeader(accommodationTexts);
                    }
                    masterResource.setOptions(accommodationOptions);
                    if (resourceFamily == null) {
                        _masterResourceAccommodations.add(masterResource);
                    } else {
                        resourceFamiltyMasterResourceAccommodations.add(masterResource);
                    }
                    masterResource = null;
                    accommodationOption = null;
                    accommodationOption = null;
                    firstSelect = true;
                    text = null;
                    break;
                case "EditResource":
                    masterResource.setResourceType("EditResource");
                    if (accommodationTexts.size() > 0) {
                        masterResource.setHeader(accommodationTexts);
                    }
                    masterResource.setOptions(accommodationOptions);
                    if (resourceFamily == null) {
                        _masterResourceAccommodations.add(masterResource);
                    } else {
                        resourceFamiltyMasterResourceAccommodations.add(masterResource);
                    }
                    masterResource = null;
                    accommodationOption = null;
                    accommodationOption = null;
                    firstSelect = true;
                    text = null;
                    break;
                case "ResourceFamily":
                    resourceFamily.setSubject(familySubjects);
                    resourceFamily.setGrade(grades);
                    resourceFamily.setMasterResourceAccommodation(resourceFamiltyMasterResourceAccommodations);
                    _resourceFamilies.add(resourceFamily);
                    familySubjects = null;
                    grades = null;
                    resourceFamily = null;
                    resourceFamiltyMasterResourceAccommodations = null;
                    text = null;
                    break;
                case "Name":
                    familySubject.setName(text);
                    text = null;
                    break;
                case "Subject":
                    familySubjects.add(familySubject);
                    familySubject = null;
                    text = null;
                    break;
                case "Grade":
                    grades.add(text);
                    text = null;
                    break;
                }
                break;
            }
            }
        }

        validateRules(_masterResourceAccommodations, _resourceFamilies);
        // validation against xsd
        xmlInput = new FileInputStream(new File(filePath));
        xsdInput = new FileInputStream(new File(xsdPath));
        validateAgainstXSD(xmlInput, xsdInput);

    } catch (IOException e) {
        throw new ValidationException("failed",
                "The xml could not be parsed into objects. The error message is:" + e.getMessage());
    } catch (XMLStreamException e) {
        throw new ValidationException("failed",
                "The xml could not be parsed into objects. The error message is:" + e.getMessage());
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.api.AnalysisService.java

private String getSchemaName(String encoding, InputStream inputStream) throws XMLStreamException, IOException {
    String domainId = null;/*ww w. j  a  v  a  2  s .c  om*/
    XMLStreamReader reader = null;
    try {
        XMLInputFactory factory = XMLInputFactory.newInstance();
        factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        if (StringUtils.isEmpty(encoding)) {
            reader = factory.createXMLStreamReader(inputStream);
        } else {
            reader = factory.createXMLStreamReader(inputStream, encoding);
        }

        while (reader.next() != XMLStreamReader.END_DOCUMENT) {
            if (reader.getEventType() == XMLStreamReader.START_ELEMENT
                    && reader.getLocalName().equalsIgnoreCase("Schema")) {
                domainId = reader.getAttributeValue("", "name");
                return domainId;
            }
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
        inputStream.reset();
    }

    return domainId;
}

From source file:org.restcomm.connect.interpreter.rcml.Parser.java

public Parser(final Reader reader, final String xml, final ActorRef sender) throws IOException {
    super();/*from w w w .  ja v  a 2 s . c o  m*/
    if (logger.isDebugEnabled()) {
        logger.debug("About to create new Parser for xml: " + xml);
    }
    this.xml = xml;
    this.sender = sender;
    final XMLInputFactory inputs = XMLInputFactory.newInstance();
    inputs.setProperty("javax.xml.stream.isCoalescing", true);
    XMLStreamReader stream = null;
    try {
        stream = inputs.createXMLStreamReader(reader);
        document = parse(stream);
        if (document == null) {
            throw new IOException("There was an error parsing the RCML.");
        }
        iterator = document.iterator();
    } catch (final XMLStreamException exception) {
        if (logger.isInfoEnabled()) {
            logger.info("There was an error parsing the RCML for xml: " + xml + " excpetion: ", exception);
        }
        sender.tell(new ParserFailed(exception, xml), null);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (final XMLStreamException nested) {
                throw new IOException(nested);
            }
        }
    }
}

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

private String retrieveCredentials(String responseBody) {
    String username = null;/*from w w  w .  j ava 2 s .c om*/
    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   ww  w  . j a v a2 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.sonar.api.profiles.XMLProfileParser.java

private SMInputFactory initStax() {
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    // just so it won't try to load DTD in if there's DOCTYPE
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
    return new SMInputFactory(xmlFactory);
}

From source file:org.sonar.api.rules.XMLRuleParser.java

public List<Rule> parse(Reader reader) {
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    // just so it won't try to load DTD in if there's DOCTYPE
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
    SMInputFactory inputFactory = new SMInputFactory(xmlFactory);
    try {/*from w ww  .  ja va 2s  .  c  om*/
        SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
        rootC.advance(); // <rules>
        List<Rule> rules = new ArrayList<Rule>();

        SMInputCursor rulesC = rootC.childElementCursor("rule");
        while (rulesC.getNext() != null) {
            // <rule>
            Rule rule = Rule.create();
            rules.add(rule);

            processRule(rule, rulesC);
        }
        return rules;

    } catch (XMLStreamException e) {
        throw new SonarException("XML is not valid", e);
    }
}

From source file:org.sonar.api.server.rule.RulesDefinitionXmlLoader.java

/**
 * Loads rules by reading the XML input stream. The reader is not closed by the method, so it
 * should be handled by the caller.//from  w w w  .  j ava  2  s.c om
 * @since 4.3
 */
public void load(RulesDefinition.NewRepository repo, Reader reader) {
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    // just so it won't try to load DTD in if there's DOCTYPE
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
    SMInputFactory inputFactory = new SMInputFactory(xmlFactory);
    try {
        SMHierarchicCursor rootC = inputFactory.rootElementCursor(reader);
        rootC.advance(); // <rules>

        SMInputCursor rulesC = rootC.childElementCursor("rule");
        while (rulesC.getNext() != null) {
            // <rule>
            processRule(repo, rulesC);
        }

    } catch (XMLStreamException e) {
        throw new IllegalStateException("XML is not valid", e);
    }
}

From source file:org.sonar.core.technicaldebt.TechnicalDebtXMLImporter.java

private SMInputFactory initStax() {
    XMLInputFactory xmlFactory = XMLInputFactory2.newInstance();
    xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
    return new SMInputFactory(xmlFactory);
}

From source file:org.sonar.cxx.sensors.utils.StaxParser.java

/**
 * StaxParser for a given stream handler and ISO control chars set awareness to on. The ISO control chars in the XML
 * file will be replaced by simple spaces, useful 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
 *//* ww w  .  j  av  a  2s  .com*/
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, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
    xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE);
    this.isoControlCharsAwareParser = isoControlCharsAwareParser;
    inf = new SMInputFactory(xmlFactory);
}