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:edu.uci.ics.jung.io.GraphMLReader.java

protected Map<String, String> getAttributeMap(Attributes atts) {
    Map<String, String> att_map = new HashMap<String, String>();
    for (int i = 0; i < atts.getLength(); i++)
        att_map.put(atts.getQName(i), atts.getValue(i));

    return att_map;
}

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

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

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

    final Table table = getTable(tableName);

    for (int i = 0; i < attrs.getLength(); i++) {
        Integer colType = table.getColumn(QualifiedDBIdentifier.newColumn(attrs.getQName(i))).getType();
        if (colType == null) {
            LOG.warn("No column type found for {}", attrs.getQName(i).toUpperCase());
            colType = Types.VARCHAR;
        }/*w  ww . j  av  a2 s .  co  m*/

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

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

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

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

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

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

        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
            try {
                query.setParameter(i + 1, Hex.decode(attrs.getValue(i)));
            } catch (IllegalArgumentException e) {
                query.setParameter(i + 1, attrs.getValue(i));
            }
            break;

        case Types.BLOB:
            try {
                query.setParameter(i + 1, Hex.decode(attrs.getValue(i)));
            } catch (IllegalArgumentException e) {
                LOG.warn("Error decoding hex string to specify a blob parameter", e);
                query.setParameter(i + 1, attrs.getValue(i));
            } catch (Exception e) {
                LOG.warn("Error creating a new blob parameter", e);
            }
            break;

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

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

@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes atts)
        throws SAXException {

    // skip root element
    if (ROOT_ELEMENT.equals(qName)) {
        return;/*w w  w  .ja va  2s . c  o m*/
    }

    StringBuilder queryString = new StringBuilder("INSERT INTO ").append(qName).append('(');

    StringBuilder values = new StringBuilder();

    for (int i = 0; i < atts.getLength(); i++) {
        queryString.append(atts.getQName(i));
        values.append('?');
        if (i < atts.getLength() - 1) {
            queryString.append(',');
            values.append(',');
        }
    }
    queryString.append(") VALUES (").append(values).append(')');

    Query query = entityManager.createNativeQuery(queryString.toString());
    setParameters(qName, atts, query);

    query.executeUpdate();
}

From source file:it.wami.map.mongodeploy.OsmSaxHandler.java

/**
 * //w w w  .j av a 2 s  . com
 * @param atts
 */
private void appendMetadata(Attributes atts) {
    for (int i = 0; i < atts.getLength(); i++) {
        //System.out.println("qName: "+atts.getQName(i)+" value: "+atts.getValue(i));
        String attribute = atts.getQName(i);
        if (attribute == "id" || attribute == "lat" || attribute == "lon") {
            continue;
        }
        /*if(attribute.contains("www")){
           System.exit(0);
        }*/
        attribute = StringUtils.replace(attribute, ".", "[dot]");
        //attribute.replace(".", "[dot]");
        //System.out.println(attribute);
        entry.append(attribute, atts.getValue(i));
    }
}

From source file:com.kdmanalytics.toif.assimilator.XMLNode.java

/**
 * Parse the node information. Note that the "Attributes" here are XML Attributes, not KDM
 * attributes.//  www  .  j a v  a  2s. com
 * 
 * @param ns
 * @param sName
 * @param qName
 * @param attrs
 */
