Example usage for javax.xml.stream XMLStreamReader getLocalName

List of usage examples for javax.xml.stream XMLStreamReader getLocalName

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamReader getLocalName.

Prototype

public String getLocalName();

Source Link

Document

Returns the (local) name of the current event.

Usage

From source file:Main.java

public static void dumpXML(XMLStreamReader parser) throws XMLStreamException {
    int depth = 0;
    do {//from w  w  w. j a  v a  2 s  .  co  m
        switch (parser.getEventType()) {
        case XMLStreamConstants.START_ELEMENT:
            for (int i = 1; i < depth; ++i) {
                System.out.print("    ");
            }
            System.out.print("<");
            System.out.print(parser.getLocalName());
            for (int i = 0; i < parser.getAttributeCount(); ++i) {
                System.out.print(" ");
                System.out.print(parser.getAttributeLocalName(i));
                System.out.print("=\"");
                System.out.print(parser.getAttributeValue(i));
                System.out.print("\"");
            }
            System.out.println(">");

            ++depth;
            break;
        case XMLStreamConstants.END_ELEMENT:
            --depth;
            for (int i = 1; i < depth; ++i) {
                System.out.print("    ");
            }
            System.out.print("</");
            System.out.print(parser.getLocalName());
            System.out.println(">");
            break;
        case XMLStreamConstants.CHARACTERS:
            for (int i = 1; i < depth; ++i) {
                System.out.print("    ");
            }

            System.out.println(parser.getText());
            break;
        }

        if (depth > 0)
            parser.next();
    } while (depth > 0);
}

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

/**
 * Read modes.xml and create {@code Scale instances} from those definitions.
 *//*w ww  .  j a va 2  s. com*/
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.utah.further.core.api.xml.XmlUtil.java

/**
 * Basic StAX element printout. For more sophisticated functionality, use
 * {@link XmlStreamPrinter}./*  ww  w.  j  a  va2  s .  co m*/
 * 
 * @param reader
 *            reader
 * @return reader's next element textual representation
 */
public static String getEventSimpleString(final XMLStreamReader reader) {
    switch (reader.getEventType()) {
    case XMLStreamConstants.START_ELEMENT:
        return "START_ELEMENT:\t\"" + reader.getLocalName() + "\"";
    case XMLStreamConstants.END_ELEMENT:
        return "END_ELEMENT:\t\"" + reader.getLocalName() + "\"";
    case XMLStreamConstants.START_DOCUMENT:
        return "START_DOCUMENT";
    case XMLStreamConstants.END_DOCUMENT:
        return "END_DOCUMENT";
    case XMLStreamConstants.CHARACTERS:
        return "CHARACTERS:\t\"" + reader.getText() + "\"" + " blank? "
                + StringUtils.isWhitespace(reader.getText());
    case XMLStreamConstants.SPACE:
        return "SPACE:\t\"" + reader.getText() + "\"";
    default:
        return "EVENT:\t" + reader.getEventType();
    }
}

From source file:com.auditbucket.client.Importer.java

static long processXMLFile(String file, AbRestClient abExporter, XmlMappable mappable, boolean simulateOnly)
        throws ParserConfigurationException, IOException, SAXException, JDOMException, DatagioException {
    try {//  w  w  w  .j  av  a2 s .c o m
        long rows = 0;
        StopWatch watch = new StopWatch();
        StreamSource source = new StreamSource(file);
        XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = xif.createXMLStreamReader(source);
        mappable.positionReader(xsr);
        List<CrossReferenceInputBean> referenceInputBeans = new ArrayList<>();

        String docType = mappable.getDataType();
        watch.start();
        try {
            long then = new DateTime().getMillis();
            while (xsr.getLocalName().equals(docType)) {
                XmlMappable row = mappable.newInstance(simulateOnly);
                String json = row.setXMLData(xsr);
                MetaInputBean header = (MetaInputBean) row;
                if (!header.getCrossReferences().isEmpty()) {
                    referenceInputBeans.add(new CrossReferenceInputBean(header.getFortress(),
                            header.getCallerRef(), header.getCrossReferences()));
                    rows = rows + header.getCrossReferences().size();
                }
                LogInputBean logInputBean = new LogInputBean("system", new DateTime(header.getWhen()), json);
                header.setLog(logInputBean);
                //logger.info(json);
                xsr.nextTag();
                writeAudit(abExporter, header, mappable.getClass().getCanonicalName());
                rows++;
                if (rows % 500 == 0 && !simulateOnly)
                    logger.info("Processed {} elapsed seconds {}", rows,
                            new DateTime().getMillis() - then / 1000d);

            }
        } finally {
            abExporter.flush(mappable.getClass().getCanonicalName(), mappable.getABType());
        }
        if (!referenceInputBeans.isEmpty()) {
            logger.debug("Wrote [{}] cross references",
                    writeCrossReferences(abExporter, referenceInputBeans, "Cross References"));
        }
        return endProcess(watch, rows);

    } catch (XMLStreamException | JAXBException e1) {
        throw new IOException(e1);
    }
}

