com.google.api.services.calendar.Calendar Java Examples

The following examples show how to use com.google.api.services.calendar.Calendar. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AnnouncementThread.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
private List<Event> getEvents(GuildSettings gs, CalendarData cd, Calendar service, Announcement a) {
	if (!allEvents.containsKey(gs.getGuildID())) {
		Logger.getLogger().announcement("getting events for guild...", gs.getGuildID() + "", a.getAnnouncementId() + "", "N/a");
		try {
			Events events = service.events().list(cd.getCalendarAddress())
					.setMaxResults(15)
					.setTimeMin(new DateTime(System.currentTimeMillis()))
					.setOrderBy("startTime")
					.setSingleEvents(true)
					.setShowDeleted(false)
					.execute();
			List<Event> items = events.getItems();
			allEvents.put(gs.getGuildID(), items);
		} catch (IOException e) {
			Logger.getLogger().exception(null, "Failed to get events list! 01ae2304 | Guild: " + gs.getGuildID() + " | Announcement: " + a.getAnnouncementId(), e, true, this.getClass());
			return new ArrayList<>();
		}
	}
	return allEvents.get(gs.getGuildID());
}
 
Example #2
Source File: GCalPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a new calendar entry.
 *
 * @param event the event to create in the remote calendar identified by the
 *            full calendar feed configured in </code>openhab.cfg</code>
 * @return the newly created entry
 * @throws IOException
 */
private Event createCalendarEvent(Calendar calendarClient, Event event) throws IOException {

    if (calendarClient == null) {
        logger.error(
                "Please configure gcal:client_id/gcal:client_secret in openhab.cfg. Refer to wiki how to create client_id/client_secret pair");
    } else {
        // set up global Calendar instance
        CalendarListEntry calendarID = GCalGoogleOAuth.getCalendarId(calendar_name);
        if (calendarID != null) {
            return calendarClient.events().insert(calendarID.getId(), event).execute();
        }

    }

    return null;

}
 
Example #3
Source File: GoogleCalendarVerifierExtension.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
protected Result verifyConnectivity(Map<String, Object> parameters) {
    ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY);

    try {
        GoogleCalendarStreamConfiguration configuration = setProperties(new GoogleCalendarStreamConfiguration(), parameters);
        GoogleCalendarClientFactory clientFactory = new BatchGoogleCalendarClientFactory();
        Calendar client = clientFactory.makeClient(configuration.getClientId(), configuration.getClientSecret(), configuration.getScopes(), configuration.getApplicationName(),
                                                   configuration.getRefreshToken(), configuration.getAccessToken(), null, null, "me");
        client.calendarList().list().execute();
    } catch (Exception e) {
        ResultErrorBuilder errorBuilder = ResultErrorBuilder.withCodeAndDescription(VerificationError.StandardCode.AUTHENTICATION, e.getMessage())
            .detail("google_calendar_exception", e.getMessage()).detail(VerificationError.ExceptionAttribute.EXCEPTION_CLASS, e.getClass().getName())
            .detail(VerificationError.ExceptionAttribute.EXCEPTION_INSTANCE, e);

        builder.error(errorBuilder.build());
    }

    return builder.build();
}
 
Example #4
Source File: AnnouncementThread.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
private List<Event> getEvents(GuildSettings gs, CalendarData cd, Calendar service, Announcement a) {
	if (!allEvents.containsKey(gs.getGuildID())) {
		Logger.getLogger().announcement("getting events for guild...", gs.getGuildID() + "", a.getAnnouncementId() + "", "N/a");
		try {
			Events events = service.events().list(cd.getCalendarAddress())
					.setMaxResults(15)
					.setTimeMin(new DateTime(System.currentTimeMillis()))
					.setOrderBy("startTime")
					.setSingleEvents(true)
					.setShowDeleted(false)
					.execute();
			List<Event> items = events.getItems();
			allEvents.put(gs.getGuildID(), items);
		} catch (IOException e) {
			Logger.getLogger().exception(null, "Failed to get events list! 01ae2304 | Guild: " + gs.getGuildID() + " | Announcement: " + a.getAnnouncementId(), e, true, this.getClass());
			return new ArrayList<>();
		}
	}
	return allEvents.get(gs.getGuildID());
}
 
