Example usage for org.xml.sax InputSource setCharacterStream

List of usage examples for org.xml.sax InputSource setCharacterStream

Introduction

In this page you can find the example usage for org.xml.sax InputSource setCharacterStream.

Prototype

public void setCharacterStream(Reader characterStream) 

Source Link

Document

Set the character stream for this input source.

Usage

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

/*****************************************************
 *      Public methods//from w  w w .  ja va  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.piusvelte.sonet.core.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);/*from w ww. j av a 2s  .c  o  m*/
    mHttpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Sonet.Accounts.SERVICE, Sonet.INVALID_SERVICE);
            mServiceName = Sonet.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Sonet.EXTRA_ACCOUNT_ID, Sonet.INVALID_ACCOUNT_ID);
            mSonetWebView = new SonetWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mSonetOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mSonetWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mSonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mSonetWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID,
                        FACEBOOK_CALLBACK.toString()));
                break;
            case MYSPACE:
                mSonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET);
                asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE,
                        MYSPACE_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case FOURSQUARE:
                mSonetWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mSonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Sonet.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            case IDENTICA:
                mSonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET);
                asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case GOOGLEPLUS:
                mSonetWebView.open(
                        String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob"));
                break;
            case CHATTER:
                mSonetWebView
                        .open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString()));
                break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:com.piusvelte.sonet.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);//from  w w  w. j  av a  2  s  .  co m
    mHttpClient = SonetHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Sonet.Accounts.SERVICE, Sonet.INVALID_SERVICE);
            mServiceName = Sonet.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Sonet.EXTRA_ACCOUNT_ID, Sonet.INVALID_ACCOUNT_ID);
            mSonetWebView = new SonetWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mSonetOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mSonetWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mSonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mSonetWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL,
                        BuildConfig.FACEBOOK_ID, FACEBOOK_CALLBACK.toString()));
                break;
            case MYSPACE:
                mSonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET);
                asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE,
                        MYSPACE_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case FOURSQUARE:
                mSonetWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, BuildConfig.FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mSonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return SonetHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Sonet.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            case IDENTICA:
                mSonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET);
                asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL),
                        String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case GOOGLEPLUS:
                mSonetWebView.open(String.format(GOOGLEPLUS_AUTHORIZE, BuildConfig.GOOGLECLIENT_ID,
                        "urn:ietf:wg:oauth:2.0:oob"));
                break;
            case CHATTER:
                mSonetWebView.open(String.format(CHATTER_URL_AUTHORIZE, BuildConfig.CHATTER_KEY,
                        CHATTER_CALLBACK.toString()));
                break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:com.shafiq.myfeedle.core.OAuthLogin.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setResult(RESULT_CANCELED);/*from   w ww . j a v  a  2  s .c  o  m*/
    mHttpClient = MyfeedleHttpClient.getThreadSafeClient(getApplicationContext());
    mLoadingDialog = new ProgressDialog(this);
    mLoadingDialog.setMessage(getString(R.string.loading));
    mLoadingDialog.setCancelable(true);
    mLoadingDialog.setOnCancelListener(this);
    mLoadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), this);
    Intent intent = getIntent();
    if (intent != null) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            int service = extras.getInt(Myfeedle.Accounts.SERVICE, Myfeedle.INVALID_SERVICE);
            mServiceName = Myfeedle.getServiceName(getResources(), service);
            mWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
            mAccountId = extras.getLong(Myfeedle.EXTRA_ACCOUNT_ID, Myfeedle.INVALID_ACCOUNT_ID);
            mMyfeedleWebView = new MyfeedleWebView();
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {
                @Override
                protected String doInBackground(String... args) {
                    try {
                        return mMyfeedleOAuth.getAuthUrl(args[0], args[1], args[2], args[3],
                                Boolean.parseBoolean(args[4]), mHttpClient);
                    } catch (OAuthMessageSignerException e) {
                        e.printStackTrace();
                    } catch (OAuthNotAuthorizedException e) {
                        e.printStackTrace();
                    } catch (OAuthExpectationFailedException e) {
                        e.printStackTrace();
                    } catch (OAuthCommunicationException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String url) {
                    if (loadingDialog.isShowing())
                        loadingDialog.dismiss();
                    // load the webview
                    if (url != null) {
                        mMyfeedleWebView.open(url);
                    } else {
                        (Toast.makeText(OAuthLogin.this,
                                String.format(getString(R.string.oauth_error), mServiceName),
                                Toast.LENGTH_LONG)).show();
                        OAuthLogin.this.finish();
                    }
                }
            };
            loadingDialog.setMessage(getString(R.string.loading));
            loadingDialog.setCancelable(true);
            loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    if (!asyncTask.isCancelled())
                        asyncTask.cancel(true);
                    dialog.cancel();
                    OAuthLogin.this.finish();
                }
            });
            loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (!asyncTask.isCancelled())
                                asyncTask.cancel(true);
                            dialog.cancel();
                            OAuthLogin.this.finish();
                        }
                    });
            switch (service) {
            case TWITTER:
                mMyfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET);
                asyncTask.execute(String.format(TWITTER_URL_REQUEST, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_ACCESS, TWITTER_BASE_URL),
                        String.format(TWITTER_URL_AUTHORIZE, TWITTER_BASE_URL), TWITTER_CALLBACK.toString(),
                        Boolean.toString(true));
                loadingDialog.show();
                break;
            case FACEBOOK:
                mMyfeedleWebView.open(String.format(FACEBOOK_URL_AUTHORIZE, FACEBOOK_BASE_URL, FACEBOOK_ID,
                        FACEBOOK_CALLBACK.toString()));
                break;
            // case MYSPACE:
            //     mMyfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET);
            //     asyncTask.execute(MYSPACE_URL_REQUEST, MYSPACE_URL_ACCESS, MYSPACE_URL_AUTHORIZE, MYSPACE_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case FOURSQUARE:
                mMyfeedleWebView.open(String.format(FOURSQUARE_URL_AUTHORIZE, FOURSQUARE_KEY,
                        FOURSQUARE_CALLBACK.toString()));
                break;
            case LINKEDIN:
                mMyfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET);
                asyncTask.execute(LINKEDIN_URL_REQUEST, LINKEDIN_URL_ACCESS, LINKEDIN_URL_AUTHORIZE,
                        LINKEDIN_CALLBACK.toString(), Boolean.toString(true));
                loadingDialog.show();
                break;
            case SMS:
                Cursor c = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(SMS) }, null);
                if (c.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "SMS has already been added.", Toast.LENGTH_LONG)).show();
                } else {
                    addAccount(getResources().getStringArray(R.array.service_entries)[SMS], null, null, 0, SMS,
                            null);
                }
                c.close();
                finish();
                break;
            case RSS:
                // prompt for RSS url
                final EditText rss_url = new EditText(this);
                rss_url.setSingleLine();
                new AlertDialog.Builder(OAuthLogin.this).setTitle(R.string.rss_url).setView(rss_url)
                        .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(final DialogInterface dialog, int which) {
                                // test the url and add if valid, else Toast error
                                mLoadingDialog.show();
                                (new AsyncTask<String, Void, String>() {
                                    String url;

                                    @Override
                                    protected String doInBackground(String... params) {
                                        url = rss_url.getText().toString();
                                        return MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(url));
                                    }

                                    @Override
                                    protected void onPostExecute(String response) {
                                        mLoadingDialog.dismiss();
                                        if (response != null) {
                                            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                                            DocumentBuilder db;
                                            try {
                                                db = dbf.newDocumentBuilder();
                                                InputSource is = new InputSource();
                                                is.setCharacterStream(new StringReader(response));
                                                Document doc = db.parse(is);
                                                // test parsing...
                                                NodeList nodes = doc.getElementsByTagName(Sitem);
                                                if (nodes.getLength() > 0) {
                                                    // check for an image
                                                    NodeList images = doc.getElementsByTagName(Simage);
                                                    if (images.getLength() > 0) {
                                                        NodeList imageChildren = images.item(0).getChildNodes();
                                                        Node n = imageChildren.item(0);
                                                        if (n.getNodeName().toLowerCase().equals(Surl)) {
                                                            if (n.hasChildNodes()) {
                                                                n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    NodeList children = nodes.item(0).getChildNodes();
                                                    String date = null;
                                                    String title = null;
                                                    String description = null;
                                                    String link = null;
                                                    int values_count = 0;
                                                    for (int child = 0, c2 = children.getLength(); (child < c2)
                                                            && (values_count < 4); child++) {
                                                        Node n = children.item(child);
                                                        if (n.getNodeName().toLowerCase().equals(Spubdate)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                date = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Stitle)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                title = n.getChildNodes().item(0)
                                                                        .getNodeValue();
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Sdescription)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                StringBuilder sb = new StringBuilder();
                                                                NodeList descNodes = n.getChildNodes();
                                                                for (int dn = 0, dn2 = descNodes
                                                                        .getLength(); dn < dn2; dn++) {
                                                                    Node descNode = descNodes.item(dn);
                                                                    if (descNode
                                                                            .getNodeType() == Node.TEXT_NODE) {
                                                                        sb.append(descNode.getNodeValue());
                                                                    }
                                                                }
                                                                // strip out the html tags
                                                                description = sb.toString()
                                                                        .replaceAll("\\<(.|\n)*?>", "");
                                                            }
                                                        } else if (n.getNodeName().toLowerCase()
                                                                .equals(Slink)) {
                                                            values_count++;
                                                            if (n.hasChildNodes()) {
                                                                link = n.getChildNodes().item(0).getNodeValue();
                                                            }
                                                        }
                                                    }
                                                    if (Myfeedle.HasValues(
                                                            new String[] { title, description, link, date })) {
                                                        final EditText url_name = new EditText(OAuthLogin.this);
                                                        url_name.setSingleLine();
                                                        new AlertDialog.Builder(OAuthLogin.this)
                                                                .setTitle(R.string.rss_channel)
                                                                .setView(url_name)
                                                                .setPositiveButton(android.R.string.ok,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                addAccount(
                                                                                        url_name.getText()
                                                                                                .toString(),
                                                                                        null, null, 0, RSS,
                                                                                        url);
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .setNegativeButton(android.R.string.cancel,
                                                                        new DialogInterface.OnClickListener() {
                                                                            @Override
                                                                            public void onClick(
                                                                                    DialogInterface dialog1,
                                                                                    int which) {
                                                                                dialog1.dismiss();
                                                                                dialog.dismiss();
                                                                                finish();
                                                                            }
                                                                        })
                                                                .show();
                                                    } else {
                                                        (Toast.makeText(OAuthLogin.this,
                                                                "Feed is missing standard fields",
                                                                Toast.LENGTH_LONG)).show();
                                                    }
                                                } else {
                                                    (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                            Toast.LENGTH_LONG)).show();
                                                    dialog.dismiss();
                                                    finish();
                                                }
                                            } catch (ParserConfigurationException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (SAXException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            } catch (IOException e) {
                                                Log.e(TAG, e.toString());
                                                (Toast.makeText(OAuthLogin.this, "Invalid feed",
                                                        Toast.LENGTH_LONG)).show();
                                                dialog.dismiss();
                                                finish();
                                            }
                                        } else {
                                            (Toast.makeText(OAuthLogin.this, "Invalid URL", Toast.LENGTH_LONG))
                                                    .show();
                                            dialog.dismiss();
                                            finish();
                                        }
                                    }
                                }).execute(rss_url.getText().toString());
                            }
                        }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).show();
                break;
            // case IDENTICA:
            //     mMyfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET);
            //     asyncTask.execute(String.format(IDENTICA_URL_REQUEST, IDENTICA_BASE_URL), String.format(IDENTICA_URL_ACCESS, IDENTICA_BASE_URL), String.format(IDENTICA_URL_AUTHORIZE, IDENTICA_BASE_URL), IDENTICA_CALLBACK.toString(), Boolean.toString(true));
            //     loadingDialog.show();
            //     break;
            case GOOGLEPLUS:
                mMyfeedleWebView.open(
                        String.format(GOOGLEPLUS_AUTHORIZE, GOOGLE_CLIENTID, "urn:ietf:wg:oauth:2.0:oob"));
                break;
            // case CHATTER:
            //     mMyfeedleWebView.open(String.format(CHATTER_URL_AUTHORIZE, CHATTER_KEY, CHATTER_CALLBACK.toString()));
            //     break;
            case PINTEREST:
                Cursor pinterestAccount = getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID }, Accounts.SERVICE + "=?",
                        new String[] { Integer.toString(PINTEREST) }, null);
                if (pinterestAccount.moveToFirst()) {
                    (Toast.makeText(OAuthLogin.this, "Pinterest has already been added.", Toast.LENGTH_LONG))
                            .show();
                } else {
                    (Toast.makeText(OAuthLogin.this,
                            "Pinterest currently allows only public, non-authenticated viewing.",
                            Toast.LENGTH_LONG)).show();
                    String[] values = getResources().getStringArray(R.array.service_values);
                    String[] entries = getResources().getStringArray(R.array.service_entries);
                    for (int i = 0, l = values.length; i < l; i++) {
                        if (Integer.toString(PINTEREST).equals(values[i])) {
                            addAccount(entries[i], null, null, 0, PINTEREST, null);
                            break;
                        }
                    }
                }
                pinterestAccount.close();
                finish();
                break;
            default:
                this.finish();
            }
        }
    }
}

