Example usage for org.xml.sax Attributes getLength

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

Introduction

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

Prototype

public abstract int getLength();

Source Link

Document

Return the number of attributes in the list.

Usage

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

private void processScenario(Attributes attrs) throws SAXParseException {
    if (currScenario != null) {
        throw new SAXParseException(StreamsResources.getStringFormatted(StreamsResources.RESOURCE_BUNDLE_NAME,
                "ConfigParserHandler.malformed.configuration", SCENARIO_ELMT), currParseLocation);
    }//from   ww w .j  av  a 2 s  .  c  o  m

    String name = null;
    for (int i = 0; i < attrs.getLength(); i++) {
        String attName = attrs.getQName(i);
        String attValue = attrs.getValue(i);
        if (NAME_ATTR.equals(attName)) {
            name = attValue;
        }
    }

    notEmpty(name, SCENARIO_ELMT, NAME_ATTR);

    currScenario = new WsScenario(name);
}

From source file:com.netspective.commons.xml.template.Template.java

public Map getTemplateParamsValues(NodeIdentifiers nodeIdentifiers, Attributes attributesFromCaller)
        throws SAXException {
    Set requiredParams = new HashSet();
    Map templateParamsValues = new HashMap();

    fillTemplateParamsRequiredAndDefaultValues(requiredParams, templateParamsValues, attributesFromCaller);

    for (int i = 0; i < attributesFromCaller.getLength(); i++) {
        String attrName = attributesFromCaller.getQName(i);
        if (attrName.startsWith(nodeIdentifiers.getTemplateParamAttrPrefix()))
            templateParamsValues.put(attrName.substring(nodeIdentifiers.getTemplateParamAttrPrefix().length()),
                    attributesFromCaller.getValue(i));
    }//from  w w  w. j  a v  a  2s.  c o  m

    // validate that all required parameters are available
    for (Iterator i = requiredParams.iterator(); i.hasNext();) {
        Parameter param = (Parameter) i.next();
        String paramValue = (String) templateParamsValues.get(param.getName());

        if (paramValue == null)
            throw new SAXException(
                    "Required param '" + param.getName() + "' not found. Available: " + templateParamsValues);
    }

    return templateParamsValues;
}

From source file:com.textocat.textokit.commons.io.axml.AXMLContentHandler.java

private void onAnnotationStart(final String aType, Attributes attrs) throws SAXParseException {
    String type = toTypeName(aType);
    Annotation newAnno = new Annotation();
    newAnno.setType(type);/*from   w  ww.  ja v a  2  s . c o  m*/
    newAnno.setBegin(textBuilder.length());
    // handle features
    for (int attrIndex = 0; attrIndex < attrs.getLength(); attrIndex++) {
        final String attrName = attrs.getLocalName(attrIndex);
        if ("id".equals(attrName)) {
            // handle as a special case
            String id = attrs.getValue(attrIndex);
            newAnno.setId(id);
            annoIdIndex.put(id, newAnno);
        } else {
            // handle the attr as feature name or alias
            String featName = attrName;
            if (featNameAliases.containsKey(attrName)) {
                featName = featNameAliases.get(attrName);
            }
            String attrVal = attrs.getValue(attrIndex);
            if (attrVal.startsWith("id:")) {
                String valId = attrVal.substring("id:".length());
                fsFeatureTable.put(newAnno, featName, valId);
            } else if (attrVal.startsWith("ids:")) {
                List<String> valIds = ID_SPLITTER.splitToList(attrVal.substring("ids:".length()));
                fsFeatureTable.put(newAnno, featName, valIds);
            } else {
                newAnno.setFeatureStringValue(featName, attrVal);
            }
        }
    }
    //
    openAnnotations.addFirst(newAnno);
}

From source file:net.sf.ehcache.config.BeanHandler.java

/**
 * Receive notification of the start of an element.
 *//* w  w  w .  j a v  a 2  s.c o  m*/
public final void startElement(final String uri, final String localName, final String qName,
        final Attributes attributes) throws SAXException {
    // Create the child object
    if (element == null) {
        element = new ElementInfo(qName, bean);
    } else {
        final Object child = createChild(element, qName);
        element = new ElementInfo(element, qName, child);
    }

    // Set the attributes
    for (int i = 0; i < attributes.getLength(); i++) {
        final String attrName = attributes.getQName(i);
        final String attrValue = attributes.getValue(i);
        setAttribute(element, attrName, attrValue);
    }
}

From source file:com.zyz.mobile.book.UserBookData.java