Example #5
Source File: GoogleCalendarWorkitemHandlerTest.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddCalendarHandler() throws Exception {

    TestWorkItemManager manager = new TestWorkItemManager();
    WorkItemImpl workItem = new WorkItemImpl();
    workItem.setParameter("CalendarSummary",
                          "mycalendarsummary");

    AddCalendarWorkitemHandler handler = new AddCalendarWorkitemHandler("myAppName",
                                                                        "{}");
    handler.setAuth(auth);

    handler.executeWorkItem(workItem,
                            manager);
    assertNotNull(manager.getResults());
    assertEquals(1,
                 manager.getResults().size());
    assertTrue(manager.getResults().containsKey(workItem.getId()));

    assertTrue((manager.getResults().get(workItem.getId())).get("Calendar") instanceof com.google.api.services.calendar.model.Calendar);
}
 
Example #6
Source File: GoogleCalendarWorkitemHandlerTest.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    try {
        CalendarList calendarListModel = new com.google.api.services.calendar.model.CalendarList();
        when(client.calendars()).thenReturn(calendars);
        when(calendars.insert(anyObject())).thenReturn(calendarsInsert);
        when(calendarsInsert.execute()).thenReturn(new com.google.api.services.calendar.model.Calendar());
        when(client.calendarList()).thenReturn(calendarsList);
        when(calendarsList.list()).thenReturn(calendarsListList);
        when(calendarsListList.execute()).thenReturn(calendarListModel);
        when(auth.getAuthorizedCalendar(anyString(),
                                        anyString())).thenReturn(client);
        when(client.events()).thenReturn(clientEvents);
        when(clientEvents.insert(anyString(),
                                 anyObject())).thenReturn(calendarEventsInsert);
        when(calendarEventsInsert.execute()).thenReturn(new com.google.api.services.calendar.model.Event());
        when(clientEvents.list(anyString())).thenReturn(calendarEventsList);
        when(calendarEventsList.execute()).thenReturn(new com.google.api.services.calendar.model.Events());
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
 
Example #7
Source File: GCalPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
    logger.trace("going to upload {} calendar entries to Google now ...", entries.size());
    Calendar calendarClient = null;
    if (entries.size() > 0) {
        Credential credential = GCalGoogleOAuth.getCredential(false);
        if (credential == null) {
            logger.error(
                    "Please configure gcal:client_id/gcal:client_secret in openhab.cfg. Refer to wiki how to create client_id/client_secret pair");
        } else {
            // set up global Calendar instance
            calendarClient = new com.google.api.services.calendar.Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY,
                    credential).setApplicationName("openHABpersistence").build();
        }
    }
    for (Event entry : entries) {
        upload(calendarClient, entry);
        entries.remove(entry);
    }
}
 
Example #8
Source File: ConditionalRetrievalSample.java    From java-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a test event, pauses while the user modifies the event in the Calendar UI, and then
 * checks if the event has been modified.
 */
private static void run() throws IOException {
  // Create a test event.
  Event event = Utils.createTestEvent(client, "Test Event");
  System.out.println(String.format("Event created: %s", event.getHtmlLink()));

  // Pause while the user modifies the event in the Calendar UI.
  System.out.println("Modify the event's description and hit enter to continue.");
  System.in.read();

  // Fetch the event again if it's been modified.
  Calendar.Events.Get getRequest = client.events().get("primary", event.getId());
  getRequest.setRequestHeaders(new HttpHeaders().setIfNoneMatch(event.getEtag()));
  try {
    event = getRequest.execute();
    System.out.println("The event was modified, retrieved latest version.");
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == 304) {
      // A 304 status code, "Not modified", indicates that the etags match, and the event has
      // not been modified since we last retrieved it.
      System.out.println("The event was not modified, using local version.");
    } else {
      throw e;
    }
  }
}
 