From source file:org.botlibre.sdk.SDKConnection.java

public Element parse(String xml) {
    if (this.debug) {
        System.out.println(xml);// ww  w.  j  a va2 s.co  m
    }
    Document dom = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        InputSource source = new InputSource();
        source.setCharacterStream(new StringReader(xml));
        dom = builder.parse(source);
        return dom.getDocumentElement();
    } catch (Exception exception) {
        if (this.debug) {
            exception.printStackTrace();
        }
        this.exception = new SDKException(exception.getMessage(), exception);
        throw this.exception;
    }
}

From source file:org.apache.hadoop.yarn.client.cli.LogsCLI.java

private String[] getContainerLogFiles(Configuration conf, String containerIdStr, String nodeHttpAddress)
        throws IOException {
    List<String> logFiles = new ArrayList<>();
    Client webServiceClient = Client.create();
    try {/*from   w ww  .  j ava  2  s.c  o m*/
        WebResource webResource = webServiceClient
                .resource(WebAppUtils.getHttpSchemePrefix(conf) + nodeHttpAddress);
        ClientResponse response = webResource.path("ws").path("v1").path("node").path("containers")
                .path(containerIdStr).accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
        if (response.getClientResponseStatus().equals(ClientResponse.Status.OK)) {
            try {
                String xml = response.getEntity(String.class);
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                Document dom = db.parse(is);
                NodeList elements = dom.getElementsByTagName("containerLogFiles");
                for (int i = 0; i < elements.getLength(); i++) {
                    logFiles.add(elements.item(i).getTextContent());
                }
            } catch (Exception e) {
                System.out.println("Unable to parse xml from webservice. Error:");
                System.out.println(e.getMessage());
                throw new IOException(e);
            }
        }

    } catch (ClientHandlerException | UniformInterfaceException ex) {
        System.out.println("Unable to fetch log files list");
        throw new IOException(ex);
    }
    return logFiles.toArray(new String[0]);
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.TestRMWebServices.java

public void verifyClusterInfoXML(String xml) throws JSONException, Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);/*w w w.j  av  a  2 s  .  c o m*/
    NodeList nodes = dom.getElementsByTagName("clusterInfo");
    assertEquals("incorrect number of elements", 1, nodes.getLength());

    for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);

        verifyClusterGeneric(WebServicesTestUtils.getXmlLong(element, "id"),
                WebServicesTestUtils.getXmlLong(element, "startedOn"),
                WebServicesTestUtils.getXmlString(element, "state"),
                WebServicesTestUtils.getXmlString(element, "haState"),
                WebServicesTestUtils.getXmlString(element, "haZooKeeperConnectionState"),
                WebServicesTestUtils.getXmlString(element, "hadoopVersionBuiltOn"),
                WebServicesTestUtils.getXmlString(element, "hadoopBuildVersion"),
                WebServicesTestUtils.getXmlString(element, "hadoopVersion"),
                WebServicesTestUtils.getXmlString(element, "resourceManagerVersionBuiltOn"),
                WebServicesTestUtils.getXmlString(element, "resourceManagerBuildVersion"),
                WebServicesTestUtils.getXmlString(element, "resourceManagerVersion"));
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.TestRMWebServices.java