From source file:edu.utah.further.core.api.xml.XmlUtil.java

/**
 * @param xmlReader//ww w.j a va 2s.c o  m
 * @return
 */
public static String getName(final XMLStreamReader xmlReader) {
    if (xmlReader.hasName()) {
        final String prefix = xmlReader.getPrefix();
        final String uri = xmlReader.getNamespaceURI();
        final String localName = xmlReader.getLocalName();
        return getName(prefix, uri, localName);
    }
    return null;
}

From source file:Main.java

/**
 * Test if the current event is an element tag with the given namespace and name.
 * If the namespace URI is null it is not checked for equality,
 * if the local name is null it is not checked for equality.
 * @param reader must not be {@code null}
 * @param event START_ELEMENT or END_ELEMENT
 * @param uri the namespace URI of the element, may be null
 * @param name the local name of the element, may be null
 * @param slash "" or "/", for error message
 * @throws XMLStreamException if the required values are not matched.
 *///from   www .java  2s  . c o  m
private static void requireElement(XMLStreamReader reader, int event, String uri, String name, String slash)
        throws XMLStreamException {
    // Note: reader.require(event, uri, name) has a lousy error message

    if (reader.getEventType() != event)
        throw new XMLStreamException("expected <" + slash + name + ">", reader.getLocation());

    if (uri != null) {
        String found = reader.getNamespaceURI();
        if (!found.equals(uri))
            throw new XMLStreamException(
                    "expected <" + slash + name + "> with namespace [" + uri + "], found [" + found + "]",
                    reader.getLocation());
    }

    if (name != null) {
        String found = reader.getLocalName();
        if (!found.equals(name))
            throw new XMLStreamException("expected <" + slash + name + ">, found <" + slash + found + ">",
                    reader.getLocation());
    }
}

From source file:MDRevealer.ResistanceTests.java

private static ArrayList<HashMap<String, String>> parse_test(File rt_input)
        throws XMLStreamException, FileNotFoundException {
    XMLInputFactory xif = XMLInputFactory.newInstance();
    XMLStreamReader xsr = xif.createXMLStreamReader(new FileInputStream(rt_input));
    ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> hm = new HashMap<String, String>();
    String key = "null";
    while (xsr.hasNext() == true) {

        int constant = xsr.next();

        switch (constant) {
        case XMLStreamConstants.START_ELEMENT:
            key = xsr.getLocalName();
            if (xsr.getAttributeCount() > 0) {
                for (int i = 0; i < xsr.getAttributeCount(); i++) {
                    hm.put(xsr.getAttributeLocalName(i), xsr.getAttributeValue(i));
                }/*from w w  w. j  ava  2s  .c  om*/
                test.add(hm);
                hm = new HashMap<String, String>();
            }
            break;
        case XMLStreamConstants.CHARACTERS:
            if (!xsr.isWhiteSpace()) {
                hm.put(key, xsr.getText());
                test.add(hm);
            }
            hm = new HashMap<String, String>();
            break;
        case XMLStreamConstants.END_ELEMENT:
            if (xsr.getLocalName().equals("condition")) {
                hm.put("condition_over", "true");
                test.add(hm);
                hm = new HashMap<String, String>();
            }
            break;
        }
    }
    return test;
}

From source file:edu.stanford.cfuller.colocalization3d.correction.Correction.java

