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:de.tuebingen.uni.sfs.germanet.api.WiktionaryLoader.java

/**
 * Loads <code>WiktionaryParaphrases</code> from the given streams into this
 * <code>WiktionaryLoader</code>'s <code>GermaNet</code> object.
 * @param inputStreams the list of streams containing <code>WiktionaryParaphrases</code> data
 * @param xmlNames the names of the streams
 * @throws javax.xml.stream.XMLStreamException
 *///from ww w . ja  v a 2  s  .  c  o  m
protected void loadWiktionary(List<InputStream> inputStreams, List<String> xmlNames) throws XMLStreamException {

    for (int i = 0; i < inputStreams.size(); i++) {
        if (xmlNames.get(i).startsWith("wiktionary")) {
            logger.debug("Loading input stream " + xmlNames.get(i) + "...");
            XMLInputFactory factory = XMLInputFactory.newInstance();
            XMLStreamReader parser = factory.createXMLStreamReader(inputStreams.get(i));
            int event;
            String nodeName;

            //Parse entire file, looking for Wiktionary paraphrase start elements
            while (parser.hasNext()) {
                event = parser.next();
                switch (event) {
                case XMLStreamConstants.START_DOCUMENT:
                    namespace = parser.getNamespaceURI();
                    break;
                case XMLStreamConstants.START_ELEMENT:
                    nodeName = parser.getLocalName();
                    if (nodeName.equals(GermaNet.XML_WIKTIONARY_PARAPHRASE)) {
                        WiktionaryParaphrase wiki = processWiktionaryParaphrase(parser);
                        germaNet.addWiktionaryParaphrase(wiki);
                    }
                    break;
                }
            }
            parser.close();
        }
    }

    logger.debug("Done.");

}

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

/**
 * Reads from the XML stream and tries to determine if the ACI response contains an error or not. The stream is left
 * at the end of the body content of the <tt>/autnresponse/response</tt> element, if one could be found.
 * @param xmlStreamReader The response to process
 * @return <tt>true</tt> if the response contains an error, <tt>false</tt> otherwise
 * @throws javax.xml.stream.XMLStreamException If there was a problem reading the IDOL Server response.
 *//* w ww.  ja  va  2s  . c  o  m*/
protected boolean isErrorResponse(final XMLStreamReader xmlStreamReader) throws XMLStreamException {
    LOGGER.trace("isErrorResponse() called...");

    // Get the /autnresponse/response element...
    while (xmlStreamReader.hasNext()) {
        // Get the event type...
        final int eventType = xmlStreamReader.next();

        // Check to see if it's a start event...
        if ((XMLEvent.START_ELEMENT == eventType)
                && ("response".equalsIgnoreCase(xmlStreamReader.getLocalName()))) {
            return "ERROR".equalsIgnoreCase(xmlStreamReader.getElementText());
        }
    }

    // Couldn't find a /autnresponse/response element...
    throw new XMLStreamException("Unable to find /autnresponse/response element.");
}

From source file:com.ikanow.infinit.e.harvest.extraction.document.file.XmlToMetadataParser.java

/**
 * Parses XML and returns a new feed with the resulting HashMap as Metadata
 * @param reader XMLStreamReader using Stax to avoid out of memory errors
 * @return List of Feeds with their Metadata set
 *///from   w w w .j  a  v a  2  s.  c  o  m