public XMLNode(String ns, String sName, String qName, Attributes attrs) {

    children = new ArrayList<XMLNode>();
    this.sName = sName;
    if ("".equals(sName))
        this.sName = qName; // Not namespace aware

    int size = attrs.getLength();
    for (int i = 0; i < size; i++) {
        String key = attrs.getLocalName(i); // Attr name
        if ("".equals(key))
            key = attrs.getQName(i);

        // Special cases
        // Stereotype/tag "type" is an attribute, not a reference
        if ("stereotype".equals(this.sName) && "type".equals(key))
            addAttribute(key, attrs.getValue(key));
        else if ("tag".equals(this.sName) && "type".equals(key))
            addAttribute(key, attrs.getValue(key));

        // Some attributes are really references
        else if (AttributeUtilities.isReference(key))
            addReference(key, attrs.getValue(key));

        // Unescape the fields which likely contain escaped HTML
        else if (stringFields.contains(key)) {
            String value = attrs.getValue(key);
            try {
                // value = StringEscapeUtils.unescapeHtml4(value);
                // value = StringEscapeUtils.unescapeXml(value);
                value = StringEscapeUtils.unescapeHtml3(value);
            } catch (StringIndexOutOfBoundsException e) {
                // String was most likely '&' which causes commons.lang3 to
                // throw... ignore it
                if (!value.contains("&")) {
                    throw e;
                }
            }
            addAttribute(key, value);
        }
        // Normal attribute
        else {
            addAttribute(key, attrs.getValue(key));
        }
    }

    // Use the xmiLid if it exists
    id = getAttribute("xmi:id");
    if (id == null)
        id = "" + UniqueID.get();
}

From source file:com.gimranov.zandy.app.XMLResponseParser.java

