Search in sources :

Example 21 with Event

use of com.thebluealliance.androidclient.models.Event in project the-blue-alliance-android by the-blue-alliance.

the class EventHelper method renderEventListWithComparator.

private static void renderEventListWithComparator(Context context, List<Event> events, List<Object> output, Comparator<Event> comparator) {
    Collections.sort(events, comparator);
    EventType lastType = null, currentType;
    String lastDistrict = "", currentDistrict;
    for (Event event : events) {
        currentType = event.getEventTypeEnum();
        currentDistrict = event.getDistrictKey() != null ? event.getDistrictKey() : "";
        if (currentType != lastType || (currentType == EventType.DISTRICT && !currentDistrict.equals(lastDistrict))) {
            String headerTitle;
            if (currentType == EventType.DISTRICT) {
                headerTitle = context.getString(R.string.district_events_header, event.getEventDistrictString());
            } else {
                headerTitle = context.getString(currentType.getCategoryName());
            }
            output.add(new ListSectionHeaderViewModel(headerTitle));
        }
        output.add(event.renderToViewModel(context, Event.RENDER_BASIC));
        if (event.isHappeningNow()) {
            // send out that there are live matches happening for other things to pick up
            TbaLogger.d("Sending live event broadcast: " + event.getKey());
            EventBus.getDefault().post(new LiveEventUpdateEvent(event));
        }
        lastType = currentType;
        lastDistrict = currentDistrict;
    }
}
Also used : EventType(com.thebluealliance.androidclient.types.EventType) ListSectionHeaderViewModel(com.thebluealliance.androidclient.viewmodels.ListSectionHeaderViewModel) LiveEventUpdateEvent(com.thebluealliance.androidclient.eventbus.LiveEventUpdateEvent) Event(com.thebluealliance.androidclient.models.Event) LiveEventUpdateEvent(com.thebluealliance.androidclient.eventbus.LiveEventUpdateEvent)

Example 22 with Event

use of com.thebluealliance.androidclient.models.Event in project the-blue-alliance-android by the-blue-alliance.

the class EventsTableTest method testUpdate.

@Test
public void testUpdate() {
    Event result = DbTableTestDriver.testUpdate(mTable, mEvents.get(0), event -> event.setName("Test"), mGson);
    assertNotNull(result);
    assertEquals("Test", result.getName());
}
Also used : Event(com.thebluealliance.androidclient.models.Event) Test(org.junit.Test)

Example 23 with Event

use of com.thebluealliance.androidclient.models.Event in project the-blue-alliance-android by the-blue-alliance.

the class EventListWriterTest method testEventListWriter.

