ca.zadrox.dota2esportticker.util.TeamDetailLoader.java Source code

Java tutorial

Introduction

Here is the source code for ca.zadrox.dota2esportticker.util.TeamDetailLoader.java

Source

/*
 * Copyright 2014 Nicholas Liu
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ca.zadrox.dota2esportticker.util;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.support.v7.graphics.Palette;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.picasso.Picasso;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

import ca.zadrox.dota2esportticker.data.http.team.model.Achievement;
import ca.zadrox.dota2esportticker.data.http.team.model.Player;
import ca.zadrox.dota2esportticker.data.http.team.model.Ranking;
import ca.zadrox.dota2esportticker.data.http.team.model.SocialMedia;
import ca.zadrox.dota2esportticker.data.http.team.model.Statistic;
import ca.zadrox.dota2esportticker.data.http.team.model.Team;

/**
 * Created by Acco on 12/9/2014.
 */
public class TeamDetailLoader extends AsyncTaskLoader<Team> {

    private static final String BASE_URL = "http://www.gosugamers.net";
    private final String TAG = TeamDetailLoader.class.getSimpleName();

    Team mTeam;
    String mUrl;

    public TeamDetailLoader(Context context, String url) {
        super(context);
        mUrl = url;
    }

    @Override
    protected void onStopLoading() {

        cancelLoad();

    }

    @Override
    public void deliverResult(Team data) {
        if (isReset()) {

            if (mTeam != null) {
                onReleaseResources(mTeam);
            }
        }

        super.deliverResult(data);
    }

    @Override
    protected void onReset() {
        super.onReset();

        onStopLoading();

        if (mTeam != null) {
            onReleaseResources(mTeam);
            mTeam = null;
        }
    }

    @Override
    public void onCanceled(Team data) {
        super.onCanceled(data);

        onReleaseResources(data);
    }

    @Override
    protected void onStartLoading() {
        if (mTeam != null) {
            deliverResult(mTeam);
        } else {
            forceLoad();
        }
    }

