Example usage for org.xml.sax Attributes getQName

List of usage examples for org.xml.sax Attributes getQName

Introduction

In this page you can find the example usage for org.xml.sax Attributes getQName.

Prototype

public abstract String getQName(int index);

Source Link

Document

Look up an attribute's XML qualified (prefixed) name by index.

Usage

From source file:com.esri.geoevent.solutions.adapter.cot.MessageParser.java

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    try {//from   ww  w.  j  a v  a2  s. c o m
        if (qName == null)
            return;

        if (messageLevel == MessageLevel.root
                && (qName.equalsIgnoreCase(MESSAGES) || qName.equalsIgnoreCase("geomessages"))) {
            messageLevel = MessageLevel.inMessages;
        } else if (messageLevel == MessageLevel.inMessages
                && (qName.equalsIgnoreCase(MESSAGE) || qName.equalsIgnoreCase("geomessage"))) {
            messageLevel = MessageLevel.inMessage;
        } else if (messageLevel == MessageLevel.inMessage) {
            messageLevel = MessageLevel.inAttribute;
            attribute = "";
            attributeName = qName;
        } else if (messageLevel == MessageLevel.inAttribute) {
            throw new SAXException("Problem parsing message, cannot handle nested attributes. (" + qName
                    + " inside " + attributeName + ")");
        } else if (qName.equalsIgnoreCase("event")) {
            // Event element was found. Store all available CoT attributes.
            for (int i = 0; attributes.getLength() > i; i++) {
                String l = attributes.getLocalName(i);
                String q = attributes.getQName(i);
                String name = null;

                if (l.isEmpty()) {
                    name = q;
                } else {
                    name = l;
                }

                if (name.equalsIgnoreCase("how")) {
                    this.how = attributes.getValue(i);
                } else if (name.equalsIgnoreCase("opex")) {
                    this.opex = attributes.getValue(i);
                } else if (name.equalsIgnoreCase("qos")) {
                    this.qos = attributes.getValue(i);
                } else if (name.equalsIgnoreCase("type")) {
                    this.type = attributes.getValue(i);
                } else if (name.equalsIgnoreCase("uid")) {
                    this.uid = attributes.getValue(i);
                } else if (name.equalsIgnoreCase("stale")) {
                    this.stale = attributes.getValue(i);
                } else if (name.equalsIgnoreCase("start")) {
                    this.start = attributes.getValue(i);
                } else if (name.equalsIgnoreCase("time")) {
                    this.time = attributes.getValue(i);
                } else if (name.equalsIgnoreCase("version")) {
                    this.version = attributes.getValue(i);
                } else if (name.equalsIgnoreCase("access")) {
                    this.access = attributes.getValue(i);
                }
            }
        } else if (!inDetails && qName.equalsIgnoreCase("detail")) {
            // <detail> element started
            tabLevel++;
            inDetails = true;
            detail.append("\n" + makeTabs(tabLevel) + "<eventWrapper><detail");
            // (NOTE: detail should NOT have any attributes but search just
            // in case)
            for (int i = 0; attributes.getLength() > i; i++) {

                detail.append("\n" + makeTabs(tabLevel + 1) + attributes.getLocalName(i) + "=" + "\""
                        + attributes.getValue(i) + "\"");
            }
            // close the tag
            detail.append(">");
        } else if (inDetails && !qName.equalsIgnoreCase("detail")) {
            // some new child element inside the Detail section
            tabLevel++;
            detail.append("\n" + makeTabs(tabLevel) + "<" + qName);
            // search for any attributes
            for (int i = 0; attributes.getLength() > i; i++) {
                String l = attributes.getLocalName(i);
                String q = attributes.getQName(i);
                String name = null;

                if (l.isEmpty()) {
                    name = q;
                } else {
                    name = l;
                }
                detail.append(
                        "\n" + makeTabs(tabLevel + 1) + name + "=" + "\"" + attributes.getValue(i) + "\"");
            }
            // close the tag
            detail.append(">");
        } else if (!inDetails && qName.equalsIgnoreCase("point")) {
            // <point> element started
            tabLevel++;
            point.append("\n" + makeTabs(tabLevel) + "<point");
            // search for any attributes
            for (int i = 0; attributes.getLength() > i; i++) {
                String l = attributes.getLocalName(i);
                String q = attributes.getQName(i);
                String name = null;

                if (l.isEmpty()) {
                    name = q;
                } else {
                    name = l;
                }
                point.append("\n" + makeTabs(tabLevel + 1) + name + "=" + "\"" + attributes.getValue(i) + "\"");
            }
            // close the tag
            point.append(" />");
            tabLevel--;
        }
    } catch (Exception e) {
        LOG.error(e);
        LOG.error(e.getStackTrace());
    }

}

