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:Main.java

/**
 * //from   w w  w  .ja v a2  s. c o  m
 * Checks indentation (over a single line - multipline text nodes is not supported)
 * 
 * @param out
 * @param indentSize
 * @return
 * @throws Exception
 */

public static boolean isIndented(String out, int indentSize) throws Exception {
    BufferedReader reader = new BufferedReader(new StringReader(out));

    boolean indentated = false;

    int level = 0;
    int line = 0;

    String string = reader.readLine();
    while (string != null) {
        int newLevel = 0;
        while (newLevel < string.length()) {
            if (!Character.isWhitespace(string.charAt(newLevel))) {
                break;
            }
            newLevel++;
        }
        if ((newLevel % indentSize) != 0) {
            throw new IllegalArgumentException("Unexpected " + newLevel + " whitespace chars at line " + line);
        }
        if (Math.abs(level - newLevel) > indentSize) {
            throw new IllegalArgumentException("Unexpected jump from " + level + " to " + newLevel
                    + " whitespace chars at line " + line + " for indenting with " + indentSize + " chars");
        }
        level = newLevel;

        string = reader.readLine();
        line++;

        if (level > 0) {
            indentated = true;
        }
    }

    if (!indentated) {
        // see if a simple xml piece
        XMLInputFactory inputFactory = XMLInputFactory.newInstance();
        XMLStreamReader parser = inputFactory.createXMLStreamReader(new StringReader(out));

        int elementMaxLevel = -1;
        int elementLevel = 0;
        do {
            int event = parser.next();
            if (event == XMLStreamConstants.START_ELEMENT) {
                elementLevel++;

                if (elementMaxLevel < elementLevel) {
                    elementMaxLevel = elementLevel;
                }
            } else if (event == XMLStreamConstants.END_ELEMENT) {
                elementLevel--;
            }
        } while (parser.hasNext());

        if (elementMaxLevel > 1) { // should be indentated
            return false;
        }
        return true;
    }

    return indentated;
}

From source file:edu.harvard.i2b2.analysis.queryClient.QueryClient.java

public static OMElement getQueryPayLoad(String XMLstr) throws Exception {
    StringReader strReader = new StringReader(XMLstr);
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader reader = xif.createXMLStreamReader(strReader);

    StAXOMBuilder builder = new StAXOMBuilder(reader);
    OMElement lineItem = builder.getDocumentElement();
    // System.out.println("Line item string " + lineItem.toString());
    return lineItem;
}

From source file:Main.java

/**
 * Creates {@link javax.xml.stream.XMLStreamReader} of a {@link InputStream}. The start document is already skipped.
 * /*from www .  j av  a  2  s  .  c  o m*/
 * @param inputStream
 *            never <code>null</code>
 * @return reader the {@link XMLStreamReader} from the passed {@link InputStream}, never <code>null</code>
 * @throws XMLStreamException
 *             - input stream could not be parsed as xml
 */
public static XMLStreamReader createReader(InputStream inputStream) throws XMLStreamException {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = factory.createXMLStreamReader(inputStream);
    skipStartDocument(reader);
    return reader;
}

From source file:com.rockhoppertech.music.midi.js.xml.ModeFactoryXMLHelper.java

/**
 * Read modes.xml and create {@code Scale instances} from those definitions.
 *//* www  .ja v  a  2s  . c om*/
public static void init() {
    List<Integer> intervals = null;
    Scale currentMode = null;
    String tagContent = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = null;
    try {
        reader = factory.createXMLStreamReader(ClassLoader.getSystemResourceAsStream("modes.xml"));
    } catch (XMLStreamException e) {
        e.printStackTrace();
        return;
    }

    try {
        while (reader.hasNext()) {
            int event = reader.next();

            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                String el = reader.getLocalName();
                logger.debug("start element '{}'", el);
                if ("mode".equals(el)) {
                    currentMode = new Scale();
                    intervals = new ArrayList<>();
                }
                if ("modes".equals(el)) {
                    modeList = new ArrayList<>();
                }
                break;

            case XMLStreamConstants.CHARACTERS:
                tagContent = reader.getText().trim();
                logger.debug("tagcontent '{}'", tagContent);
                break;

            case XMLStreamConstants.END_ELEMENT:
                switch (reader.getLocalName()) {
                case "mode":
                    // wow. both guava and commmons to get an int[] array
                    Integer[] array = FluentIterable.from(intervals).toArray(Integer.class);
                    // same as Integer[] array = intervals.toArray(new
                    // Integer[intervals.size()]);
                    int[] a = ArrayUtils.toPrimitive(array);
                    currentMode.setIntervals(a);
                    modeList.add(currentMode);
                    ScaleFactory.registerScale(currentMode);
                    break;
                case "interval":
                    logger.debug("interval '{}'", tagContent);
                    logger.debug("intervals '{}'", intervals);
                    intervals.add(Integer.parseInt(tagContent));
                    break;
                case "name":
                    currentMode.setName(tagContent);
                    break;
                }
                break;

            case XMLStreamConstants.START_DOCUMENT:
                modeList = new ArrayList<>();
                intervals = new ArrayList<>();
                break;
            }
        }
    } catch (XMLStreamException e) {
        logger.error(e.getLocalizedMessage(), e);
        e.printStackTrace();
    }

    logger.debug("mode list \n{}", modeList);
}