Example #9
Source File: GoogleCalendarExporterTest.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException {
  calendarClient = mock(Calendar.class);
  calendarCalendars = mock(Calendar.Calendars.class);
  calendarCalendarList = mock(Calendar.CalendarList.class);
  calendarListRequest = mock(Calendar.CalendarList.List.class);
  calendarEvents = mock(Calendar.Events.class);
  eventListRequest = mock(Calendar.Events.List.class);
  credentialFactory = mock(GoogleCredentialFactory.class);

  googleCalendarExporter = new GoogleCalendarExporter(credentialFactory, calendarClient);

  when(calendarClient.calendars()).thenReturn(calendarCalendars);

  when(calendarClient.calendarList()).thenReturn(calendarCalendarList);
  when(calendarCalendarList.list()).thenReturn(calendarListRequest);
  when(calendarClient.events()).thenReturn(calendarEvents);

  when(calendarEvents.list(CALENDAR_ID)).thenReturn(eventListRequest);
  when(eventListRequest.setMaxAttendees(MAX_ATTENDEES)).thenReturn(eventListRequest);

  verifyNoInteractions(credentialFactory);
}
 
Example #10
Source File: GoogleCalendarImporterTest.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
  calendarClient = mock(Calendar.class);
  calendarCalendars = mock(Calendar.Calendars.class);
  calendarInsertRequest = mock(Calendar.Calendars.Insert.class);
  calendarEvents = mock(Calendar.Events.class);
  eventInsertRequest = mock(Calendar.Events.Insert.class);
  credentialFactory = mock(GoogleCredentialFactory.class);

  executor = new FakeIdempotentImportExecutor();

  calendarService = new GoogleCalendarImporter(credentialFactory, calendarClient);

  when(calendarClient.calendars()).thenReturn(calendarCalendars);
  when(calendarClient.events()).thenReturn(calendarEvents);

  verifyNoInteractions(credentialFactory);
}
 
Example #11
Source File: GetEventsWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public String getCalendarIdBySummary(com.google.api.services.calendar.Calendar client,
                                     String summary) {
    String resultId = null;
    try {
        CalendarList calendarList = getAllCalendars(client);
        List<CalendarListEntry> entryList = calendarList.getItems();
        for (CalendarListEntry entry : entryList) {
            if (entry.getSummary().equalsIgnoreCase(summary)) {
                resultId = entry.getId();
            }
        }
    } catch (Exception e) {
        logger.error(MessageFormat.format("Error retrieveing calendars: {0}",
                                          e.getMessage()));
    }
    return resultId;
}
 
Example #12
Source File: GetEventsWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    String paramCalendarSummary = (String) workItem.getParameter("CalendarSummary");
    Map<String, Object> results = new HashMap<String, Object>();

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        Calendar client = auth.getAuthorizedCalendar(appName,
                                                     clientSecret);

        results.put(RESULTS_ALL_EVENTS,
                    getAllEvents(client,
                                 getCalendarIdBySummary(client,
                                                        paramCalendarSummary)));

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        handleException(e);
    }
}
 
Example #13
Source File: CalendarUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Deletes a calendar from Google Calendar and the Db
 *
 * @param data The BotData of the Guild whose deleting their calendar.
 * @return <code>true</code> if successful, else <code>false</code>.
 */
public static boolean deleteCalendar(CalendarData data, GuildSettings settings) {
	try {
		//Only delete if the calendar is stored on DisCal's account.
		if (!data.getCalendarAddress().equalsIgnoreCase("primary") && !settings.useExternalCalendar()) {
			Calendar service = CalendarAuth.getCalendarService(settings);
			service.calendars().delete(data.getCalendarAddress()).execute();
		}
	} catch (Exception e) {
		//Fail silently.
		Logger.getLogger().exception(null, "Failed to delete calendar", e, true, CalendarUtils.class);
		return false;
	}
	if (settings.useExternalCalendar()) {
		//Update settings.
		settings.setUseExternalCalendar(false);
		settings.setEncryptedAccessToken("N/a");
		settings.setEncryptedRefreshToken("N/a");
		DatabaseManager.getManager().updateSettings(settings);
	}

	//Delete everything that is specific to the calendar...
	DatabaseManager.getManager().deleteCalendar(data);
	DatabaseManager.getManager().deleteAllEventData(data.getGuildId());
	DatabaseManager.getManager().deleteAllRSVPData(data.getGuildId());
	DatabaseManager.getManager().deleteAllAnnouncementData(data.getGuildId());

	return true;
}
 
