Example usage for javax.xml.stream XMLStreamReader getAttributeLocalName

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

Introduction

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

Prototype

public String getAttributeLocalName(int index);

Source Link

Document

Returns the localName of the attribute at the provided index

Usage

From source file:org.apache.solr.handler.XMLLoader.java

/**
 * Given the input stream, read a document
 *
 * @since solr 1.3//  w  w w  . j  a v a  2s  . c  o  m
 */
SolrInputDocument readDoc(XMLStreamReader parser) throws XMLStreamException {
    SolrInputDocument doc = new SolrInputDocument();

    String attrName = "";
    for (int i = 0; i < parser.getAttributeCount(); i++) {
        attrName = parser.getAttributeLocalName(i);
        if ("boost".equals(attrName)) {
            doc.setDocumentBoost(Float.parseFloat(parser.getAttributeValue(i)));
        } else {
            XmlUpdateRequestHandler.log.warn("Unknown attribute doc/@" + attrName);
        }
    }

    StringBuilder text = new StringBuilder();
    String name = null;
    float boost = 1.0f;
    boolean isNull = false;
    while (true) {
        int event = parser.next();
        switch (event) {
        // Add everything to the text
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            text.append(parser.getText());
            break;

        case XMLStreamConstants.END_ELEMENT:
            if ("doc".equals(parser.getLocalName())) {
                return doc;
            } else if ("field".equals(parser.getLocalName())) {
                if (!isNull) {
                    doc.addField(name, text.toString(), boost);
                    boost = 1.0f;
                }
            }
            break;

        case XMLStreamConstants.START_ELEMENT:
            text.setLength(0);
            String localName = parser.getLocalName();
            if (!"field".equals(localName)) {
                XmlUpdateRequestHandler.log.warn("unexpected XML tag doc/" + localName);
                throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                        "unexpected XML tag doc/" + localName);
            }
            boost = 1.0f;
            String attrVal = "";
            for (int i = 0; i < parser.getAttributeCount(); i++) {
                attrName = parser.getAttributeLocalName(i);
                attrVal = parser.getAttributeValue(i);
                if ("name".equals(attrName)) {
                    name = attrVal;
                } else if ("boost".equals(attrName)) {
                    boost = Float.parseFloat(attrVal);
                } else if ("null".equals(attrName)) {
                    isNull = StrUtils.parseBoolean(attrVal);
                } else {
                    XmlUpdateRequestHandler.log.warn("Unknown attribute doc/field/@" + attrName);
                }
            }
            break;
        }
    }
}

From source file:org.apache.synapse.commons.json.JsonDataSource.java

public void serialize(XMLStreamWriter xmlWriter) throws XMLStreamException {
    XMLStreamReader reader = getReader();
    xmlWriter.writeStartDocument();/*  ww  w .  j  ava 2s  .c om*/
    while (reader.hasNext()) {
        int x = reader.next();
        switch (x) {
        case XMLStreamConstants.START_ELEMENT:
            xmlWriter.writeStartElement(reader.getPrefix(), reader.getLocalName(), reader.getNamespaceURI());
            int namespaceCount = reader.getNamespaceCount();
            for (int i = namespaceCount - 1; i >= 0; i--) {
                xmlWriter.writeNamespace(reader.getNamespacePrefix(i), reader.getNamespaceURI(i));
            }
            int attributeCount = reader.getAttributeCount();
            for (int i = 0; i < attributeCount; i++) {
                xmlWriter.writeAttribute(reader.getAttributePrefix(i), reader.getAttributeNamespace(i),
                        reader.getAttributeLocalName(i), reader.getAttributeValue(i));
            }
            break;
        case XMLStreamConstants.START_DOCUMENT:
            break;
        case XMLStreamConstants.CHARACTERS:
            xmlWriter.writeCharacters(reader.getText());
            break;
        case XMLStreamConstants.CDATA:
            xmlWriter.writeCData(reader.getText());
            break;
        case XMLStreamConstants.END_ELEMENT:
            xmlWriter.writeEndElement();
            break;
        case XMLStreamConstants.END_DOCUMENT:
            xmlWriter.writeEndDocument();
            break;
        case XMLStreamConstants.SPACE:
            break;
        case XMLStreamConstants.COMMENT:
            xmlWriter.writeComment(reader.getText());
            break;
        case XMLStreamConstants.DTD:
            xmlWriter.writeDTD(reader.getText());
            break;
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            xmlWriter.writeProcessingInstruction(reader.getPITarget(), reader.getPIData());
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            xmlWriter.writeEntityRef(reader.getLocalName());
            break;
        default:
            throw new OMException();
        }
    }
    xmlWriter.writeEndDocument();
    xmlWriter.flush();
    xmlWriter.close();
}