From source file:edu.harvard.i2b2.timeline.lifelines.PDOQueryClient.java

public static OMElement getQueryPayLoad(String str) throws Exception {
    StringReader strReader = new StringReader(str);
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader reader = xif.createXMLStreamReader(strReader);

    StAXOMBuilder builder = new StAXOMBuilder(reader);
    OMElement lineItem = builder.getDocumentElement();
    // System.out.println("Line item string " + lineItem.toString());
    return lineItem;
}

From source file:com.biomeris.i2b2.export.ws.messages.MessageFactory.java

/**
 * Function creates tutorial response OMElement from xml string
 * //from   w  ww  .  j  a  va  2  s  .  c  o  m
 * @param xmlString
 * @return OMElement
 * @throws XMLStreamException
 */
public static OMElement createResponseOMElementFromString(String xmlString) throws XMLStreamException {
    OMElement returnElement = null;

    try {
        StringReader strReader = new StringReader(xmlString);
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader reader = xif.createXMLStreamReader(strReader);

        StAXOMBuilder builder = new StAXOMBuilder(reader);
        returnElement = builder.getDocumentElement();
    } catch (XMLStreamException xmlStreamEx) {
        log.error("Error while converting tutorial response PDO to OMElement");
        throw xmlStreamEx;
    }

    return returnElement;
}

From source file:wiki.link.LinkImporter.java

public boolean readXML(String filename) {

    //System.exit(1);
    //MAKE BLOODY SURE YOU HAVE SOME HOURS.
    DbConnector dbc = new DbConnector("localhost");
    dbc.jdbcTemplate.update("TRUNCATE links;");
    try {/*ww  w .ja v a  2s.c o m*/
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(new FileInputStream(filename));

        long n = 0;
        List<Doc> toSave = new ArrayList<>();
        while (xsr.hasNext()) {
            xsr.next();
            if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) {
                if (xsr.getLocalName().equals("page")) {
                    long id = -1;
                    String title = null;
                    String text = null;
                    while (xsr.hasNext()) {
                        xsr.next();
                        if (xsr.getEventType() == XMLStreamReader.START_ELEMENT) {
                            if (xsr.getLocalName().equals("id") && id == -1) {
                                id = Long.parseLong(xsr.getElementText());
                            }
                            if (xsr.getLocalName().equals("title")) {
                                title = xsr.getElementText();
                            }
                            if (xsr.getLocalName().equals("text")) {
                                text = xsr.getElementText();
                            }
                        } else if (xsr.getEventType() == XMLStreamReader.END_ELEMENT
                                && xsr.getLocalName().equals("page")) {
                            break;
                        }
                    }
                    if (id != -1 && title != null && text != null) {
                        Doc wd = new Doc(id, title, text);
                        toSave.add(wd);
                        n++;
                        if (n % 1000 == 0) {
                            insertLinks(toSave, dbc);
                            //                                WikiDoc.insertAll(toSave, dbc);
                            System.out.println(n);
                            toSave.clear();
                        }
                    }
                }
            }
        }
    } catch (IOException | XMLStreamException e) {
        e.printStackTrace();
    }
    return true;
}

From source file:au.org.ala.bhl.DocumentPaginator.java

public void paginateText(String text, PageHandler handler) {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {//from  www .  j av  a 2  s.c  o  m
        XMLStreamReader parser = factory.createXMLStreamReader(new StringReader(text));
        paginateImpl(parser, handler);
    } catch (Exception ex) {
        throw new RuntimeException("Failed to paginate text", ex);
    }
}

From source file:com.hp.application.automation.tools.octane.tests.detection.ResultFieldsXmlReader.java

public ResultFieldsXmlReader(Reader input) throws XMLStreamException {
    this.input = input;
    eventReader = XMLInputFactory.newInstance().createXMLEventReader(input);
    resultFields = new ResultFields();
    testAttributes = new LinkedList<TestAttributes>();
}

From source file:StAXStreamTreeViewer.java

public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode current, File file)
        throws XMLStreamException, FileNotFoundException {
    FileInputStream inputStream = new FileInputStream(file);
    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader reader = inputFactory.createXMLStreamReader(inputStream);

    addStartDocumentNodes(reader, current);

    parseRestOfDocument(reader, current);
}