Example usage for org.w3c.dom Node hasAttributes

List of usage examples for org.w3c.dom Node hasAttributes

Introduction

In this page you can find the example usage for org.w3c.dom Node hasAttributes.

Prototype

public boolean hasAttributes();

Source Link

Document

Returns whether this node (if it is an element) has any attributes.

Usage

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

private Document replaceIfExistingByXPaths(final Document originalDom, final Document modifiedDom,
        Map<String, String> xPathPairs) throws XPathExpressionException {

    Document finalDom = originalDom;
    Element finalDomRoot = (Element) finalDom.getFirstChild();

    //Element modifiedDomRoot = (Element) modifiedDom.getFirstChild();

    Element lastChild = null;/*from   w w w .j  a  v  a 2s .  com*/

    for (Entry<String, String> xPathPair : xPathPairs.entrySet()) {

        /**
         * basically, this is to copy the element specified in srcXPath, and
         * replace/add it to the position pointed by destXPath...
         */
        String srcXPath = xPathPair.getKey();

        logger.debug("srcXPath: " + srcXPath);

        String destXPath = xPathPair.getValue();

        logger.debug("destXPath: " + destXPath);

        XPath xPath = getXPathInstance();
        // find all the nodes specified by destXPath in the originalDom, and
        // delete them all
        NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET));

        xPath.reset();
        // find all the nodes specified by srcXPath in the modifiedDom
        NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET));

        int el = existingNodeList.getLength();

        logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath);

        int l = nodeList.getLength();

        logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath);

        for (int i = 0; i < el; i++) {
            Node c = existingNodeList.item(i);

            //xPathExpression = xPath.compile(srcXPath);
            //NodeList srcNodeLst = (NodeList) (xPathExpression.evaluate(
            //modifiedDom, XPathConstants.NODESET));
            //NodeList srcNodeLst = modifiedDomRoot.getElementsByTagName(c.getNodeName());

            if (l > 0) {
                // remove this node from its parent...

                c.getParentNode().removeChild(c);
                logger.debug("Node:" + c.getNodeName() + " is removed!");
            }

        }

        // create the node structure first. and return the last child of the
        // path... the right most node...
        lastChild = createElementStructureByPath(finalDomRoot, destXPath);

        List<String> nodeNameList = getNodeList(destXPath);

        String lastNodeName = nodeNameList.get(nodeNameList.size() - 1);

        Node currentNode = null;
        for (int i = 0; i < l; i++) {
            currentNode = nodeList.item(i);

            // the name of the last node in srcXPath might not be the same
            // as the name of the last node in destXPath
            Element lastElement = finalDom.createElement(lastNodeName);

            // NodeList currentNodeChildNodes = currentNode.getChildNodes();
            // int s = currentNodeChildNodes.getLength();
            // for(int j = 0; j < s; j++){
            // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j),
            // true));
            // }
            if (currentNode.hasAttributes()) {
                NamedNodeMap attributes = currentNode.getAttributes();

                for (int j = 0; j < attributes.getLength(); j++) {
                    String attribute_name = attributes.item(j).getNodeName();
                    String attribute_value = attributes.item(j).getNodeValue();

                    lastElement.setAttribute(attribute_name, attribute_value);
                }
            }

            while (currentNode.hasChildNodes()) {
                Node kid = currentNode.getFirstChild();
                currentNode.removeChild(kid);
                lastElement.appendChild(finalDom.importNode(kid, true));
            }

            lastChild.appendChild(lastElement);

        }

    }

    return finalDom;

}

From source file:org.dasein.cloud.vcloud.vCloudMethod.java