Example #14
Source File: AnnouncementThread.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Calendar getService(GuildSettings gs) throws Exception {
	if (gs.useExternalCalendar()) {
		if (!customServices.containsKey(gs.getGuildID()))
			customServices.put(gs.getGuildID(), CalendarAuth.getCalendarService(gs));

		return customServices.get(gs.getGuildID());
	}
	return discalService;
}
 
Example #15
Source File: EventCreator.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public PreEvent init(MessageCreateEvent e, String eventId, GuildSettings settings, boolean handleMessage) {
	if (!hasPreEvent(settings.getGuildID())) {
		//TODO: Handle multiple calendars...
		try {
			String calId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress();
			Calendar service = CalendarAuth.getCalendarService(settings);

			Event calEvent = service.events().get(calId, eventId).execute();

			PreEvent event = EventUtils.copyEvent(settings.getGuildID(), calEvent);

			try {
				event.setTimeZone(service.calendars().get(calId).execute().getTimeZone());
			} catch (IOException e1) {
				//Failed to get tz, ignore safely.
			}

			if (handleMessage) {
				if (PermissionChecker.botHasMessageManagePerms(e)) {
					Message message = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Event.Copy.Init", settings), EventMessageFormatter.getPreEventEmbed(event, settings), e);
					event.setCreatorMessage(message);
					MessageManager.deleteMessage(e);
				} else {
					MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e);
				}
			}

			events.add(event);
			return event;
		} catch (Exception exc) {
			//Something failed...
		}
		return null;
	}
	return getPreEvent(settings.getGuildID());
}
 
Example #16
Source File: EventCreator.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public PreEvent edit(MessageCreateEvent e, String eventId, GuildSettings settings, boolean handleMessage) {
	if (!hasPreEvent(settings.getGuildID())) {
		//TODO: Handle multiple calendars...
		try {
			String calId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress();
			Calendar service = CalendarAuth.getCalendarService(settings);

			Event calEvent = service.events().get(calId, eventId).execute();

			PreEvent event = new PreEvent(settings.getGuildID(), calEvent);
			event.setEditing(true);

			try {
				event.setTimeZone(service.calendars().get(calId).execute().getTimeZone());
			} catch (IOException ignore) {
				//Failed to get tz, ignore safely.
			}

			if (handleMessage) {
				if (PermissionChecker.botHasMessageManagePerms(e)) {
					Message message = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Event.Edit.Init", settings), EventMessageFormatter.getPreEventEmbed(event, settings), e);
					event.setCreatorMessage(message);
					MessageManager.deleteMessage(e);
				} else {
					MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e);
				}
			}

			events.add(event);
			return event;
		} catch (Exception exc) {
			//Oops
		}
		return null;
	}
	return getPreEvent(settings.getGuildID());
}
 
Example #17
Source File: EventUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean eventExists(GuildSettings settings, String eventId) {
	//TODO: Support multiple calendars...
	String calendarId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress();
	try {
		Calendar service = CalendarAuth.getCalendarService(settings);

		return service.events().get(calendarId, eventId).execute() != null;
	} catch (Exception e) {
		//Failed to check event, probably doesn't exist, safely ignore.
	}
	return false;
}
 