public void verifyClusterMetricsXML(String xml) throws JSONException, Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);/*w  w w  .ja  v  a2  s .  c  om*/
    NodeList nodes = dom.getElementsByTagName("clusterMetrics");
    assertEquals("incorrect number of elements", 1, nodes.getLength());

    for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);

        verifyClusterMetrics(WebServicesTestUtils.getXmlInt(element, "appsSubmitted"),
                WebServicesTestUtils.getXmlInt(element, "appsCompleted"),
                WebServicesTestUtils.getXmlInt(element, "reservedMB"),
                WebServicesTestUtils.getXmlInt(element, "availableMB"),
                WebServicesTestUtils.getXmlInt(element, "allocatedMB"),
                WebServicesTestUtils.getXmlInt(element, "reservedVirtualCores"),
                WebServicesTestUtils.getXmlInt(element, "availableVirtualCores"),
                WebServicesTestUtils.getXmlInt(element, "allocatedVirtualCores"),
                WebServicesTestUtils.getXmlInt(element, "totalVirtualCores"),
                WebServicesTestUtils.getXmlInt(element, "reservedGPUs"),
                WebServicesTestUtils.getXmlInt(element, "availableGPUs"),
                WebServicesTestUtils.getXmlInt(element, "allocatedGPUs"),
                WebServicesTestUtils.getXmlInt(element, "totalGPUs"),
                WebServicesTestUtils.getXmlInt(element, "containersAllocated"),
                WebServicesTestUtils.getXmlInt(element, "totalMB"),
                WebServicesTestUtils.getXmlInt(element, "totalNodes"),
                WebServicesTestUtils.getXmlInt(element, "lostNodes"),
                WebServicesTestUtils.getXmlInt(element, "unhealthyNodes"),
                WebServicesTestUtils.getXmlInt(element, "decommissionedNodes"),
                WebServicesTestUtils.getXmlInt(element, "rebootedNodes"),
                WebServicesTestUtils.getXmlInt(element, "activeNodes"),
                WebServicesTestUtils.getXmlInt(element, "shutdownNodes"));
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.TestRMWebServices.java

