Search in sources :

Example 1 with Calendar

use of com.google.api.services.calendar.Calendar in project openhab1-addons by openhab.

the class GCalGoogleOAuth method getCalendarId.

/**
     * Return calendarID based on calendar name.
     * if calendar name is "primary" not check primary - just return primary
     *
     * @param calendar object
     */
public static CalendarListEntry getCalendarId(String calendar_name) {
    CalendarListEntry calendarID = null;
    if (calendarList == null) {
        Calendar client = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredential(false)).setApplicationName("openHAB").build();
        try {
            calendarList = client.calendarList().list().execute();
        } catch (com.google.api.client.auth.oauth2.TokenResponseException ae) {
            logger.error("authentication failed: {}", ae.getMessage());
            return null;
        } catch (IOException e1) {
            logger.error("authentication I/O exception: {}", e1.getMessage());
            return null;
        }
    }
    if (calendarList != null && calendarList.getItems() != null) {
        for (CalendarListEntry entry : calendarList.getItems()) {
            if ((entry.getSummary().equals(calendar_name)) || (calendar_name.equals("primary")) && entry.isPrimary()) {
                calendarID = entry;
                logger.debug("Got calendar {} CalendarID: {}", calendar_name, calendarID.getId());
            }
        }
    }
    if (calendarID == null) {
        logger.warn("Calendar {} not found", calendar_name);
    }
    return calendarID;
}
Also used : CalendarListEntry(com.google.api.services.calendar.model.CalendarListEntry) Calendar(com.google.api.services.calendar.Calendar) IOException(java.io.IOException)

Example 2 with Calendar

use of com.google.api.services.calendar.Calendar in project data-transfer-project by google.

the class GoogleCalendarExporterTest method exportCalendarFirstSet.

@Test
public void exportCalendarFirstSet() throws IOException {
    setUpSingleCalendarResponse();
    // Looking at first page, with at least one page after it
    calendarListResponse.setNextPageToken(NEXT_TOKEN);
    // Run test
    ExportResult<CalendarContainerResource> result = googleCalendarExporter.export(JOB_ID, null);
    // Check results
    // Verify correct methods were called
    verify(calendarClient).calendarList();
    verify(calendarCalendarList).list();
    verify(calendarListRequest).execute();
    // Check pagination token
    ContinuationData continuationData = (ContinuationData) result.getContinuationData();
    StringPaginationToken paginationToken = (StringPaginationToken) continuationData.getPaginationData();
    assertThat(paginationToken.getToken()).isEqualTo(CALENDAR_TOKEN_PREFIX + NEXT_TOKEN);
    // Check calendars
    Collection<CalendarModel> actualCalendars = result.getExportedData().getCalendars();
    assertThat(actualCalendars.stream().map(CalendarModel::getId).collect(Collectors.toList())).containsExactly(CALENDAR_ID);
    // Check events (should be empty, even though there is an event in the calendar
    Collection<CalendarEventModel> actualEvents = result.getExportedData().getEvents();
    assertThat(actualEvents).isEmpty();
    // Should be one container in the resource list
    List<ContainerResource> actualResources = continuationData.getContainerResources();
    assertThat(actualResources.stream().map(a -> ((IdOnlyContainerResource) a).getId()).collect(Collectors.toList())).containsExactly(CALENDAR_ID);
}
Also used : IdOnlyContainerResource(org.dataportabilityproject.spi.transfer.types.IdOnlyContainerResource) ExportResult(org.dataportabilityproject.spi.transfer.provider.ExportResult) CalendarContainerResource(org.dataportabilityproject.types.transfer.models.calendar.CalendarContainerResource) Events(com.google.api.services.calendar.model.Events) ContinuationData(org.dataportabilityproject.spi.transfer.types.ContinuationData) Calendar(com.google.api.services.calendar.Calendar) PaginationData(org.dataportabilityproject.spi.transfer.types.PaginationData) Before(org.junit.Before) Event(com.google.api.services.calendar.model.Event) ExportInformation(org.dataportabilityproject.spi.transfer.types.ExportInformation) StringPaginationToken(org.dataportabilityproject.spi.transfer.types.StringPaginationToken) InOrder(org.mockito.InOrder) EVENT_TOKEN_PREFIX(org.dataportabilityproject.datatransfer.google.common.GoogleStaticObjects.EVENT_TOKEN_PREFIX) CalendarList(com.google.api.services.calendar.model.CalendarList) Collection(java.util.Collection) Test(org.junit.Test) IOException(java.io.IOException) MAX_ATTENDEES(org.dataportabilityproject.datatransfer.google.common.GoogleStaticObjects.MAX_ATTENDEES) UUID(java.util.UUID) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Collectors(java.util.stream.Collectors) Mockito.verify(org.mockito.Mockito.verify) Mockito(org.mockito.Mockito) List(java.util.List) CalendarListEntry(com.google.api.services.calendar.model.CalendarListEntry) CALENDAR_TOKEN_PREFIX(org.dataportabilityproject.datatransfer.google.common.GoogleStaticObjects.CALENDAR_TOKEN_PREFIX) CalendarEventModel(org.dataportabilityproject.types.transfer.models.calendar.CalendarEventModel) ContainerResource(org.dataportabilityproject.types.transfer.models.ContainerResource) Collections(java.util.Collections) CalendarModel(org.dataportabilityproject.types.transfer.models.calendar.CalendarModel) Mockito.mock(org.mockito.Mockito.mock) IdOnlyContainerResource(org.dataportabilityproject.spi.transfer.types.IdOnlyContainerResource) CalendarContainerResource(org.dataportabilityproject.types.transfer.models.calendar.CalendarContainerResource) ContainerResource(org.dataportabilityproject.types.transfer.models.ContainerResource) IdOnlyContainerResource(org.dataportabilityproject.spi.transfer.types.IdOnlyContainerResource) CalendarModel(org.dataportabilityproject.types.transfer.models.calendar.CalendarModel) ContinuationData(org.dataportabilityproject.spi.transfer.types.ContinuationData) CalendarEventModel(org.dataportabilityproject.types.transfer.models.calendar.CalendarEventModel) CalendarContainerResource(org.dataportabilityproject.types.transfer.models.calendar.CalendarContainerResource) StringPaginationToken(org.dataportabilityproject.spi.transfer.types.StringPaginationToken) Test(org.junit.Test)