From source file:org.apache.syncope.client.cli.commands.migrate.MigrateConf.java

private static void copyAttrs(final XMLStreamReader streamReader, final XMLStreamWriter streamWriter,
        final String... but) throws XMLStreamException {

    Set<String> exceptions = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
    exceptions.addAll(Arrays.asList(but));
    exceptions.add("id");
    exceptions.add("name");

    for (int i = 0; i < streamReader.getAttributeCount(); i++) {
        String name = streamReader.getAttributeLocalName(i);
        if (!exceptions.contains(name)) {
            streamWriter.writeAttribute(name, streamReader.getAttributeValue(i));
        }// w  w  w  .ja  v  a2 s .c  o  m
    }
}

From source file:org.apache.syncope.client.cli.commands.migrate.MigrateConf.java

private static String getAttributeValue(final XMLStreamReader streamReader, final String key) {
    String value = null;//from  www.  j  av  a 2s  . c  o m

    for (int i = 0; i < streamReader.getAttributeCount(); i++) {
        String attrName = streamReader.getAttributeLocalName(i);
        if (attrName.equalsIgnoreCase(key)) {
            value = streamReader.getAttributeValue(i);
        }
    }

    return value;
}

From source file:org.deegree.client.core.renderer.OutputXMLRenderer.java

private void encodeXML(ResponseWriter writer, String value) throws IOException {
    int depth = 0;
    try {/*from ww  w. j  av  a2  s .  c o m*/
        XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(value));
        boolean lastWasEndElement = false;
        boolean lastWasComment = false;
        while (reader.hasNext()) {
            switch (reader.getEventType()) {
            case XMLStreamConstants.START_ELEMENT:
                if (!lastWasComment) {
                    writer.startElement("br", null);
                    writer.endElement("br");
                }
                writer.write(getSpaces(depth));
                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&lt;");
                writer.endElement("span");

                writer.startElement("span", null);
                writer.writeAttribute("class", "tag", null);
                String prefix = reader.getPrefix();
                writer.write(
                        (prefix != null && prefix.length() > 0 ? prefix + ":" : "") + reader.getLocalName());
                writer.endElement("span");

                for (int i = 0; i < reader.getAttributeCount(); i++) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", "attributeName", null);
                    writer.write("&#160;");
                    String attributePrefix = reader.getAttributePrefix(i);
                    writer.write(
                            (attributePrefix != null && attributePrefix.length() > 0 ? attributePrefix + ":"
                                    : "") + reader.getAttributeLocalName(i));
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("=\"");
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "text", null);
                    writer.write(encodeString(reader.getAttributeValue(i)));
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("\"");
                    writer.endElement("span");
                }

                for (int i = 0; i < reader.getNamespaceCount(); i++) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", "attributeName", null);
                    writer.write("&#160;");
                    String nsPrefix = reader.getNamespacePrefix(i);
                    writer.write("xmlns");
                    if (nsPrefix != null && !nsPrefix.isEmpty()) {
                        writer.write(":" + nsPrefix);
                    }
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("=\"");
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "text", null);
                    writer.write(reader.getNamespaceURI(i));
                    writer.endElement("span");

                    writer.startElement("span", null);
                    writer.writeAttribute("class", "sign", null);
                    writer.write("\"");
                    writer.endElement("span");
                }

                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&gt;");
                writer.endElement("span");
                depth++;
                lastWasEndElement = false;
                lastWasComment = false;
                break;
            case XMLStreamConstants.CHARACTERS:
                String text = reader.getText();
                if (text.trim().length() > 0) {
                    writer.startElement("span", null);
                    writer.writeAttribute("class", "text", null);
                    writer.write(encodeString(text));
                    writer.endElement("span");
                    lastWasEndElement = false;
                    lastWasComment = false;
                }
                break;
            case XMLStreamConstants.END_ELEMENT:
                depth--;
                if (lastWasEndElement) {
                    writer.startElement("br", null);
                    writer.endElement("br");
                    writer.write(getSpaces(depth));
                }
                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&lt;/");
                writer.endElement("span");

                writer.startElement("span", null);
                writer.writeAttribute("class", "tag", null);
                prefix = reader.getPrefix();
                writer.write(
                        (prefix != null && prefix.length() > 0 ? prefix + ":" : "") + reader.getLocalName());
                writer.endElement("span");

                writer.startElement("span", null);
                writer.writeAttribute("class", "sign", null);
                writer.write("&gt;");
                writer.endElement("span");
                lastWasEndElement = true;
                lastWasComment = false;
                break;
            case XMLStreamConstants.COMMENT:
                writer.startElement("div", null);
                writer.writeAttribute("class", "comment", null);
                writer.write("&lt;/!--" + reader.getText() + "--&gt;");
                writer.endElement("div");
                lastWasEndElement = false;
                lastWasComment = true;
                break;
            default:
                break;
            }
            reader.next();

        }
        reader.close();
    } catch (Throwable e) {
        if (depth == 0) {
            writer.writeText("Response could not parsed as XML.", null);
        } else {
            writer.writeText("... (if you want the complete document, please click the download button)", null);
        }
    }
}

