Example usage for org.w3c.dom NamedNodeMap item

List of usage examples for org.w3c.dom NamedNodeMap item

Introduction

In this page you can find the example usage for org.w3c.dom NamedNodeMap item.

Prototype

public Node item(int index);

Source Link

Document

Returns the indexth item in the map.

Usage

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to bind Annotation element//w  ww  . ja  v  a2 s.  c  o m
 * 
 * @param element the Annotation element
 * @return Annotation data object
 * @throws InkMLException
 */
protected Annotation getAnnotation(final Element element) throws InkMLException {
    final Annotation annotation = new Annotation();

    final NamedNodeMap attributesMap = element.getAttributes();
    final int length = attributesMap.getLength();
    for (int index = 0; index < length; index++) {
        final Attr attribute = (Attr) attributesMap.item(index);
        final String attributeName = attribute.getName();
        if ("type".equals(attributeName)) {
            annotation.setType(attribute.getValue());
        } else if ("encoding".equals(attributeName)) {
            annotation.setEncoding(attribute.getValue());
        } else {
            annotation.addToOtherAttributesMap(attributeName, attribute.getValue());
        }
    }
    final Node valueNode = element.getFirstChild();
    if (null != valueNode) {
        annotation.setAnnotationTextValue(valueNode.getNodeValue());
    }
    return annotation;
}

From source file:com.hp.hpl.inkml.InkMLDOMParser.java

/**
 * Method to bind AnnotationXML element//from  w  w w . j a  v  a2s  . c o  m
 * 
 * @param element the AnnotationXML element
 * @return AnnotationXML data object
 * @throws InkMLException
 */
protected AnnotationXML getAnnotationXML(final Element element) throws InkMLException {
    final AnnotationXML aXml = new AnnotationXML();
    final NamedNodeMap attributesMap = element.getAttributes();
    final int length = attributesMap.getLength();
    for (int index = 0; index < length; index++) {
        final Attr attribute = (Attr) attributesMap.item(index);
        final String attributeName = attribute.getName();
        if ("type".equals(attributeName)) {
            aXml.setType(attribute.getValue());
        } else if ("encoding".equals(attributeName)) {
            aXml.setEncoding(attribute.getValue());
        } else {
            aXml.addToOtherAttributesMap(attributeName, attribute.getValue());
        }
    }
    InkMLDOMParser.LOG.finest("annotationXML received: " + element.toString());
    final NodeList list = element.getChildNodes();
    final int nChildren = list.getLength();
    if (nChildren > 0) {
        for (int i = 0; i < nChildren; i++) {
            final Node node = list.item(i);
            if (!(node instanceof Element)) {
                continue;
            }
            final Element childElement = (Element) node;
            // get the tagName to use as Key in the valueMap
            final String tagName = childElement.getLocalName();
            // String key = this.parentXPath+"/"+tagName;
            final String value = childElement.getFirstChild().getNodeValue();
            // propertyElementsMap.put(key, childElement);
            // propertyElementsMap.put(key, value);
            aXml.addToPropertyElementsMap(tagName, value);
            InkMLDOMParser.LOG
                    .finer("The property with name = " + tagName + " is added to the propertyElementsMap.");
        }
    }
    return aXml;
}

From source file:com.netspective.sparx.util.xml.XmlSource.java

/**
 * Given an element, apply templates to the node. If there is an attribute called "template" then inherit that
 * template first. Then, search through all of the nodes in the element and try to find all <include-template id="x">
 * elements to copy the template elements at those locations. Also, go through each child to see if a tag name
 * exists that matches a template name -- if it does, then "inherit" that template to replace the element at that
 * location.//ww  w  .jav  a  2 s.c o  m
 */
public void processTemplates(Element elem) {
    inheritNodes(elem, templates, "template", defaultExcludeElementsFromInherit);

    NodeList includes = elem.getElementsByTagName("include-template");
    if (includes != null && includes.getLength() > 0) {
        for (int n = 0; n < includes.getLength(); n++) {
            Element include = (Element) includes.item(n);
            String templateName = include.getAttribute("id");
            Element template = (Element) templates.get(templateName);

            if (template != null) {
                NodeList incChildren = template.getChildNodes();
                for (int c = 0; c < incChildren.getLength(); c++) {
                    Node incCopy = xmlDoc.importNode(incChildren.item(c), true);
                    if (incCopy.getNodeType() == Node.ELEMENT_NODE)
                        ((Element) incCopy).setAttribute("_included-from-template", templateName);
                    elem.insertBefore(incCopy, include);
                }
            }
        }
    }

    NodeList children = elem.getChildNodes();
    for (int c = 0; c < children.getLength(); c++) {
        Node childNode = children.item(c);
        if (childNode.getNodeType() != Node.ELEMENT_NODE)
            continue;

        String nodeName = childNode.getNodeName();
        if (templates.containsKey(nodeName)) {
            Element template = (Element) templates.get(nodeName);
            Node incCopy = xmlDoc.importNode(template, true);
            if (incCopy.getNodeType() == Node.ELEMENT_NODE)
                ((Element) incCopy).setAttribute("_included-from-template", nodeName);

            // make sure that the child's attributes overwrite the attributes in the templates with the same name
            NamedNodeMap attrsInChild = childNode.getAttributes();
            for (int a = 0; a < attrsInChild.getLength(); a++) {
                Node childAttr = attrsInChild.item(a);
                ((Element) incCopy).setAttribute(childAttr.getNodeName(), childAttr.getNodeValue());
            }

            // now do the actual replacement
            inheritNodes((Element) incCopy, templates, "template", defaultExcludeElementsFromInherit);
            elem.replaceChild(incCopy, childNode);
        } else
            inheritNodes((Element) childNode, templates, "template", defaultExcludeElementsFromInherit);
    }
}

