com.google.api.services.calendar.model.CalendarListEntry Java Examples

The following examples show how to use com.google.api.services.calendar.model.CalendarListEntry. 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: AddEventWorkitemHandler.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 #2
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 #3
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 #4
Source File: GoogleCalendarMetaDataExtension.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<MetaData> meta(Map<String, Object> parameters) {
    String clientId = ConnectorOptions.extractOption(parameters, "clientId");
    if (clientId == null) {
        return Optional.empty();
    }

    LOG.debug("Retrieving calendars for connection to google calendar");
    String clientSecret = ConnectorOptions.extractOption(parameters, "clientSecret");
    String googleScopes = "https://www.googleapis.com/auth/calendar";
    String applicationName = ConnectorOptions.extractOption(parameters, "applicationName");
    String accessToken = ConnectorOptions.extractOption(parameters, "accessToken");
    String refreshToken = ConnectorOptions.extractOption(parameters, "refreshToken");

    Calendar client = new BatchGoogleCalendarClientFactory().makeClient(clientId, clientSecret,
        getScopes(googleScopes), applicationName, refreshToken, accessToken, null, null, "me");

    final CalendarList calendars;
    try {
        calendars = client.calendarList().list().execute();
    } catch (IOException e) {
        throw new IllegalStateException("Unable to fetch the list of calendars", e);
    }

    Set<CalendarListEntry> setCalendars = new HashSet<CalendarListEntry>();
    if (calendars.getItems() != null) {
        for (CalendarListEntry entry : calendars.getItems()) {
            setCalendars.add(entry);
        }
    }

    return Optional.of(MetaDataBuilder.on(getCamelContext()).withAttribute(MetaData.CONTENT_TYPE, "text/plain")
        .withAttribute(MetaData.JAVA_TYPE, String.class).withPayload(setCalendars).build());

}
 
Example #5
Source File: GoogleCalendarMetaDataRetrieval.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected SyndesisMetadata adapt(CamelContext context, String componentId, String actionId, Map<String, Object> properties,
    MetaDataExtension.MetaData metadata) {

    @SuppressWarnings("unchecked")
    Set<CalendarListEntry> calendars = (Set<CalendarListEntry>) metadata.getPayload();

    List<PropertyPair> calendarResult = new ArrayList<>();
    calendars.stream().forEach(t -> calendarResult.add(new PropertyPair(t.getId(), t.getSummary())));

    return SyndesisMetadata.of(Collections.singletonMap("calendarId", calendarResult));
}
 
Example #6
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 #7
Source File: GoogleCalendarExporter.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
private static CalendarModel convertToCalendarModel(CalendarListEntry calendarData) {
  return new CalendarModel(
      calendarData.getId(), calendarData.getSummary(), calendarData.getDescription());
}
 
Example #8
Source File: GoogleCalendarExporter.java    From data-transfer-project with Apache License 2.0 4 votes vote down vote up
private ExportResult<CalendarContainerResource> exportCalendars(
    TokensAndUrlAuthData authData, Optional<PaginationData> pageData) {
  Calendar.CalendarList.List listRequest;
  CalendarList listResult;

  // Get calendar information
  try {
    listRequest = getOrCreateCalendarInterface(authData).calendarList().list();

    if (pageData.isPresent()) {
      StringPaginationToken paginationToken = (StringPaginationToken) pageData.get();
      Preconditions.checkState(
          paginationToken.getToken().startsWith(CALENDAR_TOKEN_PREFIX),
          "Token is not applicable");
      listRequest.setPageToken(
          ((StringPaginationToken) pageData.get())
              .getToken()
              .substring(CALENDAR_TOKEN_PREFIX.length()));
    }

    listResult = listRequest.execute();
  } catch (IOException e) {
    return new ExportResult<>(e);
  }

  // Set up continuation data
  PaginationData nextPageData = null;
  if (listResult.getNextPageToken() != null) {
    nextPageData =
        new StringPaginationToken(CALENDAR_TOKEN_PREFIX + listResult.getNextPageToken());
  }
  ContinuationData continuationData = new ContinuationData(nextPageData);

  // Process calendar list
  List<CalendarModel> calendarModels = new ArrayList<>(listResult.getItems().size());
  for (CalendarListEntry calendarData : listResult.getItems()) {
    CalendarModel model = convertToCalendarModel(calendarData);
    continuationData.addContainerResource(new IdOnlyContainerResource(calendarData.getId()));
    calendarModels.add(model);
  }
  CalendarContainerResource calendarContainerResource =
      new CalendarContainerResource(calendarModels, null);

  // Get result type
  ExportResult.ResultType resultType = ResultType.CONTINUE;
  if (calendarModels.isEmpty()) {
    resultType = ResultType.END;
  }

  return new ExportResult<>(resultType, calendarContainerResource, continuationData);
}
 