From source file:org.deegree.services.csw.exporthandling.GetCapabilitiesHelper.java

private void writeTemplateElement(XMLStreamWriter writer, XMLStreamReader inStream,
        Map<String, String> varToValue) throws XMLStreamException {

    if (inStream.getEventType() != XMLStreamConstants.START_ELEMENT) {
        throw new XMLStreamException("Input stream does not point to a START_ELEMENT event.");
    }/*w  w  w  .j av a  2s. c  o m*/
    int openElements = 0;
    boolean firstRun = true;
    while (firstRun || openElements > 0) {
        firstRun = false;
        int eventType = inStream.getEventType();

        switch (eventType) {
        case CDATA: {
            writer.writeCData(inStream.getText());
            break;
        }
        case CHARACTERS: {
            String s = new String(inStream.getTextCharacters(), inStream.getTextStart(),
                    inStream.getTextLength());
            // TODO optimize
            for (String param : varToValue.keySet()) {
                String value = varToValue.get(param);
                s = s.replace(param, value);
            }
            writer.writeCharacters(s);

            break;
        }
        case END_ELEMENT: {
            writer.writeEndElement();
            openElements--;
            break;
        }
        case START_ELEMENT: {
            if (inStream.getNamespaceURI() == "" || inStream.getPrefix() == DEFAULT_NS_PREFIX
                    || inStream.getPrefix() == null) {
                writer.writeStartElement(inStream.getLocalName());
            } else {
                if (writer.getNamespaceContext().getPrefix(inStream.getPrefix()) == "") {
                    // TODO handle special cases for prefix binding, see
                    // http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/javax/xml/namespace/NamespaceContext.html#getNamespaceURI(java.lang.String)
                    writer.setPrefix(inStream.getPrefix(), inStream.getNamespaceURI());
                }
                writer.writeStartElement(inStream.getPrefix(), inStream.getLocalName(),
                        inStream.getNamespaceURI());
            }
            // copy all namespace bindings
            for (int i = 0; i < inStream.getNamespaceCount(); i++) {
                String nsPrefix = inStream.getNamespacePrefix(i);
                String nsURI = inStream.getNamespaceURI(i);
                writer.writeNamespace(nsPrefix, nsURI);
            }

            // copy all attributes
            for (int i = 0; i < inStream.getAttributeCount(); i++) {
                String localName = inStream.getAttributeLocalName(i);
                String nsPrefix = inStream.getAttributePrefix(i);
                String value = inStream.getAttributeValue(i);
                String nsURI = inStream.getAttributeNamespace(i);
                if (nsURI == null) {
                    writer.writeAttribute(localName, value);
                } else {
                    writer.writeAttribute(nsPrefix, nsURI, localName, value);
                }
            }

            openElements++;
            break;
        }
        default: {
            break;
        }
        }
        if (openElements > 0) {
            inStream.next();
        }
    }
}

From source file:org.elissa.web.server.TransformerServlet.java