/**
 * Reads a stored correction from disk.// www . j a va 2s.  c o  m
 * 
 * @param filename                  The name of the file containing the Correction that was previously written to disk.
 * @return                          The Correction contained in the file.
 * @throws java.io.IOException      if the Correction cannot be successfully read.
 * @throws ClassNotFoundException   if the file does not contain a Correction.
 */
public static Correction readFromDisk(String filename) throws java.io.IOException, ClassNotFoundException {

    File f = new File(filename);

    FileReader fr = new FileReader(f);

    XMLStreamReader xsr = null;
    String encBinData = null;

    try {
        xsr = XMLInputFactory.newFactory().createXMLStreamReader(fr);

        while (xsr.hasNext()) {

            int event = xsr.next();

            if (event != XMLStreamReader.START_ELEMENT)
                continue;

            if (xsr.hasName() && xsr.getLocalName() == BINARY_DATA_ELEMENT) {

                encBinData = xsr.getElementText();

                break;

            }

        }
    } catch (XMLStreamException e) {
        java.util.logging.Logger.getLogger(LOG_NAME)
                .severe("Exception encountered while reading XML correction: " + e.getMessage());
    }
    byte[] binData = (new HexBinaryAdapter()).unmarshal(encBinData);

    ObjectInputStream oi = new ObjectInputStream(new ByteArrayInputStream(binData));

    Object o = oi.readObject();

    return (Correction) o;

}

From source file:com.microsoft.tfs.core.memento.XMLMemento.java

/**
 * Reads an {@link XMLMemento} from the next XML element in the given given
 * {@link InputStream} in the encoding specified as
 * {@link #DEFAULT_ENCODING}./*from   www.j a  va 2 s . c  o m*/
 *
 * @param inputStream
 *        the {@link InputStream} read to read the {@link XMLMemento} from
 *        (must not be <code>null</code>)
 * @param encoding
 *        the encoding to use when reading the {@link InputStream},
 *        <code>null</code> to use the default encoding (
 *        {@link #DEFAULT_ENCODING})
 * @return a Memento modeled as the first Element in the document.
 * @throws MementoException
 *         if an error prevented the creation of the Memento.
 */
public static XMLMemento read(final InputStream inputStream, final String encoding) throws MementoException {
    Check.notNull(inputStream, "inputStream"); //$NON-NLS-1$

    try {
        final XMLStreamReader reader = StaxFactoryProvider.getXMLInputFactory(true)
                .createXMLStreamReader(inputStream, (encoding != null) ? encoding : DEFAULT_ENCODING);

        XMLMemento memento = null;
        String localName;
        int event;

        do {
            event = reader.next();

            if (event == XMLStreamConstants.START_ELEMENT) {
                localName = reader.getLocalName();

                memento = new XMLMemento(localName);
                memento.readFromElement(reader);
            }
        } while (event != XMLStreamConstants.END_ELEMENT && event != XMLStreamConstants.END_DOCUMENT);

        reader.close();

        return memento;
    } catch (final XMLStreamException e) {
        log.error("Error reading", e); //$NON-NLS-1$
        throw new MementoException(e);
    }
}

From source file:sdmx.net.service.nomis.NOMISRESTServiceRegistry.java

public static List<NOMISGeography> parseGeography(InputStream in, String cubeId, String cubeName)
        throws XMLStreamException {
    List<NOMISGeography> geogList = new ArrayList<NOMISGeography>();
    String tagContent = null;/*from w  w w. j a v  a 2  s . c o  m*/
    XMLInputFactory factory = XMLInputFactory.newInstance();

    XMLStreamReader reader = factory.createXMLStreamReader(in);
    int state = 0;
    String lastLang = null;
    while (reader.hasNext()) {
        int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
            if (reader.getLocalName().equals("Type")) {
                NOMISGeography geog = new NOMISGeography();
                geog.setCubeId(cubeId);
                geog.setCubeName(cubeName);
                geog.setGeography(reader.getAttributeValue("", "value"));
                geog.setGeographyName(reader.getAttributeValue("", "name"));
                geogList.add(geog);
            }
            break;
        case XMLStreamConstants.END_ELEMENT:
            break;
        }
    }
    return geogList;
}