Example usage for javax.xml.stream XMLInputFactory newInstance

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

Introduction

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

Prototype

public static XMLInputFactory newInstance() throws FactoryConfigurationError 

Source Link

Document

Creates a new instance of the factory in exactly the same manner as the #newFactory() method.

Usage

From source file:org.castor.jaxb.CastorUnmarshallerTest.java

/**
 * Tests the {@link CastorUnmarshaller#unmarshal(XMLStreamReader, Class)} method when declared type is null. <p/>
 * {@link IllegalArgumentException} is expected.
 *
 * @throws Exception if any error occurs during test
 *///w w w.  j a  v a 2s  .c o m
@Test(expected = IllegalArgumentException.class)
public void testUnmarshalXMLStreamReaderJAXBElementNull2() throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader xmlStreamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_XML));

    unmarshaller.unmarshal(xmlStreamReader, null);
}

From source file:org.castor.jaxb.CastorUnmarshallerTest.java

/**
 * Tests the {@link CastorUnmarshaller#unmarshal(XMLStreamReader, Class)} method.
 *
 * @throws Exception if any error occurs during test
 *///from   w ww  .java 2 s  .c o m
@Test
public void testUnmarshalXMLStreamReaderJAXBElement() throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader xmlStreamReader = inputFactory.createXMLStreamReader(new StringReader(INPUT_XML));

    JAXBElement<Entity> entity = unmarshaller.unmarshal(xmlStreamReader, Entity.class);
    testJAXBElement(entity);
}

From source file:org.psikeds.knowledgebase.xml.impl.XMLParser.java

/**
 * Helper for parsing big XML files using JAXB in combination with StAX.<br>
 * Only XML-Elements of the specified Top-Level-Class will be parsed.<br>
 * <b>Note:</b> The XML reader will not be closed. This must be invoked by
 * the caller afterwards!<br>//from   w ww.  j a v  a 2  s.c  o  m
 * 
 * @param xml
 *          Reader for XML-Data
 * @param elementClass
 *          Top-Level-Class used for JAXB-Unmarshalling
 * @param handler
 *          Callback handler used to process every single found XML
 *          element (@see
 *          org.psikeds.knowledgebase.xml.KBParserCallback#handleElement
 *          (java.lang.Object))
 * @param filter
 *          EventFilter used for StAX-Parsing
 * @param numSkipped
 *          Number of Elements to be skipped,
 *          e.g. numSkipped = 1 for skipping the XML-Root-Element.
 * @return Total number of unmarshalled XML-Elements
 * @throws XMLStreamException
 * @throws JAXBException
 */
public static long parseXmlElements(final Reader xml, final Class<?> elemClazz, final KBParserCallback handler,
        final EventFilter filter, final int numSkipped) throws XMLStreamException, JAXBException {

    // init stream reader
    final XMLInputFactory staxFactory = XMLInputFactory.newInstance();
    final XMLEventReader staxReader = staxFactory.createXMLEventReader(xml);
    final XMLEventReader filteredReader = filter == null ? staxReader
            : staxFactory.createFilteredReader(staxReader, filter);

    skipXmlElements(filteredReader, numSkipped);

    // JAXB with specific top-level-class
    final JAXBContext jaxbCtx = JAXBContext.newInstance(elemClazz);
    final Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller();

    // parsing und unmarshalling
    long counter = 0;
    while (filteredReader.peek() != null) {
        final Object element = unmarshaller.unmarshal(staxReader, elemClazz);
        handleElement(handler, element);
        counter++;
    }
    return counter;
}

From source file:org.castor.jaxb.CastorUnmarshallerTest.java

/**
 * Tests the {@link CastorUnmarshaller#unmarshal(XMLEventReader)} method.
 *
 * @throws Exception if any error occurs during test
 *///from ww  w .  j  a v a 2 s .c  o  m
@Test
public void testUnmarshalXMLEventReader() throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_XML));

    Entity entity = (Entity) unmarshaller.unmarshal(xmlEventReader);
    testEntity(entity);
}

From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java