private void loadVDC(@Nonnull VDC vdc, @Nonnull String id) throws CloudException, InternalException {
    String xml = get("vdc", id);

    if (xml != null) {
        Document doc = parseXML(xml);
        String docElementTagName = doc.getDocumentElement().getTagName();
        String nsString = "";
        if (docElementTagName.contains(":"))
            nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1);
        NodeList vdcs = doc.getElementsByTagName(nsString + "Vdc");

        if (vdcs.getLength() < 1) {
            return;
        }//w  w w . j a  v  a2 s  . c  o  m
        NodeList attributes = vdcs.item(0).getChildNodes();

        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            if (attribute.getNodeName().contains(":"))
                nsString = attribute.getNodeName().substring(0, attribute.getNodeName().indexOf(":") + 1);
            else
                nsString = "";

            if (attribute.getNodeName().equalsIgnoreCase(nsString + "Link") && attribute.hasAttributes()) {
                Node rel = attribute.getAttributes().getNamedItem("rel");

                if (rel.getNodeValue().trim().equalsIgnoreCase("add")) {
                    Node type = attribute.getAttributes().getNamedItem("type");
                    Node href = attribute.getAttributes().getNamedItem("href");

                    if (type != null && href != null) {
                        vdc.actions.put(type.getNodeValue().trim(), href.getNodeValue().trim());
                    }
                }
            } else if (attribute.getNodeName().equalsIgnoreCase(nsString + "VmQuota")
                    && attribute.hasChildNodes()) {
                try {
                    vdc.vmQuota = Integer.parseInt(attribute.getFirstChild().getNodeValue().trim());
                } catch (NumberFormatException ignore) {
                    // ignore
                }
            } else if (attribute.getNodeName().equalsIgnoreCase(nsString + "NetworkQuota")
                    && attribute.hasChildNodes()) {
                try {
                    vdc.networkQuota = Integer.parseInt(attribute.getFirstChild().getNodeValue().trim());
                } catch (NumberFormatException ignore) {
                    // ignore
                }
            } else if (attribute.getNodeName().equalsIgnoreCase(nsString + "IsEnabled")
                    && attribute.hasChildNodes()) {
                boolean enabled = attribute.getFirstChild().getNodeValue().trim().equalsIgnoreCase("true");

                if (!enabled) {
                    vdc.dataCenter.setActive(false);
                    vdc.dataCenter.setAvailable(false);
                }
            }
        }
    }
}

From source file:com.nortal.jroad.typegen.xmlbeans.XteeSchemaCodePrinter.java

private Node findFirstNode(final NodeList nodeList, final String elementName, final String name,
        boolean processChildElements) {

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node nNode = nodeList.item(i).cloneNode(true);
        String localName = nNode.getLocalName();
        if (localName != null && nNode.getLocalName().equals(elementName)) {
            if (name == null) {
                return nNode;
            } else {
                if (nNode.hasAttributes()) {
                    Node attrbute = nNode.getAttributes().getNamedItem("name");
                    if (attrbute != null && StringUtils.equals(attrbute.getNodeValue(), name)) {
                        return nNode;
                    }//from   w w  w .ja  va2  s  . c o  m
                }
            }
        }
        if (!processChildElements && "element".equals(localName)) {
            continue;
        }
        if (nNode.hasChildNodes()) {
            nNode = findFirstNode(nNode.getChildNodes(), elementName, name, processChildElements);
            if (nNode != null) {
                return nNode;
            }
        }
    }

    return null;
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Return the text value of the selected attribute.
 * //w  w  w  . ja v  a  2  s  .  c om
 * @param node
 *            The node.
 * @param xPath
 *            The xpath to select the node contain the attribute,
 * @param attributeName
 *            The name of the attribute.
 * @return The text value of the selected attribute.
 * @throws Exception
 *             If anything fails.
 */