Example #18
Source File: EventCreator.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public PreEvent edit(MessageCreateEvent e, String eventId, GuildSettings settings, boolean handleMessage) {
	if (!hasPreEvent(settings.getGuildID())) {
		//TODO: Handle multiple calendars...
		try {
			String calId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress();
			Calendar service = CalendarAuth.getCalendarService(settings);

			Event calEvent = service.events().get(calId, eventId).execute();

			PreEvent event = new PreEvent(settings.getGuildID(), calEvent);
			event.setEditing(true);

			try {
				event.setTimeZone(service.calendars().get(calId).execute().getTimeZone());
			} catch (IOException ignore) {
				//Failed to get tz, ignore safely.
			}

			if (handleMessage) {
				if (PermissionChecker.botHasMessageManagePerms(e)) {
					Message message = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Event.Edit.Init", settings), EventMessageFormatter.getPreEventEmbed(event, settings), e);
					event.setCreatorMessage(message);
					MessageManager.deleteMessage(e);
				} else {
					MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e);
				}
			}

			events.add(event);
			return event;
		} catch (Exception exc) {
			//Oops
		}
		return null;
	}
	return getPreEvent(settings.getGuildID());
}
 
Example #19
Source File: GoogleCalendar.java    From garoon-google with MIT License 5 votes vote down vote up
GoogleCalendar(CredentialConfig config) throws Exception {
	this.GOOGLE_CREDENTIAL = authenticate(config);

	this.CALENDAR = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, GOOGLE_CREDENTIAL)
	.setApplicationName("GGsync")
	.build();

	this.RECURRENCE_SDF.setTimeZone(TimeZone.getTimeZone("UTC"));
}
 
Example #20
Source File: CalendarQuickstart.java    From java-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String... args) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();

    // List the next 10 events from the primary calendar.
    DateTime now = new DateTime(System.currentTimeMillis());
    Events events = service.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute();
    List<Event> items = events.getItems();
    if (items.isEmpty()) {
        System.out.println("No upcoming events found.");
    } else {
        System.out.println("Upcoming events");
        for (Event event : items) {
            DateTime start = event.getStart().getDateTime();
            if (start == null) {
                start = event.getStart().getDate();
            }
            System.out.printf("%s (%s)\n", event.getSummary(), start);
        }
    }
}
 
Example #21
Source File: AnnouncementThread.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Calendar getService(GuildSettings gs) throws Exception {
	if (gs.useExternalCalendar()) {
		if (!customServices.containsKey(gs.getGuildID()))
			customServices.put(gs.getGuildID(), CalendarAuth.getCalendarService(gs));

		return customServices.get(gs.getGuildID());
	}
	return discalService;
}
 
Example #22
Source File: CalendarUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Deletes a calendar from Google Calendar and the Db
 *
 * @param data The BotData of the Guild whose deleting their calendar.
 * @return <code>true</code> if successful, else <code>false</code>.
 */
public static boolean deleteCalendar(CalendarData data, GuildSettings settings) {
	try {
		//Only delete if the calendar is stored on DisCal's account.
		if (!data.getCalendarAddress().equalsIgnoreCase("primary") && !settings.useExternalCalendar()) {
			Calendar service = CalendarAuth.getCalendarService(settings);
			service.calendars().delete(data.getCalendarAddress()).execute();
		}
	} catch (Exception e) {
		//Fail silently.
		Logger.getLogger().exception(null, "Failed to delete calendar", e, true, CalendarUtils.class);
		return false;
	}
	if (settings.useExternalCalendar()) {
		//Update settings.
		settings.setUseExternalCalendar(false);
		settings.setEncryptedAccessToken("N/a");
		settings.setEncryptedRefreshToken("N/a");
		DatabaseManager.getManager().updateSettings(settings);
	}

	//Delete everything that is specific to the calendar...
	DatabaseManager.getManager().deleteCalendar(data);
	DatabaseManager.getManager().deleteAllEventData(data.getGuildId());
	DatabaseManager.getManager().deleteAllRSVPData(data.getGuildId());
	DatabaseManager.getManager().deleteAllAnnouncementData(data.getGuildId());

	return true;
}
 