Example 3 with Calendar

use of com.google.api.services.calendar.Calendar in project data-transfer-project by google.

the class GoogleCalendarServiceTest method testExportCalendarFirstSet.

@Test
public void testExportCalendarFirstSet() throws IOException {
    setUpSingleCalendarResponse();
    // Looking at first page, with at least one page after it
    ExportInformation emptyExportInformation = new ExportInformation(Optional.empty(), Optional.empty());
    calendarListResponse.setNextPageToken(NEXT_TOKEN);
    // Run test
    CalendarModelWrapper wrapper = calendarService.export(emptyExportInformation);
    // Check results
    // Verify correct methods were called
    verify(calendarClient).calendarList();
    verify(calendarCalendarList).list();
    verify(calendarListRequest).execute();
    // Check pagination token
    StringPaginationToken paginationToken = (StringPaginationToken) wrapper.getContinuationInformation().getPaginationInformation();
    assertThat(paginationToken.getId()).isEqualTo(NEXT_TOKEN);
    // Check calendars
    Collection<CalendarModel> calendars = wrapper.getCalendars();
    assertThat(calendars.stream().map(CalendarModel::getId).collect(Collectors.toList())).containsExactly(CALENDAR_ID);
    // Check events (should be empty, even though there is an event in the calendar)
    Collection<CalendarEventModel> events = wrapper.getEvents();
    assertThat(events).isEmpty();
    // Should be one event in the resource list
    Collection<? extends Resource> subResources = wrapper.getContinuationInformation().getSubResources();
    assertThat(subResources.stream().map(a -> ((IdOnlyResource) a).getId()).collect(Collectors.toList())).containsExactly(CALENDAR_ID);
}
Also used : CalendarModelWrapper(org.dataportabilityproject.dataModels.calendar.CalendarModelWrapper) Events(com.google.api.services.calendar.model.Events) InMemoryJobDataCache(org.dataportabilityproject.cloud.local.InMemoryJobDataCache) PaginationInformation(org.dataportabilityproject.dataModels.PaginationInformation) JobDataCache(org.dataportabilityproject.cloud.interfaces.JobDataCache) Calendar(com.google.api.services.calendar.Calendar) GoogleStaticObjects(org.dataportabilityproject.serviceProviders.google.GoogleStaticObjects) StringPaginationToken(org.dataportabilityproject.shared.StringPaginationToken) Before(org.junit.Before) Event(com.google.api.services.calendar.model.Event) InOrder(org.mockito.InOrder) Resource(org.dataportabilityproject.dataModels.Resource) ExportInformation(org.dataportabilityproject.dataModels.ExportInformation) CalendarList(com.google.api.services.calendar.model.CalendarList) Collection(java.util.Collection) CalendarModelWrapper(org.dataportabilityproject.dataModels.calendar.CalendarModelWrapper) IOException(java.io.IOException) IdOnlyResource(org.dataportabilityproject.shared.IdOnlyResource) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Collectors(java.util.stream.Collectors) Mockito.verify(org.mockito.Mockito.verify) CalendarEventModel(org.dataportabilityproject.dataModels.calendar.CalendarEventModel) CalendarModel(org.dataportabilityproject.dataModels.calendar.CalendarModel) Mockito(org.mockito.Mockito) CalendarListEntry(com.google.api.services.calendar.model.CalendarListEntry) Optional(java.util.Optional) Collections(java.util.Collections) Mockito.mock(org.mockito.Mockito.mock) ExportInformation(org.dataportabilityproject.dataModels.ExportInformation) CalendarModel(org.dataportabilityproject.dataModels.calendar.CalendarModel) CalendarEventModel(org.dataportabilityproject.dataModels.calendar.CalendarEventModel) IdOnlyResource(org.dataportabilityproject.shared.IdOnlyResource) StringPaginationToken(org.dataportabilityproject.shared.StringPaginationToken) Test(org.junit.Test)

