Example usage for javax.xml.stream.events StartElement getAttributeByName

List of usage examples for javax.xml.stream.events StartElement getAttributeByName

Introduction

In this page you can find the example usage for javax.xml.stream.events StartElement getAttributeByName.

Prototype

public Attribute getAttributeByName(QName name);

Source Link

Document

Returns the attribute referred to by the qname.

Usage

From source file:com.microfocus.application.automation.tools.octane.tests.TestResultIterator.java

@Override
public boolean hasNext() {
    try {//  w ww . j  a va 2s  .  com
        while (items.isEmpty() && !closed) {
            if (reader.hasNext()) {
                XMLEvent event = reader.nextEvent();
                if (event instanceof StartElement) {
                    Attribute attribute;
                    StartElement element = (StartElement) event;
                    String localName = element.getName().getLocalPart();
                    if ("test_run".equals(localName)) {
                        String moduleName = element.getAttributeByName(new QName("module")).getValue();
                        String packageName = element.getAttributeByName(new QName("package")).getValue();
                        String className = element.getAttributeByName(new QName("class")).getValue();
                        String testName = element.getAttributeByName(new QName("name")).getValue();
                        long duration = Long
                                .valueOf(element.getAttributeByName(new QName("duration")).getValue());
                        TestResultStatus status = TestResultStatus
                                .fromPrettyName(element.getAttributeByName(new QName("status")).getValue());
                        long started = Long
                                .valueOf(element.getAttributeByName(new QName("started")).getValue());
                        items.add(new JUnitTestResult(moduleName, packageName, className, testName, status,
                                duration, started, null, null));
                    } else if ("build".equals(localName)) {
                        attribute = element.getAttributeByName(new QName("server_id"));
                        if (attribute != null) {
                            serverId = attribute.getValue();
                        }
                        attribute = element.getAttributeByName(new QName("job_id"));
                        if (attribute != null) {
                            jobId = attribute.getValue();
                        }
                        attribute = element.getAttributeByName(new QName("build_id"));
                        if (attribute != null) {
                            buildId = attribute.getValue();
                        }
                        attribute = element.getAttributeByName(new QName("sub_type"));
                        if (attribute != null) {
                            this.subType = attribute.getValue();
                        }
                    }
                }
            } else {
                closed = true;
                IOUtils.closeQuietly(input);
                reader.close();
            }
        }
        return !items.isEmpty();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.predic8.membrane.core.multipart.XOPReconstitutor.java

private byte[] fillInXOPParts(InputStream inputStream, HashMap<String, Part> parts)
        throws XMLStreamException, FactoryConfigurationError {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(baos);

    try {/*from w  w  w .j  a  v  a2 s  .  com*/
        XMLEventReader parser = createEventReaderFromStream(inputStream);

        boolean xopIncludeOpen = false;

        while (parser.hasNext()) {
            XMLEvent event = parser.nextEvent();

            if (event instanceof StartElement) {
                StartElement start = (StartElement) event;
                if (XOP_NAMESPACE_URI.equals(start.getName().getNamespaceURI())
                        && start.getName().getLocalPart().equals("Include")) {
                    String href = start.getAttributeByName(new QName("href")).getValue();

                    if (href.startsWith("cid:"))
                        href = href.substring(4);

                    Part p = parts.get("<" + href + ">");
                    if (p == null)
                        throw new RuntimeException("Did not find multipart with id " + href);

                    writer.add(p.asXMLEvent());
                    xopIncludeOpen = true;
                    continue;
                }
            } else if (event instanceof EndElement) {
                EndElement start = (EndElement) event;
                if (XOP_NAMESPACE_URI.equals(start.getName().getNamespaceURI())
                        && start.getName().getLocalPart().equals("Include") && xopIncludeOpen) {
                    xopIncludeOpen = false;
                    continue;
                }
            }

            writer.add(event);
        }
        writer.flush();
    } catch (XMLStreamException e) {
        log.warn("Received not-wellformed XML.");
        return null;
    }
    return baos.toByteArray();
}

From source file:fr.dutra.confluence2wordpress.core.sync.DefaultAttachmentsSynchronizer.java

private Set<Attachment> parseForAttachments(ContentEntityObject page) throws SynchronizationException {
    Set<Attachment> attachments = new HashSet<Attachment>();
    try {/*w  w  w .  j  av a 2  s.  c om*/
        XMLEventReader r = StaxUtils.getReader(page);
        String fileName = null;
        String pageTitle = null;
        String spaceKey = null;
        try {
            while (r.hasNext()) {
                XMLEvent e = r.nextEvent();
                if (e.isStartElement()) {
                    StartElement startElement = e.asStartElement();
                    QName name = startElement.getName();
                    if (name.equals(ATTACHMENT_QNAME)) {
                        Attribute att = startElement.getAttributeByName(FILENAME_QNAME);
                        if (att != null) {
                            fileName = att.getValue();
                        }
                    } else if (name.equals(PAGE_QNAME)) {
                        Attribute title = startElement.getAttributeByName(TITLE_QNAME);
                        if (title != null) {
                            pageTitle = title.getValue();
                        }
                        Attribute space = startElement.getAttributeByName(SPACE_QNAME);
                        if (space != null) {
                            spaceKey = space.getValue();
                        }
                    }
                } else if (e.isEndElement()) {
                    EndElement endElement = e.asEndElement();
                    if (endElement.getName().equals(ATTACHMENT_QNAME)) {
                        ContentEntityObject attachmentPage;
                        if (pageTitle == null) {
                            attachmentPage = page;
                        } else {
                            attachmentPage = pageManager.getPage(spaceKey, pageTitle);
                        }
                        Attachment attachment = attachmentManager.getAttachment(attachmentPage, fileName);
                        attachments.add(attachment);
                        fileName = null;
                        pageTitle = null;
                        spaceKey = null;
                    }
                }
            }
        } finally {
            r.close();
        }
    } catch (XMLStreamException e) {
        throw new SynchronizationException("Cannot read page: " + page.getTitle(), e);
    }
    return attachments;
}

From source file:fr.openwide.talendalfresco.rest.client.ClientImportCommand.java

protected void handleResponseContentEvent(XMLEvent event) {
    String[] resultLog;// w  w w.j ava  2  s . c om
    boolean isSuccessLog;
    switch (event.getEventType()) {
    case XMLEvent.START_ELEMENT:
        StartElement startElement = event.asStartElement();
        String elementName = startElement.getName().getLocalPart();
        if (RestConstants.RES_IMPORT_SUCCESS.equals(elementName)) {
            isSuccessLog = true;
        } else if (RestConstants.RES_IMPORT_ERROR.equals(elementName)) {
            isSuccessLog = false;
        } else {
            break;
        }

        Attribute noderefAttr = startElement.getAttributeByName(new QName(RestConstants.RES_IMPORT_NODEREF));
        String noderef = (noderefAttr == null) ? null : noderefAttr.getValue();
        Attribute doctypeAttr = startElement.getAttributeByName(new QName(RestConstants.RES_IMPORT_DOCTYPE));
        String doctype = (doctypeAttr == null) ? null : doctypeAttr.getValue();
        resultLog = new String[] { elementName, // error or success
                startElement.getAttributeByName(new QName(RestConstants.RES_IMPORT_NAMEPATH)).getValue(),
                startElement.getAttributeByName(new QName(RestConstants.RES_IMPORT_MESSAGE)).getValue(),
                startElement.getAttributeByName(new QName(RestConstants.RES_IMPORT_DATE)).getValue(), noderef,
                doctype };
        resultLogs.add(resultLog);
        if (isSuccessLog) {
            successLogs.add(resultLog);
        } else { // errorLog
            errorLogs.add(resultLog);
        }
        break;
    }
}

From source file:edu.monash.merc.system.parser.xml.GPMWSXmlParser.java

public List<GPMEntryBean> parseGPMXml(String fileName, XMLInputFactory2 factory2) {

    xmlif2 = factory2;// www  . j a  v a 2 s  . c o m
    logger.info("Starting to parse " + fileName);

    XMLEventReader2 xmlEventReader = null;
    List<GPMEntryBean> gpmEntryBeans = new ArrayList<GPMEntryBean>();
    try {
        xmlEventReader = (XMLEventReader2) xmlif2.createXMLEventReader(new FileInputStream(fileName));

        QName proteinQN = new QName(ELE_GPM_PROTEIN);
        QName enspQN = new QName(ATTR_GPM_ENSP);
        QName ensgQN = new QName(ATTR_GPM_ENSG);
        QName identiQN = new QName(ELE_GPM_IDENTIFICATION);
        QName besteQN = new QName(ATTR_GPM_IDEN_BESTE);
        QName samplesQN = new QName(ATTR_GPM_IDEN_SAMPLES);
        String ensg = null;
        String ensp = null;
        String beste = null;
        String samples = null;

        GPMEntryBean gpmEntryBean = null;

        while (xmlEventReader.hasNextEvent()) {
            //eventType = reader.next();
            XMLEvent event = xmlEventReader.nextEvent();
            if (event.isStartElement()) {
                StartElement element = event.asStartElement();

                //protein entry
                if (element.getName().equals(proteinQN)) {
                    //get the version attribute
                    Attribute enspAttr = element.getAttributeByName(enspQN);
                    Attribute ensgAttr = element.getAttributeByName(ensgQN);
                    if (enspAttr != null) {
                        ensp = enspAttr.getValue();
                    }
                    if (ensgAttr != null) {
                        ensg = ensgAttr.getValue();
                    }
                    //create gpn entry bean
                    gpmEntryBean = new GPMEntryBean();
                    //create gpm dbsource
                    DBSourceBean gpmDbSourceBean = new DBSourceBean();
                    gpmDbSourceBean.setDbName(DbAcType.GPM.type());
                    gpmDbSourceBean.setPrimaryEvidences(true);
                    //set the gpm dbsource
                    gpmEntryBean.setPrimaryDbSourceBean(gpmDbSourceBean);

                    //create a gene bean
                    if (StringUtils.isNotBlank(ensg)) {
                        GeneBean geneBean = new GeneBean();
                        geneBean.setEnsgAccession(ensg);
                        gpmEntryBean.setGeneBean(geneBean);
                    }

                    //create an identified accession bean
                    AccessionBean identAccessionBean = parseIdentifiedAccessionBean(ensp);
                    gpmEntryBean.setIdentifiedAccessionBean(identAccessionBean);
                    //create dbsource and accession entry bean
                    List<DbSourceAcEntryBean> dbSourceAcEntryBeanList = parseDBSourceAcEntryBeans(ensp, ensg);
                    gpmEntryBean.setDbSourceAcEntryBeans(dbSourceAcEntryBeanList);

                }

                //protein entry
                if (element.getName().equals(identiQN)) {
                    Attribute besteAttr = element.getAttributeByName(besteQN);
                    Attribute samplesAttr = element.getAttributeByName(samplesQN);
                    if (besteAttr != null) {
                        beste = besteAttr.getValue();
                    }
                    if (samplesAttr != null) {
                        samples = samplesAttr.getValue();
                    }

                    //create pe ms prob evidence based on beste and ensp accesion
                    PEEvidenceBean peMsProbEvidence = createMsProbEvidence(beste, ensp);
                    //parse pe ms samples evidence
                    PEEvidenceBean peMsSamplesEvidence = createMsSamplesEvidence(samples, ensp);

                    if (peMsProbEvidence != null) {
                        gpmEntryBean.setPeMsProbEvidenceBean(peMsProbEvidence);
                    }
                    if (peMsSamplesEvidence != null) {
                        gpmEntryBean.setPeMsSamplesEvidenceBean(peMsSamplesEvidence);
                    }
                }
            }
            //End of element
            if (event.isEndElement()) {
                EndElement endElement = event.asEndElement();
                //hpa entry end
                if (endElement.getName().equals(proteinQN)) {
                    //if gene is not null, the  accession is not null and get some evidences for this gpm entry, then we add it to the list
                    GeneBean geneBean = gpmEntryBean.getGeneBean();
                    AccessionBean identifiedAcBean = gpmEntryBean.getIdentifiedAccessionBean();
                    PEEvidenceBean peMsProbEvidence = gpmEntryBean.getPeMsProbEvidenceBean();
                    PEEvidenceBean peMsSampEvidence = gpmEntryBean.getPeMsProbEvidenceBean();
                    if (geneBean != null && identifiedAcBean != null) {
                        if (peMsProbEvidence != null || peMsSampEvidence != null) {
                            gpmEntryBeans.add(gpmEntryBean);
                        }
                    }
                }
            }
        }
        return gpmEntryBeans;
    } catch (Exception ex) {
        logger.error(ex);
        throw new DMXMLParserException(ex);
    } finally {
        if (xmlEventReader != null) {
            try {
                xmlEventReader.close();
            } catch (Exception e) {
                //ignore whatever caught.
            }
        }
    }

}

From source file:com.adobe.acs.commons.it.build.ScrMetadataIT.java

private Descriptor parseScr(InputStream is, String name, boolean checkNs) throws Exception {
    Descriptor result = new Descriptor();

    XMLEventReader reader = xmlInputFactory.createXMLEventReader(is);
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            StartElement start = event.asStartElement();
            String elementName = start.getName().getLocalPart();
            if (elementName.equals("component")) {
                result.name = start.getAttributeByName(new QName("name")).getValue();
                if (checkNs) {
                    String scrUri = start.getName().getNamespaceURI();
                    if (!ALLOWED_SCR_NS_URIS.contains(scrUri)) {
                        throw new Exception(
                                String.format("Banned Namespace URI %s found for %s", scrUri, name));
                    }/*  www. j  ava 2 s  .  c o m*/
                }
            } else if (elementName.equals("property")) {
                String propName = start.getAttributeByName(new QName("name")).getValue();
                Attribute value = start.getAttributeByName(new QName("value"));
                Attribute typeAttr = start.getAttributeByName(new QName("type"));
                String type = typeAttr == null ? "String" : typeAttr.getValue();
                if (value != null) {
                    result.properties.add(new Property(propName, value.getValue(), type));
                } else {
                    result.properties.add(new Property(propName, cleanText(reader.getElementText()), type));
                }
            }
        }
    }

    return result;
}