public boolean templateExistsInRepo(String templateName) throws Exception {
    List<String> allPackages = getPackageNames();
    try {/*from ww w  .j av  a  2s  .  co  m*/
        for (String pkg : allPackages) {
            String templateURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain()
                    + "/rest/packages/" + pkg + "/assets/" + URLEncoder.encode(templateName, "UTF-8");

            URL checkURL = new URL(templateURL);
            HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection();
            checkConnection.setRequestMethod("GET");
            checkConnection.setRequestProperty("Accept", "application/atom+xml");
            checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout()));
            checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout()));
            applyAuth(checkConnection);
            checkConnection.connect();
            if (checkConnection.getResponseCode() == 200) {

                XMLInputFactory factory = XMLInputFactory.newInstance();
                XMLStreamReader reader = factory.createXMLStreamReader(checkConnection.getInputStream());

                boolean foundFormFormat = false;
                while (reader.hasNext()) {
                    if (reader.next() == XMLStreamReader.START_ELEMENT) {
                        if ("format".equals(reader.getLocalName())) {
                            reader.next();
                            String pname = reader.getElementText();
                            if ("flt".equalsIgnoreCase(pname)) {
                                foundFormFormat = true;
                                break;
                            }
                        }
                    }
                }
                return foundFormFormat;
            }
        }
    } catch (Exception e) {
        logger.error("Exception checking template url : " + e.getMessage());
        return false;
    }
    logger.info("Could not find process template for: " + templateName);
    return false;
}

From source file:info.novatec.ita.check.config.StereotypeCheckReader.java

/**
 * Read and validate the given file to a configuration for stereotype check.
 * /*from   w  w w.j  av  a  2  s.  c  om*/
 * @param file
 *            The file to read.
 * @param additionalCheckCfg
 *            a previously read configuration which may override parts of
 *            the configuration read by the file.
 * @param readingAdditionalCfg
 *            Are we reading the additionalCfg.
 * @return the configuration.
 * @throws XMLStreamException
 * @throws IllegalArgumentException
 * @throws SAXException
 * @throws IOException
 */
private static StereotypeCheckConfiguration read(File file, String checkstyleStereotypeXsd,
        StereotypeCheckConfiguration additionalCheckCfg, boolean readingAdditionalCfg)
        throws XMLStreamException, IllegalArgumentException, SAXException, IOException {

    // Validate with StreamSource because Stax Validation is not provided
    // with every implementation of JAXP
    SchemaFactory schemafactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    Schema schema = schemafactory
            .newSchema(StereotypeCheckReader.class.getClassLoader().getResource(checkstyleStereotypeXsd));

    Validator validator = schema.newValidator();
    validator.validate(new StreamSource(file));

    // Parse with Stax
    XMLStreamReader reader = XMLInputFactory.newInstance()
            .createXMLStreamReader(new BufferedInputStream(new FileInputStream(file)));
    StereotypeCheckConfigurationReader delegate = new StereotypeCheckConfigurationReader(reader,
            additionalCheckCfg, readingAdditionalCfg);

    while (delegate.hasNext()) {
        delegate.next();
    }

    return delegate.getConfig();
}

From source file:jp.co.atware.solr.geta.GETAssocComponent.java

/**
 * GETAssoc?????<code>NamedList</code>???????
 * //from   w  ww  .ja  v  a 2s.  c om
 * @param inputStream GETAssoc??
 * @return <code>NamedList</code>?
 * @throws FactoryConfigurationError
 * @throws IOException
 */