public static String getAttributeValue(final Node node, final String xPath, final String attributeName)
        throws Exception {

    String result = null;
    Node attribute = selectSingleNode(node, xPath);
    if (attribute != null && attribute.hasAttributes()
            && attribute.getAttributes().getNamedItem(attributeName) != null) {

        result = attribute.getAttributes().getNamedItem(attributeName).getTextContent();
    }
    return result;
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Deletes the node selected by the given XPath from the provided node.
 * /*ww w.  j  a v  a 2  s  .c  o m*/
 * @param node
 *            The Node to delete the selected nodes from.
 * @param xPath
 *            The XPath selecting the sub nodes in the provided node.
 * @return returns the provided <code>Node</code> object. This <code>Node</code> object may be changed.
 * @throws Exception
 *             Thrown if anything fails.
 */
public static Node deleteNodes(final Node node, final String xPath) throws Exception {

    NodeList nodes = selectNodeList(node, xPath);
    if (nodes == null || nodes.getLength() == 0) {
        return node;
    }

    for (int i = 0; i < nodes.getLength(); ++i) {
        Node delete = nodes.item(i);
        if (delete.getNodeType() == Node.ATTRIBUTE_NODE) {
            final int index = xPath.lastIndexOf('/');
            String attribute = delete.getNodeName();
            attribute = attribute.substring(attribute.lastIndexOf(':') + 1);
            String elementXpath = xPath.substring(0, index);
            elementXpath += "[@" + attribute + "=\"" + delete.getTextContent().trim() + "\"]";
            Node parent = selectSingleNode(node, elementXpath);
            if (parent.hasAttributes()) {
                parent.getAttributes().removeNamedItem(delete.getNodeName());
            }
        } else {
            delete.getParentNode().removeChild(delete);
        }
    }

    return node;
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Delete an Attribute from an Element of a Node.
 * /*from  w  w  w.  j  a  v  a2 s.co  m*/
 * @param node
 *            the node.
 * @param xPath
 *            The xPath selecting the element.
 * @param attributeName
 *            The name of the attribute.
 * @return The resulting node.
 * @throws Exception
 *             If anything fails.
 */
public static Node deleteAttribute(final Node node, final String xPath, final String attributeName)
        throws Exception {

    if (node == null) {
        return node;
    }
    Node delete = selectSingleNode(node, xPath);
    if (delete == null) {
        return node;
    }
    if (delete.hasAttributes()) {
        for (int i = 0; i < delete.getAttributes().getLength(); ++i) {
            String nodeName = delete.getAttributes().item(i).getNodeName();
            if (nodeName.endsWith(":" + attributeName) || nodeName.equals(attributeName)) {
                delete.getAttributes().removeNamedItem(nodeName);
                break;
            }
        }
    }
    return node;
}

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

/*****************************************************
 *      Public methods/*from   w  ww .j  a v  a 2s .  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:org.apache.fop.tools.TestConverter.java

/**
 * Run the Tests.//from   ww  w.j  ava 2s .  com
 * This runs the tests specified in the xml file fname.
 * The document is read as a dom and each testcase is covered.
 * @param fname filename of the input file
 * @param dest destination directory
 * @param compDir comparison directory
 * @return Map a Map containing differences
 */
public Map runTests(String fname, String dest, String compDir) {
    logger.debug("running tests in file:" + fname);
    try {
        if (compDir != null) {
            compare = new File(baseDir + "/" + compDir);
        }
        destdir = new File(baseDir + "/" + dest);
        destdir.mkdirs();
        File f = new File(baseDir + "/" + fname);
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = factory.newDocumentBuilder();
        Document doc = db.parse(f);

        NodeList suitelist = doc.getChildNodes();
        if (suitelist.getLength() == 0) {
            return differ;
        }

        Node testsuite = null;
        testsuite = doc.getDocumentElement();

        if (testsuite.hasAttributes()) {
            String profile = testsuite.getAttributes().getNamedItem("profile").getNodeValue();
            logger.debug("testing test suite:" + profile);
        }

        NodeList testcases = testsuite.getChildNodes();
        for (int count = 0; count < testcases.getLength(); count++) {
            Node testcase = testcases.item(count);
            if (testcase.getNodeName().equals("testcases")) {
                runTestCase(testcase);
            }
        }
    } catch (Exception e) {
        logger.error("Error while running tests", e);
    }
    return differ;
}

From source file:org.apache.fop.tools.TestConverter.java

/**
 * Run a test case./*from w  w  w  . ja va  2 s  .c  o  m*/
 * This goes through a test case in the document.
 * A testcase can contain a test, a result or more test cases.
 * A test case is handled recursively otherwise the test is run.
 * @param tcase Test case node to run
 */
protected void runTestCase(Node tcase) {
    if (tcase.hasAttributes()) {
        String profile = tcase.getAttributes().getNamedItem("profile").getNodeValue();
        logger.debug("testing profile:" + profile);
    }

    NodeList cases = tcase.getChildNodes();
    for (int count = 0; count < cases.getLength(); count++) {
        Node node = cases.item(count);
        String nodename = node.getNodeName();
        if (nodename.equals("testcases")) {
            runTestCase(node);
        } else if (nodename.equals("test")) {
            runTest(tcase, node);
        } else if (nodename.equals("result")) {
            //nop
        }

    }

}