public List<DocumentPojo> parseDocument(XMLStreamReader reader) throws XMLStreamException {
    DocumentPojo doc = new DocumentPojo();
    List<DocumentPojo> docList = new ArrayList<DocumentPojo>();
    boolean justIgnored = false;
    boolean hitIdentifier = false;

    while (reader.hasNext()) {
        int eventCode = reader.next();

        switch (eventCode) {
        case (XMLStreamReader.START_ELEMENT): {
            String tagName = reader.getLocalName();

            if (null == levelOneFields || levelOneFields.size() == 0) {
                levelOneFields = new ArrayList<String>();
                levelOneFields.add(tagName);
                doc = new DocumentPojo();
                sb.delete(0, sb.length());
                justIgnored = false;
            } else if (levelOneFields.contains(tagName)) {
                sb.delete(0, sb.length());
                doc = new DocumentPojo();
                justIgnored = false;
            } else if ((null != ignoreFields) && ignoreFields.contains(tagName)) {
                justIgnored = true;
            } else {
                if (this.bPreserveCase) {
                    sb.append("<").append(tagName).append(">");
                } else {
                    sb.append("<").append(tagName.toLowerCase()).append(">");
                }
                justIgnored = false;
            }
            hitIdentifier = tagName.equalsIgnoreCase(PKElement);

            if (!justIgnored && (null != this.AttributePrefix)) { // otherwise ignore attributes anyway
                int nAttributes = reader.getAttributeCount();
                StringBuffer sb2 = new StringBuffer();
                for (int i = 0; i < nAttributes; ++i) {
                    sb2.setLength(0);
                    sb.append('<');

                    sb2.append(this.AttributePrefix);
                    if (this.bPreserveCase) {
                        sb2.append(reader.getAttributeLocalName(i).toLowerCase());
                    } else {
                        sb2.append(reader.getAttributeLocalName(i));
                    }
                    sb2.append('>');

                    sb.append(sb2);
                    sb.append("<![CDATA[").append(reader.getAttributeValue(i).trim()).append("]]>");
                    sb.append("</").append(sb2);
                }
            }
        }
            break;

        case (XMLStreamReader.CHARACTERS): {
            if (reader.getText().trim().length() > 0 && justIgnored == false)
                sb.append("<![CDATA[").append(reader.getText().trim()).append("]]>");
            if (hitIdentifier) {
                String tValue = reader.getText().trim();
                if (null != XmlSourceName) {
                    if (tValue.length() > 0) {
                        doc.setUrl(XmlSourceName + tValue);
                    }
                }
            }
        }
            break;
        case (XMLStreamReader.END_ELEMENT): {
            hitIdentifier = !reader.getLocalName().equalsIgnoreCase(PKElement);
            if ((null != ignoreFields) && !ignoreFields.contains(reader.getLocalName())) {
                if (levelOneFields.contains(reader.getLocalName())) {
                    JSONObject json;
                    try {
                        json = XML.toJSONObject(sb.toString());
                        for (String names : JSONObject.getNames(json)) {
                            JSONObject rec = null;
                            JSONArray jarray = null;

                            try {
                                jarray = json.getJSONArray(names);
                                doc.addToMetadata(names, handleJsonArray(jarray, false));
                            } catch (JSONException e) {
                                try {
                                    rec = json.getJSONObject(names);
                                    doc.addToMetadata(names, convertJsonObjectToLinkedHashMap(rec));
                                } catch (JSONException e2) {
                                    try {
                                        Object[] val = { json.getString(names) };
                                        doc.addToMetadata(names, val);
                                    } catch (JSONException e1) {
                                        e1.printStackTrace();
                                    }
                                }
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    sb.delete(0, sb.length());
                    docList.add(doc);
                } else {
                    if (this.bPreserveCase) {
                        sb.append("</").append(reader.getLocalName()).append(">");
                    } else {
                        sb.append("</").append(reader.getLocalName().toLowerCase()).append(">");
                    }

                }
            }
        } // (end case)
            break;
        } // (end switch)
    }
    return docList;
}

From source file:com.prowidesoftware.swift.io.parser.MxParser.java

/**
 * Takes an xml with an MX message and detects the specific message type
 * parsing just the namespace from the Document element. If the Document
 * element is not present, or without the namespace or if the namespace url
 * contains invalid content it will return null.
 * <br><br>//from w  w w.j  a va  2 s  . c  o m
 * Example of a recognizable Document element:<br>
 * <Doc:Document xmlns:Doc="urn:swift:xsd:camt.003.001.04" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 * <br>
 * The implementation is intended to be lightweight and efficient, based on {@link javax.xml.stream.XMLStreamReader} 
 *
 * @return id with the detected MX message type or null if it cannot be determined.
 * @since 7.7
 */
public MxId detectMessage() {
    if (StringUtils.isBlank(this.buffer)) {
        log.log(Level.SEVERE, "cannot detect message from null or empty content");
        return null;
    }
    final javax.xml.stream.XMLInputFactory xif = javax.xml.stream.XMLInputFactory.newInstance();
    try {
        final javax.xml.stream.XMLStreamReader reader = xif
                .createXMLStreamReader(new StringReader(this.buffer));
        while (reader.hasNext()) {
            int event = reader.next();
            if (javax.xml.stream.XMLStreamConstants.START_ELEMENT == event
                    && reader.getLocalName().equals(DOCUMENT_LOCALNAME)) {
                if (reader.getNamespaceCount() > 0) {
                    //log.finest("ELEMENT START: " + reader.getLocalName() + " , namespace count is: " + reader.getNamespaceCount());
                    for (int nsIndex = 0; nsIndex < reader.getNamespaceCount(); nsIndex++) {
                        final String nsPrefix = StringUtils.trimToNull(reader.getNamespacePrefix(nsIndex));
                        final String elementPrefix = StringUtils.trimToNull(reader.getPrefix());
                        if (StringUtils.equals(nsPrefix, elementPrefix)) {
                            String nsId = reader.getNamespaceURI(nsIndex);
                            //log.finest("\tNamepsace prefix: " + nsPrefix + " associated with URI " + nsId);
                            return new MxId(nsId);
                        }
                    }
                }
            }
        }
    } catch (final Exception e) {
        log.log(Level.SEVERE, "error while detecting message", e);
    }
    return null;
}

From source file:net.landora.animeinfo.anidb.AniDBHTTPManager.java

public Anime downloadAnime(int aid) {
    InputStream is = null;/*www . j  a  va  2s. co m*/
    try {

        //            URL url = new URL(String.format("%s&request=anime&aid=%d", HTTP_URL, aid));
        //            is = new GZIPInputStream(url.openStream());
        is = new BufferedInputStream(new FileInputStream("/home/bdickie/anidb/http_test.xml"));

        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(is);

        reader.nextTag();
        reader.require(XMLStreamReader.START_ELEMENT, null, "anime");

        Anime anime = new Anime();

        anime.setAnimeId(Integer.parseInt(reader.getAttributeValue(null, "id")));
        anime.setHentai(Boolean.parseBoolean(reader.getAttributeValue(null, "restricted")));
        anime.setLastLoaded(Calendar.getInstance());

        while (reader.nextTag() != XMLStreamReader.END_ELEMENT) {
            String tagName = reader.getLocalName();
            if (tagName.equals("type")) {
                anime.setType(nextString(reader));
            } else if (tagName.equals("episodecount")) {
                anime.setEpisodeCount(Integer.parseInt(nextString(reader)));
            } else if (tagName.equals("startdate")) {
                //                    anime.setStartDate(nextString(reader));
            } else if (tagName.equals("enddate")) {
                //                    anime.setEndDate(nextString(reader));
            } else if (tagName.equals("description")) {
                anime.setDescription(nextString(reader));
            } else if (tagName.equals("picture")) {
                anime.setPictureFileName(nextString(reader));
            } else if (tagName.equals("titles")) {
                List<AnimeName> names = new ArrayList<AnimeName>();
                while (reader.nextTag() != XMLStreamReader.END_ELEMENT) {
                    reader.require(XMLStreamReader.START_ELEMENT, null, "title");

                    AnimeName name = new AnimeName();
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        String aname = reader.getAttributeLocalName(i);
                        if (aname.equals("type")) {
                            name.setType(reader.getAttributeValue(i));
                        } else if (aname.equals("lang")) {
                            name.setLanguage(reader.getAttributeValue(i));
                        }

                    }

                    name.setName(nextString(reader));
                    name.setAnime(anime);
                    names.add(name);
                }

                for (AnimeName name : names) {
                    if (name.getType().equalsIgnoreCase("main")) {
                        anime.setNameMain(name.getName());
                    } else if (name.getType().equalsIgnoreCase("official")
                            && name.getLanguage().equalsIgnoreCase("en")) {
                        anime.setNameEnglish(name.getName());
                    }
                }
                anime.setNames(names);
            } else if (tagName.equals("ratings")) {

                while (reader.nextTag() != XMLStreamReader.END_ELEMENT) {
                    String tagName2 = reader.getLocalName();
                    int count = Integer.parseInt(reader.getAttributeValue(null, "count"));
                    float value = Float.parseFloat(nextString(reader));
                    if (tagName2.equals("permanent")) {
                        anime.setRatingPermanent(value);
                        anime.setRatingPermanentVotes(count);
                    } else if (tagName2.equals("temporary")) {
                        anime.setRatingTemporary(value);
                        anime.setRatingTemporaryVotes(count);
                    }
                }

            } else if (tagName.equals("categories")) {

                while (reader.nextTag() != XMLStreamReader.END_ELEMENT) {
                    reader.require(XMLStreamReader.START_ELEMENT, null, "category");

                    int categoryid = Integer.parseInt(reader.getAttributeValue(null, "id"));
                    int weight = Integer.parseInt(reader.getAttributeValue(null, "weight"));

                    AnimeCategory category = AnimeDBA.getAnimeCategory(categoryid);
                    if (category == null) {
                        return null;
                    }

                    ignoreTag(reader);
                }
            } else {
                ignoreTag(reader);
            }

        }
        reader.close();

        return anime;
    } catch (Exception e) {
        log.error("Error downloading anime: " + aid, e);
        return null;
    } finally {
        if (is != null) {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:de.uzk.hki.da.sb.SIPFactoryTest.java

/**
 * @param premis/*from   w ww . ja v a2s . c  o m*/
 * @param publicRights 
 */
private boolean checkPremisFilePubStartDate(File premis, ContractRights rights) {

    XMLInputFactory inputFactory = XMLInputFactory.newInstance();
    XMLStreamReader streamReader;
    try {
        streamReader = inputFactory.createXMLStreamReader(new FileInputStream(premis));
        while (streamReader.hasNext()) {
            int event = streamReader.next();
            switch (event) {
            case XMLStreamConstants.START_ELEMENT:
                if (streamReader.getLocalName().equals("startDate")) {

                    String startDate = streamReader.getElementText().substring(0, 10);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String publicDate = sdf.format(rights.getPublicRights().getStartDate());
                    if (startDate.trim().equals(publicDate.trim())) {
                        return true;
                    }
                }
            default:
                break;
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (XMLStreamException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:lux.search.highlight.XmlHighlighter.java

@Override
public void handleEvent(XMLStreamReader reader, int eventType) throws XMLStreamException {

    switch (eventType) {
    case XMLStreamConstants.START_DOCUMENT:
        xmlStreamReader = reader; // cache the reader so we can pull events
        super.handleEvent(reader, eventType);
        break;//ww  w  .  j  a v  a 2 s  . c  om

    case XMLStreamConstants.START_ELEMENT:
        super.handleEvent(reader, eventType);
        xmlStreamTokens
                .pushElement(new QName(reader.getNamespaceURI(), reader.getLocalName(), reader.getPrefix()));
        break;

    case XMLStreamConstants.END_ELEMENT:
        super.handleEvent(reader, eventType);
        xmlStreamTokens.popElement();
        break;

    case XMLStreamConstants.COMMENT:
    case XMLStreamConstants.PROCESSING_INSTRUCTION:
        super.handleEvent(reader, eventType);
        break;

    case XMLStreamConstants.CDATA:
        throw new XMLStreamException("unexpected CDATA event");

    case XMLStreamConstants.SPACE:
        super.handleEvent(reader, eventType);
        break;

    case XMLStreamConstants.CHARACTERS:
        textReader.text();
        try {
            highlightTextNode();
        } catch (IOException e) {
            throw new XMLStreamException(e);
        }
        break;

    case XMLStreamConstants.ENTITY_REFERENCE:
        throw new XMLStreamException("unexpected entity reference event");

    default:
        super.handleEvent(reader, eventType);
    }

}

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 a  va2  s.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:com.prowidesoftware.swift.io.parser.MxParser.java

/**
 * Convenient API to get structure information from an MX message.
 * <br ><br>//from w ww  .j a v a 2 s . co  m
 * This can be helpful when the actual content of an XML is unknown and 
 * some preprocessing of the XML must be done in order to parse or
 * validate its content properly.
 * <br >
 * The implementation is intended to be lightweight and efficient, based on {@link javax.xml.stream.XMLStreamReader}
 *  
 * @since 7.8.4
 */
public MxStructureInfo analizeMessage() {
    if (this.info != null) {
        return this.info;
    }
    this.info = new MxStructureInfo();
    if (StringUtils.isBlank(this.buffer)) {
        log.log(Level.WARNING, "cannot analize message from null or empty content");
        return this.info;
    }
    final javax.xml.stream.XMLInputFactory xif = javax.xml.stream.XMLInputFactory.newInstance();
    try {
        final javax.xml.stream.XMLStreamReader reader = xif
                .createXMLStreamReader(new StringReader(this.buffer));
        boolean first = true;
        while (reader.hasNext()) {
            int event = reader.next();
            if (javax.xml.stream.XMLStreamConstants.START_ELEMENT == event) {
                if (reader.getLocalName().equals(DOCUMENT_LOCALNAME)) {
                    this.info.containsDocument = true;
                    this.info.documentNamespace = readNamespace(reader);
                    this.info.documentPrefix = StringUtils.trimToNull(reader.getPrefix());
                } else if (reader.getLocalName().equals(HEADER_LOCALNAME)) {
                    this.info.containsHeader = true;
                    this.info.headerNamespace = readNamespace(reader);
                    this.info.headerPrefix = StringUtils.trimToNull(reader.getPrefix());
                } else if (first) {
                    this.info.containsWrapper = true;
                }
                first = false;
            }
        }
    } catch (final Exception e) {
        log.log(Level.SEVERE, "error while analizing message: " + e.getMessage());
        info.exception = e;
    }
    return this.info;
}

From source file:net.solarnetwork.util.JavaBeanXmlSerializer.java

/**
 * Parse XML into a simple Map structure.
 * //www  .j ava  2  s .  c om
 * @param in
 *        the input stream to parse
 * @return a Map of the XML
 */
public Map<String, Object> parseXml(InputStream in) {
    Deque<Map<String, Object>> stack = new LinkedList<Map<String, Object>>();
    Map<String, Object> result = null;
    XMLStreamReader reader = startParse(in);
    try {
        int eventType;
        boolean parsing = true;
        while (parsing) {
            eventType = reader.next();
            switch (eventType) {
            case XMLStreamConstants.END_DOCUMENT:
                parsing = false;
                break;

            case XMLStreamConstants.START_ELEMENT:
                String name = reader.getLocalName();
                if (stack.isEmpty()) {
                    result = new LinkedHashMap<String, Object>();
                    stack.push(result);
                } else {
                    Map<String, Object> el = new LinkedHashMap<String, Object>();
                    putMapValue(stack.peek(), name, el);
                    stack.push(el);
                }
                parseElement(stack.peek(), reader);
                break;

            case XMLStreamConstants.END_ELEMENT:
                stack.pop();
                break;

            }
        }
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    } finally {
        endParse(reader);
    }
    return result;
}