    @Override
    public Team loadInBackground() {

        if (mTeam == null) {
            mTeam = new Team();
        }

        String rawHtml;

        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            rawHtml = okHttpClient.newCall(new Request.Builder().url(mUrl).build()).execute().body().string();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        // teamCountry + socialMedia + logo + name

        int start = rawHtml.indexOf("<div class=\"titleTeamHolderGG\">");
        int end = rawHtml.indexOf("<div class=\"teamInfoHolder\">");

        String sec = rawHtml.substring(start, end);

        Document doc = Jsoup.parse(sec);

        mTeam.name = doc.getElementsByTag("h1").first().text();
        mTeam.name = mTeam.name.substring(0, mTeam.name.indexOf(" - Team Overview"));
        mTeam.name = mTeam.name.replaceAll(" ?\\.?\\-?-?Dot[aA][\\s]?2", "");

        String logoUrl = doc.getElementsByClass("teamImage").attr("style");
        logoUrl = BASE_URL + logoUrl.substring(logoUrl.indexOf("/uploads"), logoUrl.length() - 2);

        try {

            mTeam.logo = Picasso.with(getContext()).load(logoUrl).get();

            mTeam.palette = Palette.generate(mTeam.logo);

        } catch (IOException e) {
            LogUtils.LOGD(TAG, "Did not generate palette");
            e.printStackTrace();
        }

        mTeam.country = doc.getElementsByClass("flag").first().attr("title");

        ArrayList<SocialMedia> socialMedia = new ArrayList<>();

        for (Element element : doc.getElementsByClass("social").first().getElementsByTag("a")) {
            SocialMedia temp = new SocialMedia();
            temp.socialUrl = element.attr("href");
            temp.socialType = element.child(0).attr("title");
            socialMedia.add(temp);
        }

        mTeam.socialMedia = socialMedia.toArray(new SocialMedia[socialMedia.size()]);

        // teamRankings

        start = rawHtml.indexOf("<div class=\"teamInfoHolder\">", end);
        end = rawHtml.indexOf("<div class=\"statistics\">", start);

        if (!(start == -1 || end == -1)) {

            sec = rawHtml.substring(start, end);

            doc = Jsoup.parse(sec);

            ArrayList<Ranking> teamRankings = new ArrayList<>();

            for (Element element : doc.getElementsByClass("ranking")) {
                Ranking temp = new Ranking();
                temp.ranking = element.getElementsByClass("number").first().text();
                temp.region = element.getElementsByClass("region").first().text();
                teamRankings.add(temp);
            }

            mTeam.rankings = teamRankings.toArray(new Ranking[teamRankings.size()]);

        }

        // teamStatistics + currentStreak

        start = rawHtml.indexOf("<div class=\"statistics\">", end);
        end = rawHtml.indexOf("<div class=\"roster clearfix\">", start);

        if (!(start == -1 || end == -1)) {

            sec = rawHtml.substring(start, end);

            doc = Jsoup.parse(sec);

            ArrayList<Statistic> teamStatistics = new ArrayList<>();

            Elements tableSections = doc.getElementsByTag("tr");
            // these start from 1.
            Elements timeframes = tableSections.get(0).getElementsByTag("th");
            Elements winrates = tableSections.get(1).getElementsByTag("td");
            Elements matchesPlayed = tableSections.get(2).getElementsByTag("td");

            for (int i = 0; i < 3; i++) {
                Statistic temp = new Statistic();
                temp.timeFrame = timeframes.get(i + 1).text();
                temp.winPercentage = winrates.get(i).text();
                Elements scores = matchesPlayed.get(i).getElementsByTag("span");
                temp.wonMatches = scores.get(0).text();
                temp.tiedMatches = scores.get(1).text();
                temp.lostMatches = scores.get(2).text();

                teamStatistics.add(temp);
            }

            mTeam.statistics = teamStatistics.toArray(new Statistic[teamStatistics.size()]);
            mTeam.currentStreak = tableSections.get(3).getElementsByTag("td").text();

        }

        // Roster

        start = rawHtml.indexOf("<div class=\"roster clearfix\">", end);
        end = rawHtml.indexOf("<div class=\"performance\">", start);

        if (!(start == -1 || end == -1)) {

            sec = rawHtml.substring(start, end);

            doc = Jsoup.parse(sec);

            ArrayList<Player> teamRoster = new ArrayList<>();
            String ggUrlPrefix = "http://www.gosugamers.net/dota2/";

            Elements players = doc.getElementsByTag("a");

            for (Element player : players) {
                Player temp = new Player();
                temp.profileUrl = ggUrlPrefix + player.attr("href");
                String unprocessedProfPic = player.getElementsByClass("image").attr("style");
                temp.profilePicUrl = BASE_URL + unprocessedProfPic.substring(unprocessedProfPic.indexOf("/uploads"),
                        unprocessedProfPic.length() - 3);
                temp.country = player.getElementsByTag("span").first().attr("title");
                temp.gameAlias = player.getElementsByTag("h5").first().text();
                temp.realName = player.getElementsByTag("span").get(1).text();

                if (!player.getElementsByClass("heroes").first().text().contains("Manager")) {
                    teamRoster.add(temp);
                }
            }

            mTeam.roster = teamRoster.toArray(new Player[teamRoster.size()]);

        }

        // Upcoming Matches

        start = rawHtml.indexOf("<table id=\"gb-matches\" class=\"simple gamelist clearbottom\">", end);
        end = rawHtml.indexOf("<div id=\"box-ad\" class=\"ad\">", start) - 12;

        if (!(start == -1 || end == -1)) {

            sec = rawHtml.substring(start, end);

            doc = Jsoup.parse(sec);

            ArrayList<String> upcomingMatchUrls = new ArrayList<>();

            Elements upcomingMatches = doc.getElementsByTag("a");

            for (Element uMatch : upcomingMatches) {
                upcomingMatchUrls.add(BASE_URL + uMatch.attr("href"));
            }

            mTeam.upcomingMatches = upcomingMatchUrls.toArray(new String[upcomingMatchUrls.size()]);

            // Recent Matches

            start = rawHtml.indexOf("<div class=\"graph-wrap\">", end);
            end = rawHtml.indexOf("<div id=\"box-ad\" class=\"ad\">", start);

            sec = rawHtml.substring(start, end);

            doc = Jsoup.parse(sec);

            ArrayList<String> recentMatchUrls = new ArrayList<>();

            Elements recentMatches = doc.getElementsByClass("match-list-row");

            for (Element rMatch : recentMatches) {
                recentMatchUrls.add(BASE_URL + rMatch.getElementsByTag("a").first().attr("href"));
            }

            mTeam.recentMatches = recentMatchUrls.toArray(new String[recentMatchUrls.size()]);

        }

        // Achievements

        start = rawHtml.indexOf("<div class=\"content\">", end);
        end = rawHtml.indexOf("<div id=\"lower-lb-ad\">", start);

        if (!(start == -1 || end == -1)) {

            sec = rawHtml.substring(start, end);
            //sec = sec.replace("<br/>", " : ");

            doc = Jsoup.parse(sec);

            Elements achievements = doc.getElementsByTag("p");

            ArrayList<Achievement> achieveList = new ArrayList<>();

            for (int i = 0; i < achievements.size(); i++) {
                Element achievementBlock = achievements.get(i);
                String check = achievementBlock.text().substring(0,
                        achievementBlock.text().length() >= 12 ? 12 : 0);

                if (check.equals("Achievements")) {
                    i++;
                    String[] mEvents = achievements.get(i).html().split("<br>");

                    for (String event : mEvents) {
                        Achievement temp = new Achievement();
                        Document document = Jsoup.parse(event);

                        temp.place = document.getElementsByTag("body").first().child(0).text();
                        temp.place = temp.place.replaceAll("(\\s?-\\s?$)|(\\s$)", "");

                        try {
                            Element tournamentInfo = document.getElementsByTag("a").first();
                            temp.tournament = tournamentInfo.text();
                            temp.tournamentUrl = tournamentInfo.attr("href");
                        } catch (NullPointerException e) {
                            LogUtils.LOGD(TAG, "No <a>, fallback method");
                        }

                        if (temp.tournament == null) {
                            temp.tournament = document.getElementsByTag("body").first().textNodes().get(0).text();
                            temp.tournament = temp.tournament.replaceAll("(^\\s?-\\s?)|(\\s?-\\s?$)|(\\s$)", "");
                        }

                        temp.year = document.getElementsByTag("em").first().text();
                        temp.year = temp.year.substring(temp.year.indexOf('(') + 1, temp.year.indexOf(')'));

                        String text = document.getElementsByTag("body").first().text();
                        int startIndex = text.indexOf(temp.tournament) + temp.tournament.length();
                        //LogUtils.LOGD(TAG, "startIndex: " + startIndex);
                        int endIndex = text.indexOf("- ", startIndex);
                        if (endIndex == -1) {
                            temp.prizeReward = "No Reward";
                        } else {
                            temp.prizeReward = text.substring(endIndex + 2);
                        }

                        achieveList.add(temp);
                    }
                }
            }

            mTeam.achievements = achieveList.toArray(new Achievement[achieveList.size()]);
        }

        return mTeam;
    }

    protected void onReleaseResources(Team team) {
        // For a simple List<> there is nothing to do.  For something
        // like a Cursor, we would close it here.
    }
}