Example 4 with Calendar

use of com.google.api.services.calendar.Calendar in project DisCal-Discord-Bot by NovaFox161.

the class EventListCommand method moduleDay.

@SuppressWarnings("Duplicates")
private void moduleDay(String[] args, MessageReceivedEvent event, GuildSettings settings) {
    if (args.length == 1) {
        // Get the upcoming events in the next 24 hours.
        try {
            Calendar service;
            if (settings.useExternalCalendar()) {
                service = CalendarAuth.getCalendarService(settings);
            } else {
                service = CalendarAuth.getCalendarService();
            }
            DateTime now = new DateTime(System.currentTimeMillis());
            DateTime twentyFourHoursFromNow = new DateTime(now.getValue() + 86400000L);
            CalendarData calendarData = DatabaseManager.getManager().getMainCalendar(event.getGuild().getLongID());
            Events events = service.events().list(calendarData.getCalendarAddress()).setMaxResults(20).setTimeMin(now).setTimeMax(twentyFourHoursFromNow).setOrderBy("startTime").setSingleEvents(true).setShowDeleted(false).execute();
            List<Event> items = events.getItems();
            if (items.size() == 0) {
                Message.sendMessage(MessageManager.getMessage("Event.List.Found.None", settings), event);
            } else if (items.size() == 1) {
                Message.sendMessage(EventMessageFormatter.getEventEmbed(items.get(0), settings), MessageManager.getMessage("Event.List.Found.One", settings), event);
            } else {
                // List events by Id only.
                Message.sendMessage(MessageManager.getMessage("Event.List.Found.Many", "%amount%", items.size() + "", settings), event);
                for (Event e : items) {
                    Message.sendMessage(EventMessageFormatter.getCondensedEventEmbed(e, settings), event);
                }
            }
        } catch (Exception e) {
            Message.sendMessage(MessageManager.getMessage("Notification.Error.Unknown", settings), event);
            Logger.getLogger().exception(event.getAuthor(), "Failed to list events.", e, this.getClass(), true);
            e.printStackTrace();
        }
    }
}
Also used : Events(com.google.api.services.calendar.model.Events) CalendarData(com.cloudcraftgaming.discal.api.object.calendar.CalendarData) Calendar(com.google.api.services.calendar.Calendar) Event(com.google.api.services.calendar.model.Event) MessageReceivedEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent) DateTime(com.google.api.client.util.DateTime)

Example 5 with Calendar

use of com.google.api.services.calendar.Calendar in project DisCal-Discord-Bot by NovaFox161.

the class EventListCommand method moduleSimpleList.