public void parse(int mode, String url, final Database db) {
    Element entry;/* w  ww.  j  a v  a  2s. co m*/
    RootElement root;
    // we have a different root for indiv. items
    if (mode == MODE_FEED) {
        root = new RootElement(ATOM_NAMESPACE, "feed");
        entry = root.getChild(ATOM_NAMESPACE, "entry");
    } else {
        // MODE_ITEM, MODE_COLLECTION
        Log.d(TAG, "Parsing in entry mode");
        root = new RootElement(ATOM_NAMESPACE, "entry");
        entry = (Element) root;
    }

    if (mode == MODE_FEED) {
        root.getChild(ATOM_NAMESPACE, "link").setStartElementListener(new StartElementListener() {
            public void start(Attributes attributes) {
                String rel = "";
                String href = "";
                int length = attributes.getLength();
                // I shouldn't have to walk through, but the namespacing isn't working here
                for (int i = 0; i < length; i++) {
                    if ("rel".equals(attributes.getQName(i)))
                        rel = attributes.getValue(i);
                    if ("href".equals(attributes.getQName(i)))
                        href = attributes.getValue(i);
                }
                // We try to get a parent collection if necessary / possible
                if (rel.contains("self")) {
                    // Try to get a parent collection
                    int colloc = href.indexOf("/collections/");
                    int itemloc = href.indexOf("/items");
                    // Our URL looks like this:
                    //       https://api.zotero.org/users/5770/collections/2AJUSIU9/items?content=json
                    if (colloc != -1 && itemloc != -1) {
                        // The string "/collections/" is thirteen characters long
                        String id = href.substring(colloc + 13, itemloc);
                        Log.d(TAG, "Collection key: " + id);
                        parent = ItemCollection.load(id, db);
                        if (parent != null)
                            parent.loadChildren(db);
                    } else {
                        Log.d(TAG, "Key extraction failed from root; maybe this isn't a collection listing?");
                    }
                }
                // If there are more items, queue them up to be handled too
                if (rel.contains("next")) {
                    Log.d(TAG, "Found continuation: " + href);
                    APIRequest req = new APIRequest(href, "get", null);
                    req.query = href;
                    req.disposition = "xml";
                    queue.add(req);
                }
            }
        });
    }

    entry.setElementListener(new ElementListener() {
        public void start(Attributes attributes) {
            item = new Item();
            collection = new ItemCollection();
            attachment = new Attachment();
            Log.d(TAG, "New entry");
        }

        public void end() {
            if (items == true) {
                if (updateKey != null && updateType != null && updateType.equals("item")) {
                    // We have an incoming new version of an item
                    Item existing = Item.load(updateKey, db);
                    if (existing != null) {
                        Log.d(TAG, "Updating newly created item to replace temporary key: " + updateKey + " => "
                                + item.getKey() + "");
                        item.getKey();
                        existing.dirty = APIRequest.API_CLEAN;
                        // We need to update the parent key in attachments as well,
                        // so they aren't orphaned after we update the item key here
                        ArrayList<Attachment> atts = Attachment.forItem(existing, db);
                        for (Attachment a : atts) {
                            Log.d(TAG, "Propagating item key replacement to attachment with key: " + a.key);
                            a.parentKey = item.getKey();
                            a.save(db);
                        }
                        // We can't set the new key until after updating child attachments
                        existing.setKey(item.getKey());
                        if (!existing.getType().equals("attachment"))
                            existing.save(db);
                    }
                } else if (updateKey != null && updateType != null && updateType.equals("attachment")) {
                    // We have an incoming new version of an item
                    Attachment existing = Attachment.load(updateKey, db);
                    if (existing != null) {
                        Log.d(TAG, "Updating newly created attachment to replace temporary key: " + updateKey
                                + " => " + attachment.key + "");
                        existing.dirty = APIRequest.API_CLEAN;
                        // we don't change the ZFS status...
                        existing.key = attachment.key;
                        existing.save(db);
                    }
                } else {
                    item.dirty = APIRequest.API_CLEAN;
                    attachment.dirty = APIRequest.API_CLEAN;
                    if ((attachment.url != null && !"".equals(attachment.url))
                            || attachment.content.optInt("linkMode") == Attachment.MODE_IMPORTED_FILE
                            || attachment.content.optInt("linkMode") == Attachment.MODE_IMPORTED_URL)
                        attachment.status = Attachment.AVAILABLE;

                    if (!item.getType().equals("attachment") && !item.getType().equals("note")) {
                        Item oldItem = Item.load(item.getKey(), db);
                        // Check timestamps to see if it's different; if not, we should
                        // stop following the Atom continuation links
                        if (oldItem != null && oldItem.getTimestamp().equals(item.getTimestamp())) {
                            followNext = false;
                        }
                        item.save(db);
                    } else {
                        // Don't touch ZFS status here
                        Attachment existing = Attachment.load(attachment.key, db);
                        if (existing != null) {
                            attachment.status = existing.status;
                        }
                        attachment.save(db);
                    }
                }

                if (!item.getType().equals("attachment") && !item.getType().equals("note")
                        && item.getChildren() != null && !item.getChildren().equals("0")) {
                    queue.add(APIRequest.children(item));
                    Log.d(TAG, "Queued children request for item: " + item.getTitle() + " " + item.getKey());
                    Log.d(TAG, "Item has children: " + item.getChildren());
                }

                // Add to containing collection
                if (!item.getType().equals("attachment") && parent != null)
                    parent.add(item, true, db);

                request.getHandler().onUpdate(request);

                Log.d(TAG, "Done parsing item entry.");
                return;
            }

            if (!items) {
                if (updateKey != null && updateType != null && updateType.equals("collection")) {
                    // We have an incoming new version of a collection
                    ItemCollection existing = ItemCollection.load(updateKey, db);
                    if (existing != null) {
                        Log.d(TAG, "Updating newly created collection to replace temporary key: " + updateKey
                                + " => " + collection.getKey() + "");
                        existing.setKey(collection.getKey());
                        existing.dirty = APIRequest.API_CLEAN;
                        existing.save(db);
                    }
                    Log.d(TAG, "Done parsing new collection entry.");
                    // We don't need to load again, since a new collection can't be stale
                    return;
                }

                ItemCollection ic = ItemCollection.load(collection.getKey(), db);
                if (ic != null) {
                    if (!ic.getTimestamp().equals(collection.getTimestamp())) {
                        // In this case, we have data, but we should refresh it
                        collection.dirty = APIRequest.API_STALE;
                    } else {
                        // Collection hasn't changed!
                        collection = ic;
                        // We also don't need the next page, if we already saw this one
                        followNext = false;
                    }
                } else {
                    // This means that we haven't seen the collection before, so it must be
                    // a new one, and we don't have contents for it.
                    collection.dirty = APIRequest.API_MISSING;
                }
                Log.d(TAG, "Status: " + collection.dirty + " for " + collection.getTitle());
                collection.save(db);
                Log.d(TAG, "Done parsing a collection entry.");
                return;
            }
        }
    });
    entry.getChild(ATOM_NAMESPACE, "title").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setTitle(body);
            collection.setTitle(body);
            attachment.title = body;
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "key").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setKey(body);
            collection.setKey(body);
            attachment.key = body;
            Log.d(TAG, body);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "updated").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setTimestamp(body);
            collection.setTimestamp(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "itemType").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setType(body);
            items = true;
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "numChildren").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setChildren(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "year").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setYear(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(Z_NAMESPACE, "creatorSummary").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setCreatorSummary(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "id").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            item.setId(body);
            collection.setId(body);
            Log.d(TAG, body);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "link").setStartElementListener(new StartElementListener() {
        public void start(Attributes attributes) {
            String rel = "";
            String href = "";
            int length = attributes.getLength();
            // I shouldn't have to walk through, but the namespacing isn't working here
            for (int i = 0; i < length; i++) {
                if ("rel".equals(attributes.getQName(i)))
                    rel = attributes.getValue(i);
                if ("href".equals(attributes.getQName(i)))
                    href = attributes.getValue(i);
            }
            if (rel != null && rel.equals("up")) {
                int start = href.indexOf("/items/");
                // Trying to pull out the key of attachment parent
                attachment.parentKey = href.substring(start + 7, start + 7 + 8);
                Log.d(TAG, "Setting parentKey to: " + attachment.parentKey);
            } else if (rel != null && rel.equals("enclosure")) {
                attachment.url = href;
                attachment.status = Attachment.AVAILABLE;
                Log.d(TAG, "url= " + attachment.url);
            } else if (rel != null)
                Log.d(TAG, "rel=" + rel + " href=" + href);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "content").setStartElementListener(new StartElementListener() {
        public void start(Attributes attributes) {
            String etag = attributes.getValue(Z_NAMESPACE, "etag");
            item.setEtag(etag);
            collection.setEtag(etag);
            attachment.etag = etag;
            Log.d(TAG, "etag: " + etag);
        }
    });
    entry.getChild(ATOM_NAMESPACE, "content").setEndTextElementListener(new EndTextElementListener() {
        public void end(String body) {
            try {
                JSONObject obj = new JSONObject(body);
                try {
                    collection.setParent(obj.getString("parent"));
                } catch (JSONException e) {
                    Log.d(TAG, "No parent found in JSON content; not a subcollection or not a collection");
                }
                item.setContent(obj);
                attachment.content = obj;
            } catch (JSONException e) {
                Log.e(TAG, "JSON parse exception loading content", e);
            }
            Log.d(TAG, body);
        }
    });
    try {
        Xml.parse(this.input, Xml.Encoding.UTF_8, root.getContentHandler());
        if (parent != null) {
            parent.saveChildren(db);
            parent.markClean();
            parent.save(db);
        }
        db.close();
    } catch (Exception e) {
        Log.e(TAG, "exception loading content", e);
        Crashlytics.logException(new Exception("Exception parsing data", e));
    }
}

From source file:Counter.java

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

    fElements++;/*  www  .ja va  2  s  . co  m*/
    fTagCharacters++; // open angle bracket
    fTagCharacters += raw.length();
    if (attrs != null) {
        int attrCount = attrs.getLength();
        fAttributes += attrCount;
        for (int i = 0; i < attrCount; i++) {
            fTagCharacters++; // space
            fTagCharacters += attrs.getQName(i).length();
            fTagCharacters++; // '='
            fTagCharacters++; // open quote
            fOtherCharacters += attrs.getValue(i).length();
            fTagCharacters++; // close quote
        }
    }
    fTagCharacters++; // close angle bracket

}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.WsConfigParserHandler.java

