Запрос календаря Google возвращает не более 25 записей - PullRequest
4 голосов
/ 15 апреля 2010

Я пытаюсь удалить все записи календаря с сегодняшнего дня вперед. Я запускаю запрос, затем вызываю getEntries () для результата запроса. getEntries () всегда возвращает 25 записей (или меньше, если в календаре менее 25 записей). Почему не все записи возвращены? Я ожидаю около 80 записей.

В качестве теста я попытался выполнить запрос, удалить возвращенные 25 записей, выполнить запрос еще раз, удалить снова и т. Д. Это работает, но должен быть лучший способ.

Ниже приведен код Java, который выполняет запрос только один раз.

CalendarQuery myQuery = new CalendarQuery(feedUrl);

DateFormat dfGoogle = new SimpleDateFormat("yyyy-MM-dd'T00:00:00'");
Date dt = Calendar.getInstance().getTime();

myQuery.setMinimumStartTime(DateTime.parseDateTime(dfGoogle.format(dt)));
// Make the end time far into the future so we delete everything
myQuery.setMaximumStartTime(DateTime.parseDateTime("2099-12-31T23:59:59"));

// Execute the query and get the response
CalendarEventFeed resultFeed = service.query(myQuery, CalendarEventFeed.class);

// !!! This returns 25 (or less if there are fewer than 25 entries on the calendar) !!!
int test = resultFeed.getEntries().size();

// Delete all the entries returned by the query
for (int j = 0; j < resultFeed.getEntries().size(); j++) {
   CalendarEventEntry entry = resultFeed.getEntries().get(j);

   entry.delete();
}

PS: я смотрел Руководство разработчика API данных и Google Data API Javadoc . Эти сайты в порядке, но не велики. Кто-нибудь знает о дополнительной документации Google API?

Ответы [ 5 ]

9 голосов
/ 15 апреля 2010

Вы можете увеличить количество результатов с myQuery.setMaxResults(). Тем не менее, будет максимальный максимум, поэтому вы можете сделать несколько запросов («постраничных» результатов), изменяя myQuery.setStartIndex().

http://code.google.com/apis/gdata/javadoc/com/google/gdata/client/Query.html#setMaxResults(int) http://code.google.com/apis/gdata/javadoc/com/google/gdata/client/Query.html#setStartIndex(int)

3 голосов
/ 20 апреля 2010

Основываясь на ответах Джима Блэклера и Криса Камински, я улучшил свой код, чтобы прочитать результаты запроса на страницах. Я также выполняю удаление как пакет, который должен выполняться быстрее, чем отдельные удаления.

Я предоставляю здесь код Java на тот случай, если он кому-нибудь пригодится.

CalendarQuery myQuery = new CalendarQuery(feedUrl);

DateFormat dfGoogle = new SimpleDateFormat("yyyy-MM-dd'T00:00:00'"); 
Date dt = Calendar.getInstance().getTime(); 

myQuery.setMinimumStartTime(DateTime.parseDateTime(dfGoogle.format(dt))); 
// Make the end time far into the future so we delete everything 
myQuery.setMaximumStartTime(DateTime.parseDateTime("2099-12-31T23:59:59")); 

// Set the maximum number of results to return for the query.
// Note: A GData server may choose to provide fewer results, but will never provide
// more than the requested maximum.
myQuery.setMaxResults(5000);
int startIndex = 1;
int entriesReturned;

List<CalendarEventEntry> allCalEntries = new ArrayList<CalendarEventEntry>();
CalendarEventFeed resultFeed;

// Run our query as many times as necessary to get all the
// Google calendar entries we want
while (true) {
    myQuery.setStartIndex(startIndex);

    // Execute the query and get the response
    resultFeed = service.query(myQuery, CalendarEventFeed.class);

    entriesReturned = resultFeed.getEntries().size();
    if (entriesReturned == 0)
        // We've hit the end of the list
        break;

    // Add the returned entries to our local list
    allCalEntries.addAll(resultFeed.getEntries());

    startIndex = startIndex + entriesReturned;
}

// Delete all the entries as a batch delete
CalendarEventFeed batchRequest = new CalendarEventFeed();

for (int i = 0; i < allCalEntries.size(); i++) {
    CalendarEventEntry entry = allCalEntries.get(i);

    BatchUtils.setBatchId(entry, Integer.toString(i));
    BatchUtils.setBatchOperationType(entry, BatchOperationType.DELETE);
    batchRequest.getEntries().add(entry);
}

// Get the batch link URL and send the batch request
Link batchLink = resultFeed.getLink(Link.Rel.FEED_BATCH, Link.Type.ATOM);
CalendarEventFeed batchResponse = service.batch(new URL(batchLink.getHref()), batchRequest);

// Ensure that all the operations were successful
boolean isSuccess = true;
StringBuffer batchFailureMsg = new StringBuffer("These entries in the batch delete failed:");
for (CalendarEventEntry entry : batchResponse.getEntries()) {
    String batchId = BatchUtils.getBatchId(entry);
    if (!BatchUtils.isSuccess(entry)) {
        isSuccess = false;
        BatchStatus status = BatchUtils.getBatchStatus(entry);
        batchFailureMsg.append("\nID: " + batchId + "  Reason: " + status.getReason());
    }
}

if (!isSuccess) {
    throw new Exception(batchFailureMsg.toString());
}
2 голосов
/ 03 сентября 2010

На странице API есть небольшая цитата http://code.google.com/apis/calendar/data/1.0/reference.html#Parameters

Примечание. Параметр запроса max-results для календаря по умолчанию равен 25, так что вы не получите всего Календарь подаётся случайно. Если ты хочешь чтобы получить весь канал, вы можете указать очень большое число для макс-результаты.

Итак, чтобы получить все события из фида календаря Google, мы делаем это:

google.calendarurl.com/.../basic?max-results=999999

в API вы также можете запросить с помощью setMaxResults = 999999

1 голос
/ 12 августа 2011

Я попал сюда во время поиска решения Python; Если кто-то застрянет таким же образом, важная строка будет четвертой:

query = gdata.calendar.service.CalendarEventQuery(cal, visibility, projection)
query.start_min = start_date
query.start_max = end_date 
query.max_results = 1000
0 голосов
/ 15 апреля 2010

К сожалению, Google собирается ограничить максимальное количество запросов, которое вы можете получить. Это сделано для того, чтобы держать регулятор запросов в их правилах (например, HTTP-запросы не могут занимать более 30 секунд). Они построили всю свою архитектуру вокруг этого, так что вы можете также построить логику, как у вас.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...