protected NamedList<Object> convertResult(InputStream inputStream)
        throws FactoryConfigurationError, IOException {
    NamedList<Object> result = new NamedList<Object>();
    LinkedList<NamedList<Object>> stack = new LinkedList<NamedList<Object>>();
    stack.push(result);
    try {
        XMLStreamReader xml = XMLInputFactory.newInstance().createXMLStreamReader(inputStream);
        while (xml.hasNext()) {
            switch (xml.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                NamedList<Object> element = new NamedList<Object>();
                stack.peek().add(xml.getName().toString(), element);
                stack.push(element);
                for (int i = 0; i < xml.getAttributeCount(); i++) {
                    String name = xml.getAttributeName(i).toString();
                    String value = xml.getAttributeValue(i);
                    ValueOf valueOf = valueTransMap.get(name);
                    if (valueOf != null) {
                        try {
                            element.add(name, valueOf.toValue(value));
                        } catch (NumberFormatException e) {
                            element.add(name, value);
                        }
                    } else {
                        element.add(name, value);
                    }
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                stack.pop();
                break;
            default:
                break;
            }
            xml.next();

        }
        xml.close();
    } catch (XMLStreamException e) {
        throw new IOException(e);
    }

    LOG.debug(result.toString());
    return result;
}

From source file:com.sun.socialsite.pojos.PropDefinition.java

protected void init(PropDefinition profileDef, InputStream input) throws SocialSiteException {
    try {//from w w  w  . j a  v a2 s  . co  m
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader parser = factory.createXMLStreamReader(input);
        String ns = null; // TODO: namespace for ProfileDef

        // hold the current things we're working on
        Map<String, DisplaySectionDefinition> sdefs = new LinkedHashMap<String, DisplaySectionDefinition>();
        Stack<PropertyDefinitionHolder> propertyHolderStack = new Stack<PropertyDefinitionHolder>();
        List<AllowedValue> allowedValues = null;
        PropertyDefinition pdef = null;

        for (int event = parser.next(); event != XMLStreamConstants.END_DOCUMENT; event = parser.next()) {
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                log.debug("START ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    propertyHolderStack.push(new DisplaySectionDefinition(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey")));

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    pdef = new PropertyDefinition(holder.getBasePath(), parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"), parser.getAttributeValue(ns, "type"));

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    propertyHolderStack.push(new PropertyObjectCollectionDefinition(holder.getBasePath(),
                            parser.getAttributeValue(ns, "name"), parser.getAttributeValue(ns, "namekey")));

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    allowedValues = new ArrayList<AllowedValue>();

                } else if ("value".equals(parser.getLocalName())) {
                    AllowedValue allowedValue = new AllowedValue(parser.getAttributeValue(ns, "name"),
                            parser.getAttributeValue(ns, "namekey"));
                    allowedValues.add(allowedValue);

                } else if ("default-value".equals(parser.getLocalName())) {
                    pdef.setDefaultValue(parser.getText());
                }
                break;

            case XMLStreamConstants.END_ELEMENT:
                log.debug("END ELEMENT -- " + parser.getLocalName());

                if ("display-section".equals(parser.getLocalName())) {
                    DisplaySectionDefinition sdef = (DisplaySectionDefinition) propertyHolderStack.pop();
                    sdefs.put(sdef.getName(), sdef);

                } else if ("property".equals(parser.getLocalName())) {
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyDefinitions().add(pdef);
                    propertyDefs.put(pdef.getName(), pdef);
                    pdef = null;

                } else if ("object".equals(parser.getLocalName())) {
                    PropertyObjectDefinition odef = (PropertyObjectDefinition) propertyHolderStack.pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectDefinitions().add(odef);

                    // add to list of all property object defs
                    propertyObjectDefs.put(odef.getName(), odef);
                    odef = null;

                } else if ("collection".equals(parser.getLocalName())) {
                    PropertyObjectCollectionDefinition cdef = (PropertyObjectCollectionDefinition) propertyHolderStack
                            .pop();
                    PropertyDefinitionHolder holder = propertyHolderStack.peek();
                    holder.getPropertyObjectCollectionDefinitions().add(cdef);

                    // add to list of all property object defs
                    propertyObjectCollectionDefs.put(cdef.getName(), cdef);
                    cdef = null;

                } else if ("allowed-values".equals(parser.getLocalName())) {
                    pdef.setAllowedValues(allowedValues);
                    allowedValues = null;
                }
                break;

            case XMLStreamConstants.CHARACTERS:
                break;

            case XMLStreamConstants.CDATA:
                break;

            } // end switch
        } // end while

        parser.close();

        profileDef.sectionDefs = sdefs;

    } catch (Exception ex) {
        throw new SocialSiteException("ERROR parsing profile definitions", ex);
    }
}

From source file:org.castor.jaxb.CastorUnmarshallerTest.java

/**
 * Tests the {@link CastorUnmarshaller#unmarshal(XMLEventReader, Class)} method when declared type is null. <p/>
 * {@link IllegalArgumentException} is expected.
 *
 * @throws Exception if any error occurs during test
 *//*  w  w  w. j  a  va  2  s  .  co  m*/
@Test(expected = IllegalArgumentException.class)
public void testUnmarshalXMLEventReaderJAXBElementNull2() throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_XML));

    unmarshaller.unmarshal(xmlEventReader, null);
}

From source file:org.castor.jaxb.CastorUnmarshallerTest.java

/**
 * Tests the {@link CastorUnmarshaller#unmarshal(XMLEventReader, Class)} method.
 *
 * @throws Exception if any error occurs during test
 *//*from  w w  w .j a  v a  2s  .  c  o m*/
@Test
public void testUnmarshalXMLEventReaderJAXBElement() throws Exception {
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLEventReader xmlEventReader = inputFactory.createXMLEventReader(new StringReader(INPUT_XML));

    JAXBElement<Entity> entity = unmarshaller.unmarshal(xmlEventReader, Entity.class);
    testJAXBElement(entity);
}