@Test
public void testEventListWriter() {
    mWriter.write(mEvents, 0L);
    SQLiteDatabase db = mDb.getWritableDatabase();
    for (Event event : mEvents) {
        verify(db).insert(Database.TABLE_EVENTS, null, event.getParams(mGson));
    }
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Event(com.thebluealliance.androidclient.models.Event) Test(org.junit.Test)

Example 24 with Event

use of com.thebluealliance.androidclient.models.Event in project the-blue-alliance-android by the-blue-alliance.

the class LoadTBADataWorker method doWork.

@NonNull
@Override
public Result doWork() {
    mStartTime = System.currentTimeMillis();
    int[] params = getInputData().getIntArray(DATA_TO_LOAD);
    int[] dataToLoad;
    if (params == null || params.length == 0) {
        dataToLoad = new int[] { LOAD_TEAMS, LOAD_EVENTS, LOAD_DISTRICTS };
    } else {
        dataToLoad = params;
    }
    try {
        /* First, do a blocking update of Remote Config */
        publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_LOADING, mApplicationContext.getString(R.string.loading_config)));
        mAppConfig.updateRemoteDataBlocking();
        Call<ApiStatus> statusCall = mDatafeed.fetchApiStatus();
        Response<ApiStatus> statusResponse = statusCall.execute();
        if (!statusResponse.isSuccessful() || statusResponse.body() == null || statusResponse.body().getMaxSeason() == null) {
            TbaLogger.e("Bad API status response: " + statusResponse);
            return onConnectionError();
        }
        int maxCompYear = statusResponse.body().getMaxSeason();
        List<Team> allTeams = new ArrayList<>();
        int maxPageNum = 0;
        if (Arrays.binarySearch(dataToLoad, LOAD_TEAMS) != -1) {
            mDb.getTeamsTable().deleteAllRows();
            // First we will load all the teams
            for (int pageNum = 0; pageNum < 20; pageNum++) {
                // limit to 20 pages to prevent potential infinite loop
                if (isStopped()) {
                    return Result.failure();
                }
                int start = pageNum * Constants.API_TEAM_LIST_PAGE_SIZE;
                int end = start + Constants.API_TEAM_LIST_PAGE_SIZE - 1;
                start = start == 0 ? 1 : start;
                publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_LOADING, mApplicationContext.getString(R.string.loading_teams, start, end)));
                Call<List<Team>> teamListCall = mDatafeed.fetchTeamPage(pageNum, ApiConstants.TBA_CACHE_WEB);
                Response<List<Team>> teamListResponse = teamListCall.execute();
                if (!teamListResponse.isSuccessful()) {
                    return onConnectionError();
                }
                if (teamListResponse.body() == null || teamListResponse.body().isEmpty()) {
                    // No teams found for a page; we are done
                    break;
                }
                Date lastModified = teamListResponse.headers().getDate("Last-Modified");
                List<Team> responseBody = teamListResponse.body();
                if (lastModified != null) {
                    long lastModifiedTimestamp = lastModified.getTime();
                    for (int i = 0; i < responseBody.size(); i++) {
                        responseBody.get(i).setLastModified(lastModifiedTimestamp);
                    }
                }
                allTeams.addAll(responseBody);
                maxPageNum = Math.max(maxPageNum, pageNum);
            }
        }
        List<Event> allEvents = new ArrayList<>();
        if (Arrays.binarySearch(dataToLoad, LOAD_EVENTS) != -1) {
            mDb.getEventsTable().deleteAllRows();
            // Now we load all events
            for (int year = Constants.FIRST_COMP_YEAR; year <= maxCompYear; year++) {
                if (isStopped()) {
                    return Result.failure();
                }
                publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_LOADING, mApplicationContext.getString(R.string.loading_events, Integer.toString(year))));
                Call<List<Event>> eventListCall = mDatafeed.fetchEventsInYear(year, ApiConstants.TBA_CACHE_WEB);
                Response<List<Event>> eventListResponse = eventListCall.execute();
                if (!eventListResponse.isSuccessful()) {
                    return onConnectionError();
                }
                if (eventListResponse.body() == null) {
                    continue;
                }
                Date lastModified = eventListResponse.headers().getDate("Last-Modified");
                List<Event> responseBody = eventListResponse.body();
                if (lastModified != null) {
                    long lastModifiedTimestamp = lastModified.getTime();
                    for (int i = 0; i < responseBody.size(); i++) {
                        responseBody.get(i).setLastModified(lastModifiedTimestamp);
                    }
                }
                allEvents.addAll(responseBody);
                TbaLogger.i(String.format("Loaded %1$d events in %2$d", eventListResponse.body().size(), year));
            }
        }
        List<District> allDistricts = new ArrayList<>();
        if (Arrays.binarySearch(dataToLoad, LOAD_DISTRICTS) != -1) {
            mDb.getDistrictsTable().deleteAllRows();
            // load all districts
            for (int year = Constants.FIRST_DISTRICT_YEAR; year <= maxCompYear; year++) {
                if (isStopped()) {
                    return Result.failure();
                }
                publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_LOADING, mApplicationContext.getString(R.string.loading_districts, year)));
                AddDistrictKeys keyAdder = new AddDistrictKeys(year);
                Call<List<District>> districtListCall = mDatafeed.fetchDistrictList(year, ApiConstants.TBA_CACHE_WEB);
                Response<List<District>> districtListResponse = districtListCall.execute();
                if (!districtListResponse.isSuccessful() || districtListResponse.body() == null) {
                    return onConnectionError();
                }
                List<District> newDistrictList = districtListResponse.body();
                keyAdder.call(newDistrictList);
                Date lastModified = districtListResponse.headers().getDate("Last-Modified");
                if (lastModified != null) {
                    long lastModifiedTimestamp = lastModified.getTime();
                    for (int i = 0; i < newDistrictList.size(); i++) {
                        newDistrictList.get(i).setLastModified(lastModifiedTimestamp);
                    }
                }
                allDistricts.addAll(newDistrictList);
                TbaLogger.i(String.format("Loaded %1$d districts in %2$d", newDistrictList.size(), year));
            }
        }
        if (isStopped()) {
            return Result.failure();
        }
        // If no exception has been thrown at this point, we have all the data. We can now
        // insert it into the database. Pass a 0 as the last-modified time here, because we set
        // it individually above
        publishProgress(new LoadProgressInfo(LoadProgressInfo.STATE_LOADING, mApplicationContext.getString(R.string.loading_almost_finished)));
        TbaLogger.i("Writing " + allTeams.size() + " teams");
        mTeamWriter.write(allTeams, 0L);
        TbaLogger.i("Writing " + allEvents.size() + " events");
        mEventWriter.write(allEvents, 0L);
        TbaLogger.i("Writing " + allDistricts.size() + " districts");
        mDistrictWriter.write(allDistricts, 0L);
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        // Write TBA Status
        editor.putString(TBAStatusController.STATUS_PREF_KEY, statusResponse.body().getJsonBlob());
        editor.putInt(Constants.LAST_YEAR_KEY, statusResponse.body().getMaxSeason());
        // Loop through all pages
        for (int pageNum = 0; pageNum <= maxPageNum; pageNum++) {
            editor.putBoolean(Database.ALL_TEAMS_LOADED_TO_DATABASE_FOR_PAGE + pageNum, true);
        }
        // Loop through all years
        for (int year = Constants.FIRST_COMP_YEAR; year <= maxCompYear; year++) {
            editor.putBoolean(Database.ALL_EVENTS_LOADED_TO_DATABASE_FOR_YEAR + year, true);
        }
        // Loop through years for districts
        for (int year = Constants.FIRST_DISTRICT_YEAR; year <= maxCompYear; year++) {
            editor.putBoolean(Database.ALL_DISTRICTS_LOADED_TO_DATABASE_FOR_YEAR + year, true);
        }
        editor.putInt(Constants.APP_VERSION_KEY, BuildConfig.VERSION_CODE);
        editor.apply();
        AnalyticsHelper.sendTimingUpdate(mApplicationContext, System.currentTimeMillis() - mStartTime, "load all data", "");
        return Result.success(new LoadProgressInfo(LoadProgressInfo.STATE_FINISHED, mApplicationContext.getString(R.string.loading_finished)).toData());
    } catch (RuntimeException ex) {
        // This is bad, probably an error in the response from the server
        TbaLogger.e("Error loading initial data", ex);
        return onFailure(new LoadProgressInfo(LoadProgressInfo.STATE_ERROR, Utilities.exceptionStacktraceToString(ex)));
    } catch (IOException | InterruptedException | ExecutionException e) {
        /* Some sort of network error */
        TbaLogger.e("Error loading initial data", e);
        return onConnectionError();
    }
}
Also used : ApiStatus(com.thebluealliance.androidclient.models.ApiStatus) ArrayList(java.util.ArrayList) Team(com.thebluealliance.androidclient.models.Team) ArrayList(java.util.ArrayList) List(java.util.List) ExecutionException(java.util.concurrent.ExecutionException) SharedPreferences(android.content.SharedPreferences) IOException(java.io.IOException) AddDistrictKeys(com.thebluealliance.androidclient.datafeed.maps.AddDistrictKeys) Date(java.util.Date) Event(com.thebluealliance.androidclient.models.Event) District(com.thebluealliance.androidclient.models.District) NonNull(androidx.annotation.NonNull)