Example #9
Source File: AddCalendarCommand.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Issues the command this Object is responsible for.
 *
 * @param args  The command arguments.
 * @param event The event received.
 * @return <code>true</code> if successful, else <code>false</code>.
 */
@Override
public boolean issueCommand(String[] args, MessageCreateEvent event, GuildSettings settings) {
	if (settings.isDevGuild() || settings.isPatronGuild()) {
		if (PermissionChecker.hasManageServerRole(event)) {
			if (args.length == 0) {
				if (DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress().equalsIgnoreCase("primary")) {
					MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Start", settings), event);
					GoogleExternalAuth.getAuth().requestCode(event, settings);
				} else {
					MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.HasCalendar", settings), event);
				}
			} else if (args.length == 1) {
				//Check if arg is calendar ID that is supported, if so, complete the setup.
				if (!DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress().equalsIgnoreCase("primary")) {
					MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.HasCalendar", settings), event);
				} else if (settings.getEncryptedAccessToken().equalsIgnoreCase("N/a") && settings.getEncryptedRefreshToken().equalsIgnoreCase("N/a")) {
					MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Select.NotAuth", settings), event);
				} else {
					try {
						Calendar service = CalendarAuth.getCalendarService(settings);
						List<CalendarListEntry> items = service.calendarList().list().setMinAccessRole("writer").execute().getItems();
						boolean valid = false;
						for (CalendarListEntry i: items) {
							if (!i.isDeleted() && i.getId().equals(args[0])) {
								//valid
								valid = true;
								break;
							}
						}
						if (valid) {
							//Update and save.
							CalendarData data = new CalendarData(event.getGuild().block().getId(), 1);
							data.setCalendarId(args[0]);
							data.setCalendarAddress(args[0]);
							data.setExternal(true);
							DatabaseManager.getManager().updateCalendar(data);

							//Update guild settings
							settings.setUseExternalCalendar(true);
							DatabaseManager.getManager().updateSettings(settings);

							MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Select.Success", settings), event);
						} else {
							//Invalid
							MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Select.Failure.Invalid", settings), event);
						}
					} catch (Exception e) {
						MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Select.Failure.Unknown", settings), event);
						Logger.getLogger().exception(event.getMember().get(), "Failed to connect external calendar!", e, true, this.getClass());
					}
				}
			} else {
				MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Specify", settings), event);
			}
		} else {
			MessageManager.sendMessageAsync(MessageManager.getMessage("Notification.Perm.MANAGE_SERVER", settings), event);
		}
	} else {
		MessageManager.sendMessageAsync(MessageManager.getMessage("Notification.Patron", settings), event);
	}
	return false;
}
 
Example #10
Source File: AddCalendarCommand.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Issues the command this Object is responsible for.
 *
 * @param args  The command arguments.
 * @param event The event received.
 * @return <code>true</code> if successful, else <code>false</code>.
 */