private void processCronScheduler(Attributes attrs) throws SAXException {
    if (currStep == null) {
        throw new SAXParseException(
                StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "ConfigParserHandler.malformed.configuration2", SCHED_CRON_ELMT, STEP_ELMT),
                currParseLocation);//  w w  w.j av a2s .  c om
    }

    if (currStep.getSchedulerData() != null) {
        throw new SAXException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                "WsConfigParserHandler.element.has.multiple", STEP_ELMT, SCHED_CRON_ELMT, SCHED_SIMPLE_ELMT,
                getLocationInfo()));
    }

    String expression = null;
    for (int i = 0; i < attrs.getLength(); i++) {
        String attName = attrs.getQName(i);
        String attValue = attrs.getValue(i);
        if (EXPRESSION_ATTR.equals(attName)) {
            expression = attValue;
        }
    }
    notEmpty(expression, SCHED_CRON_ELMT, EXPRESSION_ATTR);

    CronSchedulerData schedData = new CronSchedulerData(expression);

    currStep.setSchedulerData(schedData);
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.WsConfigParserHandler.java

private void processSimpleScheduler(Attributes attrs) throws SAXException {
    if (currStep == null) {
        throw new SAXParseException(
                StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                        "ConfigParserHandler.malformed.configuration2", SCHED_SIMPLE_ELMT, STEP_ELMT),
                currParseLocation);//from  w ww  . j a  v  a2s  .co  m
    }

    if (currStep.getSchedulerData() != null) {
        throw new SAXException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                "WsConfigParserHandler.element.has.multiple", STEP_ELMT, SCHED_CRON_ELMT, SCHED_SIMPLE_ELMT,
                getLocationInfo()));
    }

    Integer interval = null;
    String timeUnits = null;
    Integer repeatCount = null;
    for (int i = 0; i < attrs.getLength(); i++) {
        String attName = attrs.getQName(i);
        String attValue = attrs.getValue(i);
        if (INTERVAL_ATTR.equals(attName)) {
            interval = Integer.parseInt(attValue);
        } else if (UNITS_ATTR.equals(attName)) {
            timeUnits = attValue;
        } else if (REPEATS_ATTR.equals(attName)) {
            repeatCount = Integer.parseInt(attValue);
        }
    }
    if (interval == null || interval < 0) {
        throw new SAXException(StreamsResources.getStringFormatted(WsStreamConstants.RESOURCE_BUNDLE_NAME,
                "WsConfigParserHandler.attr.missing.or.illegal", SCHED_SIMPLE_ELMT, INTERVAL_ATTR, interval,
                getLocationInfo()));
    }

    SimpleSchedulerData schedData = new SimpleSchedulerData(interval);
    schedData.setUnits(
            StringUtils.isEmpty(timeUnits) ? TimeUnit.MILLISECONDS : TimeUnit.valueOf(timeUnits.toUpperCase()));
    schedData.setRepeatCount(repeatCount);

    currStep.setSchedulerData(schedData);
}