private void revisitSequenceFlows(Definitions def, String orig) {
    try {//from   w  ww .j  a va  2  s  .  com
        Map<String, Map<String, String>> sequenceFlowMapping = new HashMap<String, Map<String, String>>();
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(orig));
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("sequenceFlow".equals(reader.getLocalName())) {
                    String id = "";
                    String source = "";
                    String target = "";
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("id".equals(reader.getAttributeLocalName(i))) {
                            id = reader.getAttributeValue(i);
                        }
                        if ("sourceRef".equals(reader.getAttributeLocalName(i))) {
                            source = reader.getAttributeValue(i);
                        }
                        if ("targetRef".equals(reader.getAttributeLocalName(i))) {
                            target = reader.getAttributeValue(i);
                        }
                    }
                    Map<String, String> valueMap = new HashMap<String, String>();
                    valueMap.put("sourceRef", source);
                    valueMap.put("targetRef", target);
                    sequenceFlowMapping.put(id, valueMap);
                }
            }
        }
        List<RootElement> rootElements = def.getRootElements();
        for (RootElement root : rootElements) {
            if (root instanceof Process) {
                Process process = (Process) root;
                List<FlowElement> flowElements = process.getFlowElements();
                for (FlowElement fe : flowElements) {
                    if (fe instanceof SequenceFlow) {
                        SequenceFlow sf = (SequenceFlow) fe;
                        if (sequenceFlowMapping.containsKey(sf.getId())) {
                            sf.setSourceRef(
                                    getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("sourceRef")));
                            sf.setTargetRef(
                                    getFlowNode(def, sequenceFlowMapping.get(sf.getId()).get("targetRef")));
                        } else {
                            _logger.error("Could not find mapping for sequenceFlow: " + sf.getId());
                        }
                    }
                }
            }
        }
    } catch (FactoryConfigurationError e) {
        _logger.error(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        _logger.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.elissa.web.server.TransformerServlet.java

private void addBpmnDiInfo(Definitions def, String gpd) {
    try {//from w w w  . j a  va  2  s.  c  o  m
        Map<String, Bounds> _bounds = new HashMap<String, Bounds>();
        XMLInputFactory factory = XMLInputFactory.newInstance();
        XMLStreamReader reader = factory.createXMLStreamReader(new StringReader(gpd));
        while (reader.hasNext()) {
            if (reader.next() == XMLStreamReader.START_ELEMENT) {
                if ("node".equals(reader.getLocalName())) {
                    Bounds b = DcFactory.eINSTANCE.createBounds();
                    String nodeName = null;
                    String nodeX = null;
                    String nodeY = null;
                    String nodeWidth = null;
                    String nodeHeight = null;
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        if ("name".equals(reader.getAttributeLocalName(i))) {
                            nodeName = reader.getAttributeValue(i);
                        } else if ("x".equals(reader.getAttributeLocalName(i))) {
                            nodeX = reader.getAttributeValue(i);
                        } else if ("y".equals(reader.getAttributeLocalName(i))) {
                            nodeY = reader.getAttributeValue(i);
                        } else if ("width".equals(reader.getAttributeLocalName(i))) {
                            nodeWidth = reader.getAttributeValue(i);
                        } else if ("height".equals(reader.getAttributeLocalName(i))) {
                            nodeHeight = reader.getAttributeValue(i);
                        }
                    }
                    b.setX(new Float(nodeX).floatValue());
                    b.setY(new Float(nodeY).floatValue());
                    b.setWidth(new Float(nodeWidth).floatValue());
                    b.setHeight(new Float(nodeHeight).floatValue());
                    _bounds.put(nodeName, b);
                }
            }
        }

        for (RootElement rootElement : def.getRootElements()) {
            if (rootElement instanceof Process) {
                Process process = (Process) rootElement;
                BpmnDiFactory diFactory = BpmnDiFactory.eINSTANCE;
                BPMNDiagram diagram = diFactory.createBPMNDiagram();
                BPMNPlane plane = diFactory.createBPMNPlane();
                plane.setBpmnElement(process);
                diagram.setPlane(plane);
                for (FlowElement flowElement : process.getFlowElements()) {
                    if (flowElement instanceof FlowNode) {
                        Bounds b = _bounds.get(flowElement.getId());
                        if (b != null) {
                            BPMNShape shape = diFactory.createBPMNShape();
                            shape.setBpmnElement(flowElement);
                            shape.setBounds(b);
                            plane.getPlaneElement().add(shape);
                        }
                    } else if (flowElement instanceof SequenceFlow) {
                        SequenceFlow sequenceFlow = (SequenceFlow) flowElement;
                        BPMNEdge edge = diFactory.createBPMNEdge();
                        edge.setBpmnElement(flowElement);
                        DcFactory dcFactory = DcFactory.eINSTANCE;
                        Point point = dcFactory.createPoint();
                        if (sequenceFlow.getSourceRef() != null) {
                            Bounds sourceBounds = _bounds.get(sequenceFlow.getSourceRef().getId());
                            point.setX(sourceBounds.getX() + (sourceBounds.getWidth() / 2));
                            point.setY(sourceBounds.getY() + (sourceBounds.getHeight() / 2));
                        }
                        edge.getWaypoint().add(point);
                        //                      List<Point> dockers = _dockers.get(sequenceFlow.getId());
                        //                      for (int i = 1; i < dockers.size() - 1; i++) {
                        //                         edge.getWaypoint().add(dockers.get(i));
                        //                      }
                        point = dcFactory.createPoint();
                        if (sequenceFlow.getTargetRef() != null) {
                            Bounds targetBounds = _bounds.get(sequenceFlow.getTargetRef().getId());
                            point.setX(targetBounds.getX() + (targetBounds.getWidth() / 2));
                            point.setY(targetBounds.getY() + (targetBounds.getHeight() / 2));
                        }
                        edge.getWaypoint().add(point);
                        plane.getPlaneElement().add(edge);
                    }
                }

                def.getDiagrams().add(diagram);
            }
        }
    } catch (FactoryConfigurationError e) {
        _logger.error("Exception adding bpmndi info: " + e.getMessage());
    } catch (Exception e) {
        _logger.error("Exception adding bpmndi info: " + e.getMessage());
    }
}

From source file:org.erdc.cobie.shared.COBieUtility.java

static public Map<String, String> elementMapFromXMLObject(XmlObject xml) {
    Map<String, String> elementMap = new HashMap<String, String>();
    XMLStreamReader rdr = xml.newXMLStreamReader();
    String keyName = "";
    String keyVal = "";
    boolean lastWasStartElement = false;
    int attCount = 0;
    try {//from ww w . j a  v a 2s  . c o  m

        while (rdr.hasNext()) {
            try {
                attCount = rdr.getAttributeCount();
            } catch (Exception ex) {
                attCount = 0;
            }
            if (attCount > 0) {
                for (int i = 0; i < attCount; i++) {
                    keyName = rdr.getAttributeLocalName(i);
                    keyVal = rdr.getAttributeValue(i);
                    if (!elementMap.containsKey(keyName)) {
                        elementMap.put(keyName, escape(keyVal));
                    }
                    lastWasStartElement = false;
                }
            }
            if (rdr.isStartElement()) {
                keyName = rdr.getLocalName();
                lastWasStartElement = true;

            } else if (rdr.isCharacters() && lastWasStartElement) {
                if (isElementADateTime(xml, keyName)) {
                    keyVal = COBieUtility.stringFromXmlDateTime(xml, keyName);

                } else {
                    keyVal = rdr.getText();
                }
                if (!elementMap.containsKey(keyName)) {
                    elementMap.put(keyName, escape(keyVal));
                }
                lastWasStartElement = false;
            } else {
                lastWasStartElement = false;
            }

            rdr.next();
        }
    } catch (XMLStreamException e) {
        LOGGER.error("", e);
    }
    return elementMap;
}

From source file:org.fcrepo.migration.foxml.FoxmlInputStreamFedoraObjectProcessor.java

private static Map<String, String> getAttributes(final XMLStreamReader r, final String... allowedNames) {
    final HashMap<String, String> result = new HashMap<String, String>();
    final Set<String> allowed = new HashSet<String>(Arrays.asList(allowedNames));
    for (int i = 0; i < r.getAttributeCount(); i++) {
        final String localName = r.getAttributeLocalName(i);
        final String value = r.getAttributeValue(i);
        if (allowed.contains(localName)) {
            result.put(localName, value);
        } else {/*  w  w w .  j a va2 s  .  c om*/
            System.err.println("Unexpected attribute: " + localName + " = \"" + value + "\"");
        }
    }
    return result;

}