From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Extract an attribute value from a <code>StartElement </code> event.
 *
 * @param element        Event object.//from w w  w .ja  va 2s .c  om
 * @param name           Attribute QName
 * @param def            Default value.
 * @param onErrorMessage On error message.
 * @return attribute value
 * @throws XMLStreamException if attribute is missing and there is no default value set.
 */
private String getAttributeValue(StartElement element, QName name, String def, String onErrorMessage)
        throws XMLStreamException {
    Attribute attribute = element.getAttributeByName(name);

    if (attribute == null) {
        if (def == null)
            throw new XMLStreamException(onErrorMessage, element.getLocation());

        return def;
    }

    return attribute.getValue();
}

From source file:com.adobe.acs.commons.it.build.ScrMetadataIT.java

private Descriptor parseMetatype(InputStream is, String name) throws Exception {
    Descriptor result = new Descriptor();

    XMLEventReader reader = xmlInputFactory.createXMLEventReader(is);
    while (reader.hasNext()) {
        XMLEvent event = reader.nextEvent();
        if (event.isStartElement()) {
            StartElement start = event.asStartElement();
            String elementName = start.getName().getLocalPart();
            if (elementName.equals("Designate")) {
                Attribute pidAttribute = start.getAttributeByName(new QName("pid"));
                if (pidAttribute != null) {
                    result.name = pidAttribute.getValue();
                } else {
                    pidAttribute = start.getAttributeByName(new QName("factoryPid"));
                    if (pidAttribute != null) {
                        result.name = pidAttribute.getValue();
                    }//ww  w  .  j a  v  a 2s  .c o m
                    result.factory = true;
                }
            } else if (elementName.equals("AD")) {
                String propName = start.getAttributeByName(new QName("id")).getValue();
                Attribute value = start.getAttributeByName(new QName("default"));
                Attribute typeAttr = start.getAttributeByName(new QName("type"));
                String type = typeAttr == null ? "String" : typeAttr.getValue();
                if (value == null) {
                    result.properties.add(new Property(propName, "", type));
                } else {
                    result.properties.add(new Property(propName, value.getValue(), type));
                }
            }
        }
    }

    if (result.name == null) {
        throw new Exception("Could not identify pid for " + name);
    }
    return result;
}