@SuppressWarnings("UnusedAssignment")
@Override//from  ww  w  .  j a v  a 2  s. co m
public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
        throws SAXException {
    if (localName.equals(Element.BOOK)) {
        mStatus.in_book = true;
        try {
            if (atts.getLength() >= 1) {
                setOffset(Integer.parseInt(atts.getValue(0)));
            }
            if (atts.getLength() >= 2) {
                mVersion = Integer.parseInt(atts.getValue(1));
            }
        } catch (NumberFormatException e) {

        }
    } else if (localName.equals(Element.SPANS)) {
        mStatus.in_spans = true;
    } else if (localName.equals(Element.SPAN)) {
        mStatus.in_span = true;

        try {
            int i = 0;
            if (atts.getLength() >= 4) {
                int type = Integer.parseInt(atts.getValue(i++));
                int color = Integer.parseInt(atts.getValue(i++));
                int start = Integer.parseInt(atts.getValue(i++));
                int end = Integer.parseInt(atts.getValue(i++));

                mCurrentSpanObj = new UserSpan(UserSpanType.toEnum(type), color, start, end);
                insertSpan(mCurrentSpanObj);
            }
            if (atts.getLength() >= 5) {
                mCurrentSpanObj.setDescription(StringEscapeUtils.unescapeXml(atts.getValue(i)));
            }
        } catch (NumberFormatException e) {
            // should not happen unless the file is corrupted or modified incorrectly
        }
    } else if (localName.equals(Element.NOTE)) {
        mStatus.in_note = true;
    } else if (localName.equals(Element.BOOKMARKS)) {
        mStatus.in_bookmarks = true;
    } else if (localName.equals(Element.BOOKMARK)) {
        mStatus.in_bookmark = true;
        int i = 0;

        try {
            if (mStatus.in_bookmarks) {
                if (atts.getLength() >= 1) {
                    int start = Integer.parseInt(atts.getValue(i++));
                    mCurrentSpanObj = (new UserSpan.Builder()).setType(UserSpanType.BOOKMARK).setStart(start)
                            .create();
                    insertSpan(mCurrentSpanObj);
                }
                if (atts.getLength() >= 2) {
                    mCurrentSpanObj.setDescription(StringEscapeUtils.unescapeXml(atts.getValue(i)));
                }
            } else if (mStatus.in_history) {
                if (atts.getLength() >= 1) {
                    int offset = Integer.parseInt(atts.getValue(i++));
                    mLocationHistory.add(offset);
                }
            }
        } catch (NumberFormatException e) {

        }

    } else if (localName.equals(Element.HISTORY)) {
        mStatus.in_history = true;
    }
}

From source file:org.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;//ww  w.  j ava 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:com.frameworkset.orm.engine.transform.XmlToData.java

/**
 * Handles opening elements of the xml file.
 *///w w  w  . j a v  a  2 s .c o  m
public void startElement(String uri, String localName, String rawName, Attributes attributes)
        throws SAXException {
    try {
        if (rawName.equals("dataset")) {
            //ignore <dataset> for now.
        }

        else {
            Table table = database.getTableByJavaName(rawName);

            if (table == null) {
                throw new SAXException("Table '" + rawName + "' unknown");
            }
            List columnValues = new ArrayList();
            for (int i = 0; i < attributes.getLength(); i++) {
                Column col = table.getColumnByJavaName(attributes.getQName(i));

                if (col == null) {
                    throw new SAXException(
                            "Column " + attributes.getQName(i) + " in table " + rawName + " unknown.");
                }

                String value = attributes.getValue(i);
                columnValues.add(new ColumnValue(col, value));
            }
            data.add(new DataRow(table, columnValues));
        }
    } catch (Exception e) {
        throw new SAXException(e);
    }
}

From source file:de.mpg.mpdl.inge.citationmanager.utils.XsltHelper.java

/**
 * Gets every element and set it to currentElement.
 *///from   w  ww.j  a  va 2  s.  co  m
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {

    if ("".equals(uri)) {
        currentElement = name;
    } else {
        currentElement = localName;
    }
    // gets the attribute with the URL of the item and cuts the coneValue
    if (currentElement.equals("Description") && attributes.getLength() != 0) {
        coneValue = attributes.getValue("rdf:about");
        coneValue = coneValue.substring(coneValue.lastIndexOf("/") + 1);
    }
}

From source file:de.mpg.escidoc.services.citationmanager.utils.XsltHelper.java

/**
 * Gets every element and set it to currentElement.
 *///from  ww w .  j a v a 2  s .  co m
@Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {

    if ("".equals(uri)) {
        currentElement = name;
    } else {
        currentElement = localName;
    }
    //gets the attribute with the URL of the item and cuts the coneValue
    if (currentElement.equals("Description") && attributes.getLength() != 0) {
        coneValue = attributes.getValue("rdf:about");
        coneValue = coneValue.substring(coneValue.lastIndexOf("/") + 1);
    }
}

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

public void parse(int mode, String url, final Database db) {
    Element entry;//from w  w  w .  j  ava 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));
    }
}