From source file:Sax2Dom.java

public void startElement(String namespace, String localName, String qName, Attributes attrs) {
    final Element tmp = (Element) _document.createElementNS(namespace, qName);

    // Add namespace declarations first
    if (_namespaceDecls != null) {
        final int nDecls = _namespaceDecls.size();
        for (int i = 0; i < nDecls; i++) {
            final String prefix = (String) _namespaceDecls.elementAt(i++);

            if (prefix == null || prefix.equals(EMPTYSTRING)) {
                tmp.setAttributeNS(XMLNS_URI, XMLNS_PREFIX, (String) _namespaceDecls.elementAt(i));
            } else {
                tmp.setAttributeNS(XMLNS_URI, XMLNS_STRING + prefix, (String) _namespaceDecls.elementAt(i));
            }//from w  w  w .  j  av  a  2  s. co m
        }
        _namespaceDecls.clear();
    }

    // Add attributes to element
    final int nattrs = attrs.getLength();
    for (int i = 0; i < nattrs; i++) {
        if (attrs.getLocalName(i) == null) {
            tmp.setAttribute(attrs.getQName(i), attrs.getValue(i));
        } else {
            tmp.setAttributeNS(attrs.getURI(i), attrs.getQName(i), attrs.getValue(i));
        }
    }

    // Append this new node onto current stack node
    Node last = (Node) _nodeStk.peek();
    last.appendChild(tmp);

    // Push this node onto stack
    _nodeStk.push(tmp);
}