From source file:com.aionemu.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Extract an attribute value from a/*w w  w .j  a va2s  .  c  om*/
 * <code>StartElement </code> event.
 *
 * @param element        Event object.
 * @param name           Attribute QName
 * @param def            Default value.
 * @param onErrorMessage On error message.
 * @return attribute value
 * @throws XMLStreamException if attribute is missing and there is no
 *                            default value set.
 */
private String getAttributeValue(StartElement element, QName name, String def, String onErrorMessage)
        throws XMLStreamException {
    Attribute attribute = element.getAttributeByName(name);

    if (attribute == null) {
        if (def == null) {
            throw new XMLStreamException(onErrorMessage, element.getLocation());
        }

        return def;
    }

    return attribute.getValue();
}

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

public TestResultContainer readXml() {
    boolean fieldsElement = false;
    try {/* w w w.  j av  a 2  s  . c o m*/
        while (eventReader.hasNext()) {
            XMLEvent event = eventReader.nextEvent();
            if (event instanceof StartElement) {
                StartElement element = (StartElement) event;
                String localName = element.getName().getLocalPart();
                if ("test_fields".equals(localName)) {
                    fieldsElement = true;
                }
                if ("test_field".equals(localName)) {
                    if (!fieldsElement) {
                        Assert.fail(
                                "<test_field> element found, but surrounding element '<test_fields>' is missing in the XML file");
                    }
                    String type = element.getAttributeByName(new QName("type")).getValue();
                    String value = element.getAttributeByName(new QName("value")).getValue();
                    if (type.equals("Framework")) {
                        resultFields.setFramework(value);
                    } else if (type.equals("Testing_Tool_Type")) {
                        resultFields.setTestingTool(value);
                    } else if (type.equals("Test_Level")) {
                        resultFields.setTestLevel(value);
                    }
                }
                if ("test_run".equals(localName)) {
                    String moduleName = element.getAttributeByName(new QName("module")).getValue();
                    String packageName = element.getAttributeByName(new QName("package")).getValue();
                    String className = element.getAttributeByName(new QName("class")).getValue();
                    String testName = element.getAttributeByName(new QName("name")).getValue();
                    testAttributes.add(new TestAttributes(moduleName, packageName, className, testName));
                }
            }
        }
        IOUtils.closeQuietly(input);
        eventReader.close();
    } catch (XMLStreamException e) {
        throw new RuntimeException(e);
    }
    return new TestResultContainer(testAttributes, resultFields);
}