Example #23
Source File: EventUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean eventExists(GuildSettings settings, String eventId) {
	//TODO: Support multiple calendars...
	String calendarId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress();
	try {
		Calendar service = CalendarAuth.getCalendarService(settings);

		return service.events().get(calendarId, eventId).execute() != null;
	} catch (Exception e) {
		//Failed to check event, probably doesn't exist, safely ignore.
	}
	return false;
}
 
Example #24
Source File: EventCreator.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public PreEvent init(MessageCreateEvent e, String eventId, GuildSettings settings, boolean handleMessage) {
	if (!hasPreEvent(settings.getGuildID())) {
		//TODO: Handle multiple calendars...
		try {
			String calId = DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress();
			Calendar service = CalendarAuth.getCalendarService(settings);

			Event calEvent = service.events().get(calId, eventId).execute();

			PreEvent event = EventUtils.copyEvent(settings.getGuildID(), calEvent);

			try {
				event.setTimeZone(service.calendars().get(calId).execute().getTimeZone());
			} catch (IOException e1) {
				//Failed to get tz, ignore safely.
			}

			if (handleMessage) {
				if (PermissionChecker.botHasMessageManagePerms(e)) {
					Message message = MessageManager.sendMessageSync(MessageManager.getMessage("Creator.Event.Copy.Init", settings), EventMessageFormatter.getPreEventEmbed(event, settings), e);
					event.setCreatorMessage(message);
					MessageManager.deleteMessage(e);
				} else {
					MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Notif.MANAGE_MESSAGES", settings), e);
				}
			}

			events.add(event);
			return event;
		} catch (Exception exc) {
			//Something failed...
		}
		return null;
	}
	return getPreEvent(settings.getGuildID());
}
 
Example #25
Source File: Utils.java    From java-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a new {@link java.util.Date} relative to the current date and time.
 *
 * @param field the field identifier from {@link java.util.Calendar} to increment
 * @param amount the amount of the field to increment
 * @return the new date
 */
public static Date getRelativeDate(int field, int amount) {
  Date now = new Date();
  java.util.Calendar cal = java.util.Calendar.getInstance();
  cal.setTime(now);
  cal.add(field, amount);
  return cal.getTime();
}
 
Example #26
Source File: GCalGoogleOAuth.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: GoogleCalendarExporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
private synchronized Calendar makeCalendarInterface(TokensAndUrlAuthData authData) {
  Credential credential = credentialFactory.createCredential(authData);
  return new Calendar.Builder(
      credentialFactory.getHttpTransport(), credentialFactory.getJsonFactory(), credential)
      .setApplicationName(GoogleStaticObjects.APP_NAME)
      .build();
}
 
Example #28
Source File: GCalPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private void upload(Calendar calendarClient, Event entry) {
    try {
        long startTime = System.currentTimeMillis();
        Event createdEvent = createCalendarEvent(calendarClient, entry);
        logger.debug("succesfully created new calendar event (title='{}', date='{}', content='{}') in {}ms",
                new Object[] { createdEvent.getSummary(), createdEvent.getStart().toString(),
                        createdEvent.getDescription(), System.currentTimeMillis() - startTime });
    } catch (Exception e) {
        logger.error("creating a new calendar entry throws an exception: {}", e.getMessage());
    }
}
 
Example #29
Source File: GoogleCalendarImporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
static com.google.api.services.calendar.model.Calendar convertToGoogleCalendar(
    CalendarModel
        calendarModel) {
  return new com.google.api.services.calendar.model.Calendar()
      .setSummary("Copy of - " + calendarModel.getName())
      .setDescription(calendarModel.getDescription());
}
 
Example #30
Source File: GoogleCalendarImporter.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
String importSingleCalendar(TokensAndUrlAuthData authData, CalendarModel calendarModel)
    throws IOException {
  com.google.api.services.calendar.model.Calendar toInsert = convertToGoogleCalendar(
      calendarModel);
  com.google.api.services.calendar.model.Calendar calendarResult =
      getOrCreateCalendarInterface(authData).calendars().insert(toInsert).execute();
  return calendarResult.getId();
}