From source file:org.syncope.core.util.ImportExport.java

private void setParameters(final String tableName, final Attributes atts, final Query query) {

    Map<String, Integer> colTypes = new HashMap<String, Integer>();

    Connection conn = DataSourceUtils.getConnection(dataSource);
    ResultSet rs = null;/*ww w .j  a v a  2 s .co  m*/
    Statement stmt = null;
    try {
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT * FROM " + tableName);
        for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
            colTypes.put(rs.getMetaData().getColumnName(i + 1).toUpperCase(),
                    rs.getMetaData().getColumnType(i + 1));
        }
    } catch (SQLException e) {
        LOG.error("While", e);
    } finally {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing statement", e);
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        DataSourceUtils.releaseConnection(conn, dataSource);
    }

    for (int i = 0; i < atts.getLength(); i++) {
        Integer colType = colTypes.get(atts.getQName(i).toUpperCase());
        if (colType == null) {
            LOG.warn("No column type found for {}", atts.getQName(i).toUpperCase());
            colType = Types.VARCHAR;
        }

        switch (colType) {
        case Types.NUMERIC:
        case Types.REAL:
        case Types.INTEGER:
        case Types.TINYINT:
            try {
                query.setParameter(i + 1, Integer.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Integer '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DECIMAL:
        case Types.BIGINT:
            try {
                query.setParameter(i + 1, Long.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Long '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DOUBLE:
            try {
                query.setParameter(i + 1, Double.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Double '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.FLOAT:
            try {
                query.setParameter(i + 1, Float.valueOf(atts.getValue(i)));
            } catch (NumberFormatException e) {
                LOG.error("Unparsable Float '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            try {
                query.setParameter(i + 1, DateUtils.parseDate(atts.getValue(i), SyncopeConstants.DATE_PATTERNS),
                        TemporalType.TIMESTAMP);
            } catch (ParseException e) {
                LOG.error("Unparsable Date '{}'", atts.getValue(i));
                query.setParameter(i + 1, atts.getValue(i));
            }
            break;

        case Types.BIT:
        case Types.BOOLEAN:
            query.setParameter(i + 1, "1".equals(atts.getValue(i)) ? Boolean.TRUE : Boolean.FALSE);
            break;

        default:
            query.setParameter(i + 1, atts.getValue(i));
        }
    }
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

private void recordProperty(Attributes attributes) throws SAXException {
    if (curElement == null) {
        throw new SAXParseException("<" + SIM_XML_PROP + ">: Must have <" + SIM_XML_ACTIVITY + ">, <"
                + SIM_XML_EVENT + ">, or <" + SIM_XML_SNAPSHOT + "> as parent element", saxLocator);
    }/*from  w  w w.j  a  v  a2  s  .  com*/

    String name = null;
    String type = null;
    String value = null;
    String valType = null;

    try {
        for (int i = 0; i < attributes.getLength(); i++) {
            String attName = attributes.getQName(i);
            String attValue = expandEnvVars(attributes.getValue(i));

            if (attName.equals(SIM_XML_ATTR_NAME))
                name = attValue;
            else if (attName.equals(SIM_XML_ATTR_TYPE))
                type = attValue;
            else if (attName.equals(SIM_XML_ATTR_VALUE))
                value = attValue;
            else if (attName.equals(SIM_XML_ATTR_VALTYPE))
                valType = attValue;
            else
                throw new SAXParseException("Unknown <" + SIM_XML_PROP + "> attribute '" + attName + "'",
                        saxLocator);
        }

        if (StringUtils.isEmpty(name))
            throw new SAXParseException("<" + SIM_XML_PROP + ">: must specify '" + SIM_XML_ATTR_NAME + "'",
                    saxLocator);

        TNT4JSimulator.trace(simCurrTime, "Recording " + curElement + " property: " + name + " ...");

        Property prop = processPropertyValue(name, type, value, valType);

        if (SIM_XML_SNAPSHOT.equals(curElement))
            curSnapshot.add(prop);
        else if (SIM_XML_EVENT.equals(curElement))
            curEvent.getOperation().addProperty(prop);
        else if (SIM_XML_ACTIVITY.equals(curElement))
            curActivity.addProperty(prop);
    } catch (Exception e) {
        if (e instanceof SAXException)
            throw (SAXException) e;
        throw new SAXException("Failed processing definition for property '" + name + "': " + e, e);
    }
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

private void recordSource(Attributes attributes) throws SAXException {
    if (TNT4JSimulator.getIteration() > 1L)
        return;/*ww  w .j av a 2s. c o m*/

    if (!SIM_XML_ROOT.equals(curElement))
        throw new SAXParseException(
                "<" + SIM_XML_SOURCE + ">: must have <" + SIM_XML_ROOT + "> as parent element", saxLocator);

    int id = 0;
    String fqn = null;
    String url = null;
    String user = null;

    try {
        for (int i = 0; i < attributes.getLength(); i++) {
            String attName = attributes.getQName(i);
            String attValue = expandEnvVars(attributes.getValue(i));

            if (attName.equals(SIM_XML_ATTR_ID))
                id = Integer.parseInt(attValue);
            else if (attName.equals(SIM_XML_ATTR_FQN))
                fqn = attValue;
            else if (attName.equals(SIM_XML_ATTR_USER))
                user = attValue;
            else if (attName.equals(SIM_XML_ATTR_URL))
                url = attValue;
            else
                throw new SAXParseException("Unknown <" + SIM_XML_SOURCE + "> attribute " + attName,
                        saxLocator);
        }

        if (id <= 0)
            throw new SAXParseException("<" + SIM_XML_SOURCE + "> element has missing or invalid "
                    + SIM_XML_ATTR_ID + " attribute ", saxLocator);

        if (sourceIds.containsKey(id))
            throw new SAXParseException(
                    "<" + SIM_XML_SOURCE + "> duplicate " + SIM_XML_ATTR_ID + " attribute: " + id, saxLocator);

        if (StringUtils.isEmpty(fqn))
            throw new SAXParseException(
                    "<" + SIM_XML_SOURCE + "> element is missing " + SIM_XML_ATTR_FQN + " attribute ",
                    saxLocator);

        if (sourceNames.containsKey(fqn))
            throw new SAXParseException(
                    "<" + SIM_XML_SOURCE + "> duplicate " + SIM_XML_ATTR_FQN + " attribute: " + fqn,
                    saxLocator);

        Source src = DefaultSourceFactory.getInstance().newFromFQN(fqn);
        if (!StringUtils.isEmpty(user))
            src.setUser(user);
        if (!StringUtils.isEmpty(url))
            src.setUrl(url);

        sourceNames.put(fqn, src);
        sourceIds.put(id, src);

        TrackerConfig srcCfg = DefaultConfigFactory.getInstance().getConfig(fqn);
        srcCfg.setSource(src);

        srcCfg.setProperty("Url", TNT4JSimulator.getConnectUrl());

        String token = TNT4JSimulator.getAccessToken();
        if (!StringUtils.isEmpty(token))
            srcCfg.setProperty("Token", token);

        Tracker tracker = trackerFactory.getInstance(srcCfg.build());
        trackers.put(fqn, tracker);
    } catch (Exception e) {
        if (e instanceof SAXException)
            throw (SAXException) e;
        throw new SAXParseException("Failed processing definition for source: ", saxLocator, e);
    }

    TNT4JSimulator.trace(simCurrTime, "Recording Server: " + fqn + " ...");
}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

private void recordSnapshot(Attributes attributes) throws SAXException {
    if ((curActivity == null || !SIM_XML_ACTIVITY.equals(curElement))
            && (curEvent == null || !SIM_XML_EVENT.equals(curElement))) {
        throw new SAXParseException("<" + SIM_XML_SNAPSHOT + ">: must have <" + SIM_XML_ACTIVITY + "> or <"
                + SIM_XML_EVENT + "> as parent element", saxLocator);
    }//w w  w .j a v a 2s  .  co m

    String name = null;
    String category = null;
    OpLevel severity = OpLevel.INFO;

    try {
        for (int i = 0; i < attributes.getLength(); i++) {
            String attName = attributes.getQName(i);
            String attValue = expandEnvVars(attributes.getValue(i));

            if (attName.equals(SIM_XML_ATTR_NAME)) {
                name = attValue;
                TNT4JSimulator.trace(simCurrTime, "Recording Snapshot: " + attValue + " ...");
            } else if (attName.equals(SIM_XML_ATTR_CAT)) {
                category = attValue;
            } else if (attName.equals(SIM_XML_ATTR_SEVERITY)) {
                severity = getLevel(attValue);
            } else {
                throw new SAXParseException("Unknown <" + SIM_XML_SNAPSHOT + "> attribute '" + attName + "'",
                        saxLocator);
            }
        }

        if (StringUtils.isEmpty(name))
            throw new SAXParseException("<" + SIM_XML_SNAPSHOT + ">: missing '" + SIM_XML_ATTR_NAME + "'",
                    saxLocator);

        if (StringUtils.isEmpty(category))
            category = null;

        curSnapshot = new PropertySnapshot(category, name, severity, simCurrTime);
        curSnapshot.setTTL(TNT4JSimulator.getTTL());
    } catch (Exception e) {
        if (e instanceof SAXException)
            throw (SAXException) e;
        throw new SAXException("Failed processing definition for snapshot '" + name + "': " + e, e);
    }
}

From source file:cn.ctyun.amazonaws.services.s3.model.transform.XmlResponsesSaxParser.java

private static String findAttributeValue(String qnameToFind, Attributes attrs) {
    for (int i = 0; i < attrs.getLength(); i++) {
        String qname = attrs.getQName(i);
        if (qname.trim().equalsIgnoreCase(qnameToFind.trim())) {
            return attrs.getValue(i);
        }//from   w w w  .j a v  a2  s. c o m
    }

    return null;
}

From source file:DocumentTracer.java

/** Start element. */
public void startElement(String uri, String localName, String qname, Attributes attributes)
        throws SAXException {

    printIndent();//from   w  w w .j  a  v  a 2 s  .c o m
    fOut.print("startElement(");
    fOut.print("uri=");
    printQuotedString(uri);
    fOut.print(',');
    fOut.print("localName=");
    printQuotedString(localName);
    fOut.print(',');
    fOut.print("qname=");
    printQuotedString(qname);
    fOut.print(',');
    fOut.print("attributes=");
    if (attributes == null) {
        fOut.println("null");
    } else {
        fOut.print('{');
        int length = attributes.getLength();
        for (int i = 0; i < length; i++) {
            if (i > 0) {
                fOut.print(',');
            }
            String attrLocalName = attributes.getLocalName(i);
            String attrQName = attributes.getQName(i);
            String attrURI = attributes.getURI(i);
            String attrType = attributes.getType(i);
            String attrValue = attributes.getValue(i);
            fOut.print('{');
            fOut.print("uri=");
            printQuotedString(attrURI);
            fOut.print(',');
            fOut.print("localName=");
            printQuotedString(attrLocalName);
            fOut.print(',');
            fOut.print("qname=");
            printQuotedString(attrQName);
            fOut.print(',');
            fOut.print("type=");
            printQuotedString(attrType);
            fOut.print(',');
            fOut.print("value=");
            printQuotedString(attrValue);
            fOut.print('}');
        }
        fOut.print('}');
    }
    fOut.println(')');
    fOut.flush();
    fIndent++;

}

From source file:com.jkoolcloud.jesl.simulator.TNT4JSimulatorParserHandler.java

private void recordMessage(Attributes attributes) throws SAXException {
    if (TNT4JSimulator.getIteration() > 1L)
        return;/*from  ww  w.j a  v  a  2 s.  c  om*/

    if (!SIM_XML_ROOT.equals(curElement))
        throw new SAXParseException("<" + SIM_XML_MSG + ">: must have <" + SIM_XML_ROOT + "> as parent element",
                saxLocator);

    int id = 0;
    String mimeType = null;
    String encoding = null;
    String charset = null;
    String fileName = null;
    boolean isBinary = false;

    try {
        for (int i = 0; i < attributes.getLength(); i++) {
            String attName = attributes.getQName(i);
            String attValue = expandEnvVars(attributes.getValue(i));

            if (attName.equals(SIM_XML_ATTR_ID)) {
                id = Integer.parseInt(attValue);
                TNT4JSimulator.trace(simCurrTime, "Recording Message: " + attValue + " ...");
            } else if (attName.equals(SIM_XML_ATTR_MIME)) {
                mimeType = attValue;
            } else if (attName.equals(SIM_XML_ATTR_ENC)) {
                encoding = attValue;
            } else if (attName.equals(SIM_XML_ATTR_CHARSET)) {
                charset = attValue;
            } else if (attName.equals(SIM_XML_ATTR_FILE)) {
                fileName = attValue;
            } else if (attName.equals(SIM_XML_ATTR_BINFILE)) {
                isBinary = Boolean.parseBoolean(attValue);
            } else {
                throw new SAXParseException("Unknown <" + SIM_XML_MSG + "> attribute '" + attName + "'",
                        saxLocator);
            }
        }

        if (id == 0)
            throw new SAXParseException("<" + SIM_XML_MSG + ">: missing or invalid '" + SIM_XML_ATTR_ID + "'",
                    saxLocator);

        curMsg = messageIds.get(id);
        if (curMsg == null) {
            curMsg = new Message(TNT4JSimulator.newUUID());
            messageIds.put(id, curMsg);
        }

        if (fileName != null) {
            if (isBinary) {
                BufferedInputStream fileReader = null;
                try {
                    File f = new File(fileName);
                    fileReader = new BufferedInputStream(new FileInputStream(f));
                    byte[] binData = new byte[(int) f.length()];
                    int totalBytesRead = 0;
                    while (totalBytesRead < binData.length) {
                        int bytesRemaining = binData.length - totalBytesRead;
                        int bytesRead = fileReader.read(binData, totalBytesRead, bytesRemaining);
                        if (bytesRead > 0)
                            totalBytesRead += bytesRead;
                        curMsg.setMessage(binData);
                    }
                } catch (Exception e) {
                    throw new SAXParseException("Failed loading message data from " + fileName, saxLocator, e);
                } finally {
                    if (fileReader != null)
                        try {
                            fileReader.close();
                        } catch (Exception e1) {
                        }
                }
            } else {
                FileReader fileReader = null;
                try {
                    fileReader = new FileReader(fileName);
                    StringBuffer msgData = new StringBuffer();
                    char[] text = new char[2048];
                    int numRead = 0;
                    while ((numRead = fileReader.read(text, 0, text.length)) > 0)
                        msgData.append(text, 0, numRead);
                    curMsg.setMessage(msgData.toString());
                } catch (Exception e) {
                    throw new SAXParseException("Failed loading message data from " + fileName, saxLocator, e);
                } finally {
                    if (fileReader != null)
                        try {
                            fileReader.close();
                        } catch (Exception e1) {
                        }
                }
            }

            curMsg = null; // to ignore msg element value
        }

        if (!StringUtils.isEmpty(mimeType))
            curMsg.setMimeType(mimeType);
        if (!StringUtils.isEmpty(encoding))
            curMsg.setEncoding(encoding);
        if (!StringUtils.isEmpty(charset))
            curMsg.setCharset(charset);
    } catch (Exception e) {
        if (e instanceof SAXException)
            throw (SAXException) e;
        throw new SAXException("Failed processing definition for message '" + id + "': " + e, e);
    }
}

From source file:net.sf.joost.stx.Processor.java

/**
 * Simulate events for each of the attributes of the current element.
 * This method will be called due to an <code>stx:process-attributes</code>
 * instruction./*from  w ww .  ja va2  s.co m*/
 * @param attrs the attributes to be processed
 */
private void processAttributes(Attributes attrs) throws SAXException {
    // actually only the target group need to be put on this stack ..
    // (for findMatchingTemplate)
    dataStack.push(new Data(PR_ATTRIBUTES, null, null, null, context));
    for (int i = 0; i < attrs.getLength(); i++) {
        if (DEBUG)
            if (log.isDebugEnabled())
                log.debug(attrs.getQName(i));
        SAXEvent ev = SAXEvent.newAttribute(attrs, i);
        eventStack.push(ev);
        processEvent();
        eventStack.pop();
        if (DEBUG)
            if (log.isDebugEnabled())
                log.debug("done " + attrs.getQName(i));
    }
    Data d = dataStack.pop();
    // restore position, current group and variables
    context.position = d.contextPosition;
    context.currentGroup = d.currentGroup;
    context.localVars = d.localVars;
}

From source file:Writer.java

/** Start element. */
public void startElement(String uri, String local, String raw, Attributes attrs) throws SAXException {

    // Root Element
    if (fElementDepth == 0) {
        if (fLocator != null) {
            fXML11 = "1.1".equals(getVersion());
            fLocator = null;// w  w w  . j  a  v  a  2 s .  c  o m
        }

        // The XML declaration cannot be printed in startDocument because
        // the version reported by the Locator cannot be relied on until after
        // the XML declaration in the instance document has been read.
        if (!fCanonical) {
            if (fXML11) {
                fOut.println("<?xml version=\"1.1\" encoding=\"UTF-8\"?>");
            } else {
                fOut.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
            }
            fOut.flush();
        }
    }

    fElementDepth++;
    fOut.print('<');
    fOut.print(raw);
    if (attrs != null) {
        attrs = sortAttributes(attrs);
        int len = attrs.getLength();
        for (int i = 0; i < len; i++) {
            fOut.print(' ');
            fOut.print(attrs.getQName(i));
            fOut.print("=\"");
            normalizeAndPrint(attrs.getValue(i), true);
            fOut.print('"');
        }
    }
    fOut.print('>');
    fOut.flush();

}