@Override
public boolean issueCommand(String[] args, MessageCreateEvent event, GuildSettings settings) {
	if (settings.isDevGuild() || settings.isPatronGuild()) {
		if (PermissionChecker.hasManageServerRole(event)) {
			if (args.length == 0) {
				if (DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress().equalsIgnoreCase("primary")) {
					MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Start", settings), event);
					GoogleExternalAuth.getAuth().requestCode(event, settings);
				} else {
					MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.HasCalendar", settings), event);
				}
			} else if (args.length == 1) {
				//Check if arg is calendar ID that is supported, if so, complete the setup.
				if (!DatabaseManager.getManager().getMainCalendar(settings.getGuildID()).getCalendarAddress().equalsIgnoreCase("primary")) {
					MessageManager.sendMessageAsync(MessageManager.getMessage("Creator.Calendar.HasCalendar", settings), event);
				} else if (settings.getEncryptedAccessToken().equalsIgnoreCase("N/a") && settings.getEncryptedRefreshToken().equalsIgnoreCase("N/a")) {
					MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Select.NotAuth", settings), event);
				} else {
					try {
						Calendar service = CalendarAuth.getCalendarService(settings);
						List<CalendarListEntry> items = service.calendarList().list().setMinAccessRole("writer").execute().getItems();
						boolean valid = false;
						for (CalendarListEntry i: items) {
							if (!i.isDeleted() && i.getId().equals(args[0])) {
								//valid
								valid = true;
								break;
							}
						}
						if (valid) {
							//Update and save.
							CalendarData data = new CalendarData(event.getGuild().block().getId(), 1);
							data.setCalendarId(args[0]);
							data.setCalendarAddress(args[0]);
							data.setExternal(true);
							DatabaseManager.getManager().updateCalendar(data);

							//Update guild settings
							settings.setUseExternalCalendar(true);
							DatabaseManager.getManager().updateSettings(settings);

							MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Select.Success", settings), event);
						} else {
							//Invalid
							MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Select.Failure.Invalid", settings), event);
						}
					} catch (Exception e) {
						MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Select.Failure.Unknown", settings), event);
						Logger.getLogger().exception(event.getMember().get(), "Failed to connect external calendar!", e, true, this.getClass());
					}
				}
			} else {
				MessageManager.sendMessageAsync(MessageManager.getMessage("AddCalendar.Specify", settings), event);
			}
		} else {
			MessageManager.sendMessageAsync(MessageManager.getMessage("Notification.Perm.MANAGE_SERVER", settings), event);
		}
	} else {
		MessageManager.sendMessageAsync(MessageManager.getMessage("Notification.Patron", settings), event);
	}
	return false;
}
 
Example #11
Source File: GCalEventDownloader.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Connects to Google-Calendar Service and returns the specified Events
 *
 * @return the corresponding Events or <code>null</code> if an error
 *         occurs. <i>Note:</i> We do only return events if their startTime lies between
 *         <code>now</code> and <code>now + 2 * refreshInterval</code> to reduce
 *         the amount of events to process.
 */
private static Events downloadEventFeed() {
    // TODO: teichsta: there could be more than one calendar url in openHAB.cfg
    // for now we accept this limitation of downloading just one feed ...

    if (StringUtils.isBlank(calendar_name)) {
        logger.warn("Login aborted no calendar name defined");
        return null;
    }
    // authorization

    CalendarListEntry calendarID = GCalGoogleOAuth.getCalendarId(calendar_name);

    if (calendarID == null) {
        return null;
    }

    DateTime start = new DateTime(new Date(), TimeZone.getTimeZone(calendarID.getTimeZone()));
    DateTime end = new DateTime(new Date(start.getValue() + (2 * refreshInterval)),
            TimeZone.getTimeZone(calendarID.getTimeZone()));
    logger.debug("Downloading calendar feed for time interval: {} to  {} ", start, end);

    Events feed = null;
    try {
        Credential credential = GCalGoogleOAuth.getCredential(false);

        // set up global Calendar instance
        Calendar client = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("openHAB").build();
        Calendar.Events.List l = client.events().list(calendarID.getId()).setSingleEvents(true).setTimeMin(start)
                .setTimeMax(end);

        // add the fulltext filter if it has been configured
        if (StringUtils.isNotBlank(filter)) {
            l = l.setQ(filter);
        }
        feed = l.execute();
    } catch (IOException e1) {
        logger.error("Event fetch failed: {}", e1.getMessage());
    }

    try {

        if (feed != null) {
            checkIfFullCalendarFeed(feed.getItems());
        }

        return feed;
    } catch (Exception e) {
        logger.error("downloading CalendarEventFeed throws exception: {}", e.getMessage());
    }

    return null;
}