Example 25 with Event

use of com.thebluealliance.androidclient.models.Event in project the-blue-alliance-android by the-blue-alliance.

the class EventHelperTest method testGetLabelForEvent.

@Test
public void testGetLabelForEvent() {
    Event noType = mockEventType(EventType.NONE);
    assertEquals(EventHelper.generateLabelForEvent(noType), EventHelper.WEEKLESS_LABEL);
    Event preseason = mockEventType(EventType.PRESEASON);
    assertEquals(EventHelper.generateLabelForEvent(preseason), EventHelper.PRESEASON_LABEL);
    Event offseason = mockEventType(EventType.OFFSEASON);
    when(offseason.getFormattedStartDate()).thenReturn(new Date(115, 4, 2));
    assertEquals(EventHelper.generateLabelForEvent(offseason), "May Offseason Events");
    Event cmpDivision = mockEventType(EventType.CMP_DIVISION);
    assertEquals(EventHelper.generateLabelForEvent(cmpDivision), EventHelper.CHAMPIONSHIP_LABEL);
    Event cmpFinals = mockEventType(EventType.CMP_FINALS);
    assertEquals(EventHelper.generateLabelForEvent(cmpFinals), EventHelper.CHAMPIONSHIP_LABEL);
    Event regional = mockRegularEvent(EventType.REGIONAL, 2015, 5);
    assertEquals(EventHelper.generateLabelForEvent(regional), "Week 5");
    Event district = mockRegularEvent(EventType.DISTRICT, 2015, 2);
    assertEquals(EventHelper.generateLabelForEvent(district), "Week 2");
    Event districtCmp = mockRegularEvent(EventType.DISTRICT_CMP, 2012, 1);
    assertEquals(EventHelper.generateLabelForEvent(districtCmp), "Week 1");
    /* Special cases for 2016 events & Week 0.5 */
    Event scmb = ModelMaker.getModel(Event.class, "2016scmb");
    assertEquals(EventHelper.generateLabelForEvent(scmb), "Week 0.5");
    Event regional2016 = mockRegularEvent(EventType.REGIONAL, 2016, 2);
    assertEquals(EventHelper.generateLabelForEvent(regional2016), "Week 1");
    Event district2016 = mockRegularEvent(EventType.DISTRICT, 2016, 4);
    assertEquals(EventHelper.generateLabelForEvent(district2016), "Week 3");
    Event districtCmp2016 = mockRegularEvent(EventType.DISTRICT_CMP, 2016, 7);
    assertEquals(EventHelper.generateLabelForEvent(districtCmp2016), "Week 6");
}
Also used : Event(com.thebluealliance.androidclient.models.Event) Date(java.util.Date) Test(org.junit.Test)