@SuppressWarnings("Duplicates")
private void moduleSimpleList(String[] args, MessageReceivedEvent event, GuildSettings settings) {
    if (args.length == 0) {
        try {
            Calendar service;
            if (settings.useExternalCalendar()) {
                service = CalendarAuth.getCalendarService(settings);
            } else {
                service = CalendarAuth.getCalendarService();
            }
            DateTime now = new DateTime(System.currentTimeMillis());
            CalendarData calendarData = DatabaseManager.getManager().getMainCalendar(event.getGuild().getLongID());
            Events events = service.events().list(calendarData.getCalendarAddress()).setMaxResults(1).setTimeMin(now).setOrderBy("startTime").setSingleEvents(true).setShowDeleted(false).execute();
            List<Event> items = events.getItems();
            if (items.size() == 0) {
                Message.sendMessage(MessageManager.getMessage("Event.List.Found.None", settings), event);
            } else if (items.size() == 1) {
                Message.sendMessage(EventMessageFormatter.getEventEmbed(items.get(0), settings), MessageManager.getMessage("Event.List.Found.One", settings), event);
            }
        } catch (Exception e) {
            Message.sendMessage(MessageManager.getMessage("Notification.Error.Unknown", settings), event);
            Logger.getLogger().exception(event.getAuthor(), "Failed to list events.", e, this.getClass(), true);
            e.printStackTrace();
        }
    } else if (args.length == 1) {
        try {
            Integer eventNum = Integer.valueOf(args[0]);
            if (eventNum > 15) {
                Message.sendMessage(MessageManager.getMessage("Event.List.Amount.Over", settings), event);
                return;
            }
            if (eventNum < 1) {
                Message.sendMessage(MessageManager.getMessage("Event.List.Amount.Under", settings), event);
                return;
            }
            try {
                Calendar service;
                if (settings.useExternalCalendar()) {
                    service = CalendarAuth.getCalendarService(settings);
                } else {
                    service = CalendarAuth.getCalendarService();
                }
                DateTime now = new DateTime(System.currentTimeMillis());
                CalendarData calendarData = DatabaseManager.getManager().getMainCalendar(event.getGuild().getLongID());
                Events events = service.events().list(calendarData.getCalendarAddress()).setMaxResults(eventNum).setTimeMin(now).setOrderBy("startTime").setSingleEvents(true).execute();
                List<Event> items = events.getItems();
                if (items.size() == 0) {
                    Message.sendMessage(MessageManager.getMessage("Event.List.Found.None", settings), event);
                } else if (items.size() == 1) {
                    Message.sendMessage(EventMessageFormatter.getEventEmbed(items.get(0), settings), MessageManager.getMessage("Event.List.Found.One", settings), event);
                } else {
                    // List events by Id only.
                    Message.sendMessage(MessageManager.getMessage("Event.List.Found.Many", "%amount%", items.size() + "", settings), event);
                    for (Event e : items) {
                        Message.sendMessage(EventMessageFormatter.getCondensedEventEmbed(e, settings), event);
                    }
                }
            } catch (Exception e) {
                Message.sendMessage(MessageManager.getMessage("Notification.Error.Unknown", settings), event);
                Logger.getLogger().exception(event.getAuthor(), "Failed to list events.", e, this.getClass(), true);
                e.printStackTrace();
            }
        } catch (NumberFormatException e) {
            Message.sendMessage(MessageManager.getMessage("Notification.Args.Value.Integer", settings), event);
        }
    } else {
        Message.sendMessage(MessageManager.getMessage("Event.List.Args.Many", settings), event);
    }
}
Also used : Events(com.google.api.services.calendar.model.Events) CalendarData(com.cloudcraftgaming.discal.api.object.calendar.CalendarData) Calendar(com.google.api.services.calendar.Calendar) Event(com.google.api.services.calendar.model.Event) MessageReceivedEvent(sx.blah.discord.handle.impl.events.guild.channel.message.MessageReceivedEvent) ArrayList(java.util.ArrayList) List(java.util.List) DateTime(com.google.api.client.util.DateTime)

Aggregations

Calendar (com.google.api.services.calendar.Calendar)31 Event (com.google.api.services.calendar.model.Event)13 IOException (java.io.IOException)12 CalendarData (com.cloudcraftgaming.discal.api.object.calendar.CalendarData)11 DateTime (com.google.api.client.util.DateTime)8 CalendarListEntry (com.google.api.services.calendar.model.CalendarListEntry)8 Events (com.google.api.services.calendar.model.Events)8 EventData (com.cloudcraftgaming.discal.api.object.event.EventData)7 Credential (com.google.api.client.auth.oauth2.Credential)7 GuildSettings (com.cloudcraftgaming.discal.api.object.GuildSettings)6 ArrayList (java.util.ArrayList)5 EmbedBuilder (sx.blah.discord.util.EmbedBuilder)5 EventColor (com.cloudcraftgaming.discal.api.enums.event.EventColor)4 WebGuild (com.cloudcraftgaming.discal.api.object.web.WebGuild)4 EventDateTime (com.google.api.services.calendar.model.EventDateTime)4 Recurrence (com.cloudcraftgaming.discal.api.object.event.Recurrence)3 CalendarList (com.google.api.services.calendar.model.CalendarList)3 List (java.util.List)3 Map (java.util.Map)3 Consumer (java.util.function.Consumer)3