From source file:com.netspective.sparx.util.xml.XmlSource.java

public void replaceNodeMacros(Node inNode, Set nodeNames, Map variables) {
    if (!variables.containsKey("this"))
        variables.put("this", inNode);

    NamedNodeMap attrs = inNode.getAttributes();
    if (attrs != null && attrs.getLength() > 0) {
        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            if (nodeNames.contains(attr.getNodeName())) {
                String nodeValue = attr.getNodeValue();
                String replaced = replaceExpressions(nodeValue, variables);
                if (nodeValue != replaced)
                    attr.setNodeValue(replaced);
            }//from ww w.j  a  v  a  2s . c  om
        }
    }

    NodeList children = inNode.getChildNodes();
    for (int c = 0; c < children.getLength(); c++) {
        Node node = children.item(c);
        if (node.getNodeType() == Node.ELEMENT_NODE && nodeNames.contains(node.getNodeName())) {
            Text textNode = (Text) node.getFirstChild();
            String nodeValue = textNode.getNodeValue();
            String replaced = replaceExpressions(nodeValue, variables);
            if (nodeValue != replaced)
                textNode.setNodeValue(replaced);
        }
    }
}

From source file:com.draagon.meta.loader.xml.XMLFileMetaDataLoader.java

/**
 * Parses actual element attributes and adds them as StringAttributes
 *//*from  ww  w .  ja va 2  s. co  m*/