Aggregations

Event (com.thebluealliance.androidclient.models.Event)35 Test (org.junit.Test)8 Team (com.thebluealliance.androidclient.models.Team)6 ArrayList (java.util.ArrayList)5 District (com.thebluealliance.androidclient.models.District)4 Date (java.util.Date)4 JsonObject (com.google.gson.JsonObject)3 TeamAvatarUpdateEvent (com.thebluealliance.androidclient.eventbus.TeamAvatarUpdateEvent)3 Match (com.thebluealliance.androidclient.models.Match)3 EventRenderer (com.thebluealliance.androidclient.renderers.EventRenderer)3 Before (org.junit.Before)3 Cursor (android.database.Cursor)2 Nullable (androidx.annotation.Nullable)2 WorkerThread (androidx.annotation.WorkerThread)2 JsonElement (com.google.gson.JsonElement)2 MatchSortByPlayOrderComparator (com.thebluealliance.androidclient.comparators.MatchSortByPlayOrderComparator)2 EventMatchesEvent (com.thebluealliance.androidclient.eventbus.EventMatchesEvent)2 LiveEventUpdateEvent (com.thebluealliance.androidclient.eventbus.LiveEventUpdateEvent)2 ListGroup (com.thebluealliance.androidclient.listitems.ListGroup)2 DistrictPointBreakdown (com.thebluealliance.androidclient.models.DistrictPointBreakdown)2