public void verifySchedulerFifoXML(String xml) throws JSONException, Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);//www.ja va2s. co  m
    NodeList nodesSched = dom.getElementsByTagName("scheduler");
    assertEquals("incorrect number of elements", 1, nodesSched.getLength());
    NodeList nodes = dom.getElementsByTagName("schedulerInfo");
    assertEquals("incorrect number of elements", 1, nodes.getLength());

    for (int i = 0; i < nodes.getLength(); i++) {
        Element element = (Element) nodes.item(i);

        verifyClusterSchedulerFifoGeneric(WebServicesTestUtils.getXmlAttrString(element, "xsi:type"),
                WebServicesTestUtils.getXmlString(element, "qstate"),
                WebServicesTestUtils.getXmlFloat(element, "capacity"),
                WebServicesTestUtils.getXmlFloat(element, "usedCapacity"),
                WebServicesTestUtils.getXmlInt(element, "minQueueMemoryCapacity"),
                WebServicesTestUtils.getXmlInt(element, "maxQueueMemoryCapacity"),
                WebServicesTestUtils.getXmlInt(element, "numNodes"),
                WebServicesTestUtils.getXmlInt(element, "usedNodeCapacity"),
                WebServicesTestUtils.getXmlInt(element, "availNodeCapacity"),
                WebServicesTestUtils.getXmlInt(element, "totalNodeCapacity"),
                WebServicesTestUtils.getXmlInt(element, "numContainers"));
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.TestRMWebServicesAppsModification.java

protected static void verifyAppStateXML(ClientResponse response, RMAppState... appStates)
        throws ParserConfigurationException, IOException, SAXException {
    assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
    String xml = response.getEntity(String.class);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource is = new InputSource();
    is.setCharacterStream(new StringReader(xml));
    Document dom = db.parse(is);/*from  w w  w  .  ja v a  2 s.c o m*/
    NodeList nodes = dom.getElementsByTagName("appstate");
    assertEquals("incorrect number of elements", 1, nodes.getLength());
    Element element = (Element) nodes.item(0);
    String state = WebServicesTestUtils.getXmlString(element, "state");
    boolean valid = false;
    for (RMAppState appState : appStates) {
        if (appState.toString().equals(state)) {
            valid = true;
        }
    }
    String msg = "app state incorrect, got " + state;
    assertTrue(msg, valid);
}