protected void parseAttributes(MetaData md, Element el) {

    NamedNodeMap attrs = el.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {

        Node n = attrs.item(i);
        String attrName = n.getNodeName();
        if (!reservedAttributes.contains(attrName)) {

            String value = n.getNodeValue();
            md.addAttribute(new StringAttribute(attrName, value));
        }
    }
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private void addAttributes(SOAPMessage responseMessage, SOAPEnvelope soapEnvelope, Context context,
        NamedNodeMap attributes, SOAPElement soapElement) throws SOAPException {
    SOAPElement soapMethodResponseElement = (SOAPElement) soapEnvelope.getBody().getFirstChild();
    String targetNamespace = soapMethodResponseElement.getNamespaceURI();
    String prefix = soapMethodResponseElement.getPrefix();

    int len = attributes.getLength();
    Attr attribute;/*from  w  w w  .ja  v a2 s.co  m*/
    for (int i = 0; i < len; i++) {
        attribute = (Attr) attributes.item(i);
        String attributeName = attribute.getName();
        String attributeValue = attribute.getNodeValue();
        String attributeNsUri = attribute.getNamespaceURI();
        String attributePrefix = getPrefix(context.projectName, attributeNsUri);

        XmlSchemaAttribute xmlSchemaAttribute = getXmlSchemaAttributeByName(context.projectName, attributeName);
        boolean isGlobal = xmlSchemaAttribute != null;
        if (isGlobal) {
            attributeNsUri = xmlSchemaAttribute.getQName().getNamespaceURI();
            attributePrefix = getPrefix(context.projectName, attributeNsUri);
        }

        if (XsdForm.qualified == context.project.getSchemaElementForm() || isGlobal) {
            if (attributePrefix == null) {
                soapElement.addAttribute(soapEnvelope.createName(attributeName, prefix, targetNamespace),
                        attributeValue);
            } else {
                soapElement.addAttribute(
                        soapEnvelope.createName(attributeName, attributePrefix, attributeNsUri),
                        attributeValue);
            }
        } else {
            soapElement.addAttribute(soapEnvelope.createName(attributeName), attributeValue);
        }
    }
}

From source file:com.hardcopy.retrowatch.contents.FeedParser.java

/*****************************************************
 *      Public methods//from  ww w. j  ava  2 s .c o  m
 ******************************************************/

public ArrayList<FeedObject> parseResultString(CPObject CpObj, String strResult) {
    if (CpObj == null)
        return null;

    int type = CpObj.mId;
    ArrayList<FeedObject> feedList = new ArrayList<FeedObject>();

    Logs.d(TAG, "# Parsing string :: CP type = " + CpObj.mId + ", parsing type = " + CpObj.mParsingType);

    switch (CpObj.mParsingType) {
    case FeedObject.REQUEST_TYPE_DAUM_REALTIME_KEYWORDS: {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(strResult));

            Document doc = db.parse(is);
            Element element = doc.getDocumentElement();

            NodeList items = element.getElementsByTagName(PARSING_TAG_WORD); // <realtime/>[ <word/> {<rank/><keyword/><value/><type/><linkurl/>} ]

            for (int i = 0; i < items.getLength(); i++) {
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                int rankType = RANK_TYPE_NONE;
                int rankUpAndDown = 0;
                int commentCount = 0;

                Node item = items.item(i); //  ? Node? ??  .
                NodeList children = item.getChildNodes(); // ?? Node 

                for (int j = 0; j < children.getLength(); j++) {
                    Node child = children.item(j);
                    String nodeName = child.getNodeName();
                    if (nodeName.equalsIgnoreCase(PARSING_TAG_KEYWORD)) {
                        String temp = child.getFirstChild().getNodeValue();
                        if (temp != null)
                            keyword = new String(temp.getBytes());
                    } else if (nodeName.equalsIgnoreCase(PARSING_TAG_LINKURL)) {
                        String temp = child.getFirstChild().getNodeValue();
                        if (temp != null)
                            link = new String(temp.getBytes(), ENCODING_TYPE_UTF_8);
                    } else if (nodeName.equalsIgnoreCase(PARSING_TAG_TYPE)) {
                        String temp = child.getFirstChild().getNodeValue();
                        if (temp != null) {
                            String temp2 = new String(temp.getBytes(), ENCODING_TYPE_UTF_8); // <type> value : "new" or "++"
                            if (temp2.equalsIgnoreCase(PARSING_TAG_NEW))
                                rankType = RANK_TYPE_NEW;
                        }
                    } else if (nodeName.equalsIgnoreCase(PARSING_TAG_VALUE)) {
                        try {
                            String temp = child.getFirstChild().getNodeValue();
                            if (temp != null && temp.length() > 0) {
                                String temp2 = new String(temp.getBytes(), ENCODING_TYPE_UTF_8); // <value> : 
                                rankUpAndDown = Integer.parseInt(temp2) / RANK_MODIFIER_DAUM_REALTIME_KEYWORD; // TODO:
                                if (rankUpAndDown > 10)
                                    rankUpAndDown = 10;
                            }
                        } catch (Exception e) {
                        }
                    }
                } // End of for loop

                if (keyword != null && link != null) {
                    String idStr = keyword;
                    FeedObject feed = new FeedObject(type, idStr, link, keyword, null, null);
                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feed.setRankInfo(rankType, rankUpAndDown, commentCount);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop

        } catch (Exception e) {
            Logs.d(TAG, e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_NAVER_REALTIME_KEYWORDS: {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(strResult));

            Document doc = db.parse(is);
            Element element = doc.getDocumentElement();

            NodeList temp = element.getElementsByTagName(PARSING_TAG_ITEM); // result -> item 
            NodeList items = temp.item(0).getChildNodes(); // List contains R1, R2...

            //? ? ??? Node ?
            for (int i = 0; i < items.getLength(); i++) {
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                int rankType = RANK_TYPE_NONE;
                int rankUpAndDown = 0;
                int commentCount = 0;

                Node item = items.item(i); // <Rn> :    n-th R tag
                NodeList children = item.getChildNodes(); // <k> <s> <v>

                for (int j = 0; j < children.getLength(); j++) {
                    Node child = children.item(j);
                    String nodeName = child.getNodeName();
                    if (nodeName.equalsIgnoreCase(PARSING_TAG_K)) {
                        String tempStr = child.getFirstChild().getNodeValue();
                        if (tempStr != null)
                            keyword = new String(tempStr.getBytes());
                    } else if (nodeName.equalsIgnoreCase(PARSING_TAG_V)) {
                        String tempStr = child.getFirstChild().getNodeValue();
                        rankUpAndDown = Integer.parseInt(tempStr) / RANK_MODIFIER_NAVER_REALTIME_KEYWORD; // TODO: 
                        if (rankUpAndDown > 10)
                            rankUpAndDown = 10;
                    }
                }

                if (keyword != null) {
                    String idStr = keyword;
                    FeedObject feed = new FeedObject(type, idStr, null, keyword, null, null);
                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feed.setRankInfo(rankType, rankUpAndDown, commentCount);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop

        } catch (Exception e) {
            Logs.d(TAG, e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_DAUM_SOCIAL_PICK: {
        try {
            JSONObject jsonRoot = new JSONObject(strResult); // root { 
            JSONObject jsonObjSocialPick = jsonRoot.getJSONObject(PARSING_TAG_SOCIALPICK); // { socialpick :
            JSONArray jsonArray = jsonObjSocialPick.getJSONArray(PARSING_TAG_ITEM); // {item: [

            for (int i = 0; i < jsonArray.length(); i++) {
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                int rankType = RANK_TYPE_NONE;
                int rankUpAndDown = 0;
                int commentCount = 0;

                JSONObject obj = jsonArray.getJSONObject(i); // {rank:1, link:"xx", keyword:"xx", content:"xx", count:30000, quotation_cnt:1345, comment_cnt:13816, rank_diff:3, category:"c" }
                link = obj.getString(PARSING_TAG_LINK);
                keyword = obj.getString(PARSING_TAG_KEYWORD);
                content = obj.getString(PARSING_TAG_CONTENT);
                commentCount = obj.getInt(PARSING_TAG_COMMENT_CNT) / RANK_MODIFIER_DAUM_SOCIALPICK;
                commentCount = commentCount * 2; // To encourage rank priority
                if (commentCount > 10)
                    commentCount = 10;

                if (link != null && keyword != null && content != null) {
                    String idStr = keyword;
                    FeedObject feed = new FeedObject(type, idStr, link, keyword, content, null);
                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feed.setRankInfo(rankType, rankUpAndDown, commentCount);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop
        } catch (JSONException e) {
            Logs.d(TAG, "##### JSON Parsing stopped with error :");
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_TWITTER_HOTTEST:
    case FeedObject.REQUEST_TYPE_TWITTER_REALTIME:
    case FeedObject.REQUEST_TYPE_TWITTER_TODAY:
    case FeedObject.REQUEST_TYPE_TWITTER_IMAGE: {
        String link = null;
        String keyword = null;
        String content = null;
        String thumbnail = null;

        try {
            JSONObject jsonRoot = new JSONObject(strResult); // root { 
            JSONArray jsonObjList = jsonRoot.getJSONArray(PARSING_TAG_RANKED_TWIT_LIST); // { rankedTwitList : [

            for (int i = 0; i < jsonObjList.length(); i++) {
                JSONObject obj = jsonObjList.getJSONObject(i); // id, owner, body, rtRank, rtCount, registDate, links:{}, rtTwitCount, twitId

                //---------- make content
                String idStr = obj.getString(PARSING_TAG_ID);
                String name = obj.getString(PARSING_TAG_OWNER);
                content = obj.getString(PARSING_TAG_BODY);

                JSONObject linkObj = obj.getJSONObject(PARSING_TAG_LINKS);
                if (linkObj != null) {
                    try { // If there is no <image> object, skip below routine
                        JSONArray imageObjList = linkObj.getJSONArray(PARSING_TAG_IMAGE);
                        if (imageObjList != null) {
                            // Multiple images can be found, but we'll take only first one.
                            JSONObject objImg = imageObjList.getJSONObject(0);
                            thumbnail = objImg.getString(PARSING_TAG_THUMBNAIL_URL);
                            link = objImg.getString(PARSING_TAG_URL);
                        }
                    } catch (Exception e) {
                    }
                }

                if (idStr != null && content != null) {
                    FeedObject feed = new FeedObject(type, idStr, link, keyword, content, thumbnail);
                    if (name != null)
                        feed.setName(name);
                    else
                        Log.d(TAG, "+++ Parsing :: id is null");

                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop
        } catch (JSONException e) {
            Logs.d(TAG, "##### JSON Parsing stopped with error :");
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_NAVER_RELATED_KEYWORDS: {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(strResult));

            // Document Element  w3c dom? ? ? .
            Document doc = db.parse(is);
            Element element = doc.getDocumentElement();

            NodeList temp = element.getElementsByTagName(PARSING_TAG_ITEM); // result -> item 

            //? ? ??? Node ?
            for (int i = 0; i < temp.getLength(); i++) {
                String keyword = null;
                Node item = temp.item(i);
                String tempStr = item.getFirstChild().getNodeValue();
                if (tempStr != null && tempStr.length() > 0)
                    keyword = new String(tempStr.getBytes());

                if (keyword != null) {
                    FeedObject feed = new FeedObject(type, keyword, null, keyword, null, null);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop

        } catch (Exception e) {
            Logs.d(TAG, e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_9GAG_HOT:
    case FeedObject.REQUEST_TYPE_9GAG_TREND: {
        try {
            JSONObject jsonRoot = new JSONObject(strResult); // root { 
            JSONArray jsonArray = jsonRoot.getJSONArray(PARSING_TAG_DATA); // {data: [

            long current = System.currentTimeMillis();
            for (int i = 0; i < jsonArray.length(); i++) {
                String id = null;
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                String fullSizeImage = null;
                // {id:xx, from:{name:xx}, caption:xx, images:{small:xx, normal:xx, large:xx}, link:xx, action:{like:xx, dislike:xx, unlike:xx}, vote:{count:xx}
                JSONObject obj = jsonArray.getJSONObject(i);
                id = obj.getString(PARSING_TAG_ID);
                link = obj.getString(PARSING_TAG_LINK);
                keyword = obj.getString(PARSING_TAG_CAPTION);
                JSONObject objImage = obj.getJSONObject(PARSING_TAG_IMAGES);
                thumbnail = objImage.getString(PARSING_TAG_SMALL);
                fullSizeImage = objImage.getString(PARSING_TAG_NORMAL);

                if (id != null && link != null && keyword != null && thumbnail != null) {
                    FeedObject feed = new FeedObject(type, id, link, keyword, null, thumbnail);
                    feed.setFullSizeImageURL(fullSizeImage);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop
        } catch (JSONException e) {
            Logs.d(TAG, "##### JSON Parsing stopped with error :");
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_NOTICE: {
        try {
            JSONObject jsonRoot = new JSONObject(strResult); // root { 
            JSONArray jsonArray = jsonRoot.getJSONArray(PARSING_TAG_NOTICE); // {notice: [

            long current = System.currentTimeMillis();
            for (int i = 0; i < jsonArray.length(); i++) {
                int version = 0;
                String id = null;
                String link = null;
                String name = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                String fullSizeImage = null;
                // {title:XXX, LINK:XXX, description:XXX, author:XXX, appversion:XXX, pubDate:XXX
                JSONObject obj = jsonArray.getJSONObject(i);

                keyword = obj.getString(PARSING_TAG_TITLE);
                link = obj.getString(PARSING_TAG_LINK);
                content = obj.getString(PARSING_TAG_DESCRIPTION);
                name = obj.getString(PARSING_TAG_AUTHOR);
                version = obj.getInt(PARSING_TAG_APP_VERSION);
                id = obj.getString(PARSING_TAG_PUBDATE);

                if (id != null && link != null && keyword != null) {
                    FeedObject feed = new FeedObject(type, id, link, keyword, content, null);
                    feed.setName(name);
                    feed.setDate(id);
                    feed.setVersion(version);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop
        } catch (JSONException e) {
            Logs.d(TAG, "##### JSON Parsing stopped with error :");
            e.printStackTrace();
            feedList = null;
        }
        break;
    }

    case FeedObject.REQUEST_TYPE_RSS_DEFAULT:
    case FeedObject.REQUEST_TYPE_RSS_FEED43: {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = factory.newDocumentBuilder();

            InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(strResult));

            // Document Element  w3c dom? ? ? .
            Document doc = db.parse(is);
            Element element = doc.getDocumentElement();

            // Extract logo image
            try {
                NodeList logoImage = element.getElementsByTagName(PARSING_TAG_IMAGE);
                if (logoImage != null && logoImage.getLength() > 0) {
                    Node logoitem = logoImage.item(0);
                    NodeList logochildren = logoitem.getChildNodes();
                    for (int j = 0; j < logochildren.getLength(); j++) {
                        Node logochild = logochildren.item(j);
                        String logoName = logochild.getNodeName();
                        if (logoName.equalsIgnoreCase(PARSING_TAG_URL)) {
                            String tempStr = logochild.getFirstChild().getNodeValue();
                            if (tempStr != null && tempStr.length() > 0)
                                CpObj.mLogoImage = tempStr;
                        }
                    }
                }
            } catch (Exception e) {
            }

            NodeList temp = element.getElementsByTagName(PARSING_TAG_ITEM); // channel -> item 

            long current = System.currentTimeMillis();
            for (int i = 0; i < temp.getLength(); i++) {
                int version = 0;
                String guid = null;
                String name = null;
                String date = null;
                String link = null;
                String keyword = null;
                String content = null;
                String thumbnail = null;
                Node item = temp.item(i); // <item> :    n-th item tag
                NodeList children = item.getChildNodes(); // <title> <author> <link> <description> <pubDate>

                for (int j = 0; j < children.getLength(); j++) {
                    try { // If error occurs in this block, skip current item parsing and go next
                        Node child = children.item(j);
                        String nodeName = child.getNodeName();
                        if (nodeName.equalsIgnoreCase(PARSING_TAG_LINK)) {
                            String tempStr = child.getFirstChild().getNodeValue();
                            if (tempStr != null)
                                link = new String(tempStr.getBytes());
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_TITLE)) {
                            String tempStr = child.getFirstChild().getNodeValue();
                            if (tempStr != null) {
                                keyword = new String(tempStr.getBytes());
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_DESCRIPTION)) {
                            String tempStr = child.getFirstChild().getNodeValue();
                            if (tempStr != null) {
                                String[] strArray = tempStr.split(STRING_RSS_SPLIT_TAG);
                                if (strArray[0] != null && strArray[0].length() > 0) {
                                    strArray[0] = Html.fromHtml(strArray[0]).toString();
                                    strArray[0] = strArray[0].replaceAll(REG_EXP_REMOVE_TAG, "");
                                    strArray[0] = strArray[0].replaceAll(REG_EXP_REMOVE_NEWLINE, "");
                                    content = strArray[0];
                                }
                                if (strArray.length > 1 && strArray[1] != null && strArray[1].length() > 0) {
                                    thumbnail = strArray[1];
                                }
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_AUTHOR)) {
                            if (child != null && child.getFirstChild() != null) {
                                String tempStr = child.getFirstChild().getNodeValue();
                                if (tempStr != null)
                                    name = new String(tempStr.getBytes());
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_PUBDATE)) {
                            if (child != null && child.getFirstChild() != null) {
                                String tempStr = child.getFirstChild().getNodeValue();
                                if (tempStr != null)
                                    date = new String(tempStr.getBytes());
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_GUID)) {
                            if (child != null && child.getFirstChild() != null) {
                                String tempStr = child.getFirstChild().getNodeValue();
                                if (tempStr != null)
                                    guid = new String(tempStr.getBytes());
                            }
                        } else if (nodeName.equalsIgnoreCase(PARSING_TAG_APP_VERSION)) {
                            if (child != null && child.getFirstChild() != null) {
                                String tempStr = child.getFirstChild().getNodeValue();
                                if (tempStr != null && tempStr.length() > 0)
                                    version = Integer.parseInt(tempStr);
                            }
                        } else if (nodeName.contains(PARSING_TAG_THUMBNAIL)) {
                            try {
                                if (child != null && child.hasAttributes()) {
                                    NamedNodeMap attrs = child.getAttributes();
                                    for (int k = 0; k < attrs.getLength(); k++) {
                                        Node attr = attrs.item(k);
                                        if (attr.getNodeName().equalsIgnoreCase(PARSING_TAG_URL)) {
                                            thumbnail = attr.getNodeValue();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                thumbnail = null;
                            }

                        } else if (nodeName.contains(PARSING_TAG_ENCLOSURE)) {
                            try {
                                if (child != null && child.hasAttributes()) {
                                    NamedNodeMap attrs = child.getAttributes();
                                    for (int k = 0; k < attrs.getLength(); k++) {
                                        Node attr = attrs.item(k);
                                        if (attr.getNodeName().equalsIgnoreCase(PARSING_TAG_URL)) {
                                            thumbnail = attr.getNodeValue();
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                thumbnail = null;
                            }

                        }

                    } catch (Exception e) {
                        Logs.d(TAG,
                                e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
                        e.printStackTrace();
                    }

                } // End of for loop.... parsing each item

                if (link != null && keyword != null && content != null) {
                    StringBuilder sb = new StringBuilder();
                    if (guid != null) {
                        sb.append("rss_").append(removeSpecialChars(guid));
                    } else if (date != null) {
                        sb.append("rss_").append(date.replace(",", "").replace(":", "").trim());
                    } else {
                        String temp1 = null;
                        if (keyword.length() > 50)
                            temp1 = keyword.substring(0, 50);
                        else
                            temp1 = keyword;
                        temp1 = URLEncoder.encode(temp1, ENCODING_TYPE_UTF_8).replace("+", "%20")
                                .replace("*", "%2A").replace("%7E", "~");
                        if (temp1.length() > PARSER_ID_SUBSTRING_MAX)
                            temp1 = temp1.substring(0, PARSER_ID_SUBSTRING_MAX - 1);
                        temp1 = temp1.trim();
                        sb.append("rss_").append(temp1);
                    }

                    FeedObject feed = new FeedObject(type, sb.toString(), link, keyword, content, thumbnail);
                    feed.mDownloadStatus = FeedObject.CONTENT_DOWNLOAD_STATUS_INIT;
                    feed.setDate(date);
                    feed.setName(name);
                    if (CpObj.mParsingType == FeedObject.REQUEST_TYPE_NOTICE && version > 0)
                        feed.setVersion(version);
                    feedList.add(feed);
                }

                if (i >= CpObj.mCachingCount - 1) { // Break loop if count has reached caching count
                    break;
                }
            } // End of for loop

        } catch (Exception e) {
            Logs.d(TAG, e.getMessage() == null ? "Unknown error while parsing xml" : e.getMessage());
            e.printStackTrace();
            feedList = null;
        }
        break;
    } // End of default block

    } // End of switch(type)

    return feedList;

}

From source file:com.twinsoft.convertigo.beans.transactions.XmlHttpTransaction.java

@Override
public void makeDocument(byte[] httpData) throws Exception {
    Engine.logBeans.trace("makeDocument : " + getEncodingCharSet());

    Charset charset = XMLUtils.getEncoding(httpData, Charset.forName(xmlEncoding));

    String sdata = new String(httpData, charset);
    sdata = sdata.replaceFirst("[\\d\\D]*?<", "<");
    Engine.logBeans.trace("makeDocument afternewString: " + sdata);

    Document xmlHttpDocument = requester.parseDOM(sdata);
    if (Engine.logBeans.isTraceEnabled())
        Engine.logBeans.trace("makeDocument after parseDom: " + XMLUtils.prettyPrintDOM(xmlHttpDocument));

    // Replace SOAP fault by an c8o error element
    if (isErrorOnSoapFault()) {
        Element soapFaultElement = null;
        soapFaultElement = getSoapFaultElement(xmlHttpDocument);
        if (soapFaultElement != null) {
            String sfm = getSoapFaultMessage(soapFaultElement);
            ConvertigoException ex = new ConvertigoException("The Web Service returned a SOAP Fault",
                    new SOAPException(sfm));
            ConvertigoError err = ConvertigoError.initError(ErrorType.Project, ex);
            Document errDocument = err.buildErrorDocument(getRequester(), context);
            Node error = context.outputDocument.importNode(errDocument.getDocumentElement().getFirstChild(),
                    true);//from w w  w . j  a v a2s . com
            context.outputDocument.getDocumentElement().appendChild(error);
            return;
        }
    }

    if (getAllowDownloadAttachment()) {
        Element attachmentInfo = (Element) XPathAPI.selectSingleNode(context.outputDocument,
                "/document/AttachmentInfo");

        if (attachmentInfo != null) {
            NodeList nl = XPathAPI.selectNodeList(attachmentInfo, "attachment");

            for (int i = 0; i < nl.getLength(); i++) {
                Element attachment = (Element) nl.item(i);
                String cid = attachment.getAttribute("cid");

                if (StringUtils.isNotBlank(cid)) {
                    Element include = (Element) XPathAPI.selectSingleNode(xmlHttpDocument,
                            "//*[local-name()='Include' and @href='" + cid + "']");

                    if (include != null) {
                        include.appendChild(xmlHttpDocument.importNode(attachment, true));
                        XMLUtils.removeNode(attachment);
                    }
                }
            }

            if (XPathAPI.selectSingleNode(attachmentInfo, "attachment") == null) {
                XMLUtils.removeNode(attachmentInfo);
            }
        }
    }

    // Removes soap elements if needed
    if (isIgnoreSoapEnveloppe()) {
        Element soapBodyResponseElement = null;
        soapBodyResponseElement = getSoapBodyResponseElement(xmlHttpDocument.getDocumentElement());
        if (soapBodyResponseElement != null) {
            NamedNodeMap attributes = ((Element) soapBodyResponseElement.getParentNode()).getAttributes();
            NodeList childNodes = soapBodyResponseElement.getChildNodes();
            int len = childNodes.getLength();
            Node child, node;
            for (int i = 0; i < len; i++) {
                node = childNodes.item(i);
                if (node instanceof Element) {
                    //child = importNodeWithNoPrefix(context.outputDocument, node, true);
                    child = context.outputDocument.importNode(node, true);
                    // add envelope attributes (e.g namespace declarations to avoid unbound prefixes for XSL transformation)
                    for (int j = 0; j < attributes.getLength(); j++) {
                        Node attr = attributes.item(j);
                        ((Element) child)
                                .setAttributeNode((Attr) context.outputDocument.importNode(attr, true));
                    }
                    context.outputDocument.getDocumentElement().appendChild(child);
                }
            }
        } else {
            XMLUtils.copyDocument(xmlHttpDocument, context.outputDocument);
        }
    }
    // Normal case
    else
        XMLUtils.copyDocument(xmlHttpDocument, context.outputDocument);
}

From source file:com.moviejukebox.reader.MovieJukeboxXMLReader.java

/**
 * Parse the person XML file from the jukebox
 *
 * @param xmlFile/*w w  w .ja  v  a  2  s.com*/
 * @param person
 * @return
 */
public boolean parsePersonXML(File xmlFile, Person person) {
    Document xmlDoc;
    try {
        xmlDoc = DOMHelper.getDocFromFile(xmlFile);
    } catch (MalformedURLException error) {
        LOG.error(ERROR_FIXIT, xmlFile.getName(), "person");
        LOG.error(SystemTools.getStackTrace(error));
        return Boolean.FALSE;
    } catch (IOException error) {
        LOG.error(ERROR_FIXIT, xmlFile.getName(), "person");
        LOG.error(SystemTools.getStackTrace(error));
        return Boolean.FALSE;
    } catch (ParserConfigurationException | SAXException error) {
        LOG.error(ERROR_FIXIT, xmlFile.getName(), "person");
        LOG.error(SystemTools.getStackTrace(error));
        return Boolean.FALSE;
    }

    Node nPeople, nTemp;
    NodeList nlPeople = xmlDoc.getElementsByTagName("person");
    String sTemp;
    Element eTemp;
    NodeList nlTemp;
    for (int looper = 0; looper < nlPeople.getLength(); looper++) {
        nPeople = nlPeople.item(looper);
        if (nPeople.getNodeType() == Node.ELEMENT_NODE) {
            Element ePerson = (Element) nPeople;

            // Get IDs
            nlTemp = ePerson.getElementsByTagName("id");
            for (int idLoop = 0; idLoop < nlTemp.getLength(); idLoop++) {
                nTemp = nlTemp.item(idLoop);

                if (nTemp.getNodeType() == Node.ELEMENT_NODE) {
                    Element eId = (Element) nTemp;
                    String personDatabase = eId.getAttribute("persondb");
                    if (StringTools.isNotValidString(personDatabase)) {
                        personDatabase = ImdbPlugin.IMDB_PLUGIN_ID;
                    }
                    person.setId(personDatabase, eId.getTextContent());
                }
            }

            // Get Name
            eTemp = DOMHelper.getElementByName(ePerson, "name");
            if (eTemp != null) {
                sTemp = eTemp.getTextContent();
                if (StringTools.isNotValidString(person.getName())) {
                    person.setName(sTemp);
                } else {
                    person.addAka(sTemp);
                }
            }

            person.setTitle(DOMHelper.getValueFromElement(ePerson, "title"));
            person.setFilename(DOMHelper.getValueFromElement(ePerson, "baseFilename"));
            person.setBiography(DOMHelper.getValueFromElement(ePerson, "biography"));
            person.setYear(DOMHelper.getValueFromElement(ePerson, "birthday"));
            person.setBirthPlace(DOMHelper.getValueFromElement(ePerson, "birthplace"));
            person.setBirthName(DOMHelper.getValueFromElement(ePerson, "birthname"));
            person.setUrl(DOMHelper.getValueFromElement(ePerson, "url"));
            person.setPhotoFilename(DOMHelper.getValueFromElement(ePerson, "photoFile"));
            person.setPhotoURL(DOMHelper.getValueFromElement(ePerson, "photoURL"));
            person.setBackdropFilename(DOMHelper.getValueFromElement(ePerson, "backdropFile"));
            person.setBackdropURL(DOMHelper.getValueFromElement(ePerson, "backdropURL"));
            person.setKnownMovies(Integer.parseInt(DOMHelper.getValueFromElement(ePerson, "knownMovies")));
            person.setVersion(Integer.parseInt(DOMHelper.getValueFromElement(ePerson, "version")));
            person.setLastModifiedAt(DOMHelper.getValueFromElement(ePerson, "lastModifiedAt"));

            nlTemp = ePerson.getElementsByTagName("movie");
            for (int movieLoop = 0; movieLoop < nlTemp.getLength(); movieLoop++) {
                nTemp = nlTemp.item(movieLoop);
                if (nTemp.getNodeType() == Node.ELEMENT_NODE) {
                    Filmography film = new Filmography();
                    Element eMovie = (Element) nTemp;

                    film.setId(eMovie.getAttribute("id"));

                    // Process the attributes
                    NamedNodeMap nnmAttr = eMovie.getAttributes();
                    for (int i = 0; i < nnmAttr.getLength(); i++) {
                        Node nAttr = nnmAttr.item(i);
                        String ns = nAttr.getNodeName();

                        if ("id".equalsIgnoreCase(ns)) {
                            film.setId(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.toLowerCase().contains(ID)) {
                            person.setId(ns.substring(3), nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(NAME)) {
                            film.setName(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(TITLE)) {
                            film.setTitle(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(ORIGINAL_TITLE)) {
                            film.setOriginalTitle(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(YEAR)) {
                            film.setYear(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(RATING)) {
                            film.setRating(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(CHARACTER)) {
                            film.setCharacter(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(JOB)) {
                            film.setJob(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(DEPARTMENT)) {
                            film.setDepartment(nAttr.getTextContent());
                            continue;
                        }
                        if (ns.equalsIgnoreCase(URL)) {
                            film.setUrl(nAttr.getTextContent());
                            //continue; // Last contine not needed
                        }
                    }

                    // Set the filename
                    film.setFilename(eMovie.getTextContent());
                    film.setDirty(Boolean.FALSE);
                    person.addFilm(film);
                }
            }

            person.setFilename();
            person.setDirty(Boolean.FALSE);

            // Only process the first in the file
            return Boolean.TRUE;
        }
    }

    // FAILED
    return Boolean.FALSE;
}

From source file:jp.co.acroquest.jsonic.Formatter.java

public boolean format(final JSON json, final Context context, final Object src, final Object o,
        final OutputSource out) throws Exception {
    Element elem = (Element) o;
    out.append('[');
    StringFormatter.serialize(context, elem.getTagName(), out);

    out.append(',');
    if (context.isPrettyPrint()) {
        out.append('\n');
        for (int j = 0; j < context.getDepth() + 1; j++)
            out.append('\t');
    }//w w  w . j ava 2 s .  co m
    out.append('{');
    if (elem.hasAttributes()) {
        NamedNodeMap names = elem.getAttributes();
        for (int i = 0; i < names.getLength(); i++) {
            if (i != 0) {
                out.append(',');
            }
            if (context.isPrettyPrint() && names.getLength() > 1) {
                out.append('\n');
                for (int j = 0; j < context.getDepth() + 2; j++)
                    out.append('\t');
            }
            Node node = names.item(i);
            if (node instanceof Attr) {
                StringFormatter.serialize(context, node.getNodeName(), out);
                out.append(':');
                if (context.isPrettyPrint())
                    out.append(' ');
                StringFormatter.serialize(context, node.getNodeValue(), out);
            }
        }
        if (context.isPrettyPrint() && names.getLength() > 1) {
            out.append('\n');
            for (int j = 0; j < context.getDepth() + 1; j++)
                out.append('\t');
        }
    }
    out.append('}');
    if (elem.hasChildNodes()) {
        NodeList nodes = elem.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Object value = nodes.item(i);
            if ((value instanceof Element) || (value instanceof CharacterData && !(value instanceof Comment))) {
                out.append(',');
                if (context.isPrettyPrint()) {
                    out.append('\n');
                    for (int j = 0; j < context.getDepth() + 1; j++)
                        out.append('\t');
                }
                context.enter(i + 2);
                value = json.preformatInternal(context, value);
                json.formatInternal(context, value, out);
                context.exit();
                if (out instanceof Flushable)
                    ((Flushable) out).flush();
            }
        }
    }
    if (context.isPrettyPrint()) {
        out.append('\n');
        for (int j = 0; j < context.getDepth(); j++)
            out.append('\t');
    }
    out.append(']');
    return true;
}