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

The following examples show how to use com.google.api.services.calendar.model.Event. 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: GoogleCalendar.java    From garoon-google with MIT License 6 votes vote down vote up
public String addSchedule(Date start, Date end, String title, String description, String location, String color, ArrayList<String> recurrence, TimeZone timezone) throws Exception {
	String id = null;

	Event googleSchedule = new Event();
	googleSchedule.setStart(new EventDateTime().setTimeZone(timezone.getID()).setDateTime(new DateTime(start)));
	googleSchedule.setEnd(new EventDateTime().setTimeZone(timezone.getID()).setDateTime(new DateTime(end)));
	googleSchedule.setRecurrence(null);
	googleSchedule.setSummary(title.trim());
	googleSchedule.setDescription(description.trim());
	googleSchedule.setLocation(location.trim());
	googleSchedule.setColorId(color);

	googleSchedule.setRecurrence(recurrence);

	Event createdEvent = this.CALENDAR.events().insert(this.CALENDAR_NAME, googleSchedule).execute();
	id = createdEvent.getId();

	return id;
}
 
Example #2
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 #3
Source File: GCalEventDownloader.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @{inheritDoc}
 */
@Override
protected void execute() {
    Events myFeed = downloadEventFeed();
    if (myFeed != null) {
        List<Event> entries = myFeed.getItems();

        if (entries.size() > 0) {
            logger.debug("found {} calendar events to process", entries.size());

            try {
                if (scheduler.isShutdown()) {
                    logger.warn("Scheduler has been shut down - probably due to exceptions?");
                }
                cleanJobs();
                processEntries(entries);
            } catch (SchedulerException se) {
                logger.error("scheduling jobs throws exception", se);
            }
        } else {
            logger.debug("gcal feed contains no events ...");
        }
    }
}
 
Example #4
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 #5
Source File: GoogleCalendarExporter.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
private static CalendarEventModel convertToCalendarEventModel(String id, Event eventData) {
  List<EventAttendee> attendees = eventData.getAttendees();
  List<String> recurrenceRulesStrings = eventData.getRecurrence();
  return new CalendarEventModel(
      id,
      eventData.getDescription(),
      eventData.getSummary(),
      attendees == null
          ? null
          : attendees
              .stream()
              .map(GoogleCalendarExporter::transformToModelAttendee)
              .collect(Collectors.toList()),
      eventData.getLocation(),
      getEventTime(eventData.getStart()),
      getEventTime(eventData.getEnd()),
      recurrenceRulesStrings == null ? null : getRecurrenceRule(recurrenceRulesStrings));
}
 
Example #6
Source File: GoogleCalendarResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/read/event")
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response readCalendarEvent(@QueryParam("calendarId") String calendarId, @QueryParam("eventId") String eventId) {
    Map<String, Object> headers = new HashMap<>();
    headers.put("CamelGoogleCalendar.calendarId", calendarId);
    headers.put("CamelGoogleCalendar.eventId", eventId);
    try {
        Event response = producerTemplate.requestBodyAndHeaders("google-calendar://events/get", null, headers, Event.class);
        if (response != null) {
            return Response.ok(response.getSummary()).build();
        } else {
            return Response.status(Response.Status.NOT_FOUND).build();
        }
    } catch (CamelExecutionException e) {
        Exception exchangeException = e.getExchange().getException();
        if (exchangeException != null && exchangeException.getCause() instanceof GoogleJsonResponseException) {
            GoogleJsonResponseException originalException = (GoogleJsonResponseException) exchangeException.getCause();
            return Response.status(originalException.getStatusCode()).build();
        }
        throw e;
    }
}
 
Example #7
Source File: HolidayEventsLoader.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
public void loadHolidays(long start, long end) {
  LOG.info("Loading holidays between {} and {}", start, end);
  List<Event> newHolidays = null;
  try {
    newHolidays = getAllHolidays(start, end);
  } catch (Exception e) {
    LOG.error("Fetch holidays failed. Aborting.", e);
    return;
  }
  Map<HolidayEvent, Set<String>> newHolidayEventToCountryCodes = aggregateCountryCodesGroupByHolidays(newHolidays);

  Map<String, List<EventDTO>> holidayNameToHolidayEvent = getHolidayNameToEventDtoMap(newHolidayEventToCountryCodes);

  // Get the existing holidays within the time range from the database
  List<EventDTO> existingEvents = eventDAO.findEventsBetweenTimeRange(EventType.HOLIDAY.toString(), start, end);

  mergeWithExistingHolidays(holidayNameToHolidayEvent, existingEvents);
}
 
Example #8
Source File: GCalPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a new Google Calendar Entry for each <code>item</code> and adds
 * it to the processing queue. The entries' title will either be the items
 * name or <code>alias</code> if it is <code>!= null</code>.
 *
 * The new Calendar Entry will contain a single command to be executed e.g.<br>
 * <p>
 * <code>send &lt;item.name&gt; &lt;item.state&gt;</code>
 * </p>
 *
 * @param item the item which state should be persisted.
 * @param alias the alias under which the item should be persisted.
 */
@Override
public void store(final Item item, final String alias) {
    if (initialized) {
        String newAlias = alias != null ? alias : item.getName();

        Event event = new Event();
        event.setSummary("[PresenceSimulation] " + newAlias);
        event.setDescription(String.format(executeScript, item.getName(), item.getState().toString()));
        Date now = new Date();
        Date startDate = new Date(now.getTime() + 3600000L * 24 * offset);
        Date endDate = startDate;
        DateTime start = new DateTime(startDate);
        event.setStart(new EventDateTime().setDateTime(start));
        DateTime end = new DateTime(endDate);
        event.setEnd(new EventDateTime().setDateTime(end));

        entries.offer(event);

        logger.trace("added new entry '{}' for item '{}' to upload queue", event.getSummary(), item.getName());
    } else {
        logger.debug(
                "GCal PresenceSimulation Service isn't initialized properly! No entries will be uploaded to your Google Calendar");
    }
}
 
Example #9
Source File: HolidayEventsLoader.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private Map<HolidayEvent, Set<String>> aggregateCountryCodesGroupByHolidays(List<Event> newHolidays) {
  // A map from new holiday to a set of country codes that has the holiday
  Map<HolidayEvent, Set<String>> newHolidayEventToCountryCodes = new HashMap<>();

  // Convert Google Event Type to holiday events and aggregates the country code list
  for (Event holiday : newHolidays) {
    String countryCode = getCountryCode(holiday);
    String timeZone = getTimeZoneForCountry(countryCode);
    HolidayEvent holidayEvent =
        new HolidayEvent(holiday.getSummary(), EventType.HOLIDAY.toString(),
            getUtcTimeStamp(holiday.getStart().getDate().getValue(), timeZone),
            getUtcTimeStamp(holiday.getEnd().getDate().getValue(), timeZone));
    if (!newHolidayEventToCountryCodes.containsKey(holidayEvent)) {
      newHolidayEventToCountryCodes.put(holidayEvent, new HashSet<String>());
    }
    if (!countryCode.equals(NO_COUNTRY_CODE)) {
      newHolidayEventToCountryCodes.get(holidayEvent).add(countryCode);
    }
    LOG.info("Get holiday event {} in country {} between {} and {} in timezone {} ", holidayEvent.getName(),
        countryCode, holidayEvent.getStartTime(), holidayEvent.getEndTime(), timeZone);
  }
  return newHolidayEventToCountryCodes;
}
 
Example #10
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 #11
Source File: CheckupReminders.java    From Crimson with Apache License 2.0 6 votes vote down vote up
/**
 * Fetch a list of the next 10 events from the primary calendar.
 *
 * @return List of Strings describing returned events.
 * @throws IOException
 */
private List<String> getDataFromApi() throws IOException {
    // List the next 10 events from the primary calendar.
    DateTime now = new DateTime(System.currentTimeMillis());
    List<String> eventStrings = new ArrayList<String>();
    Events events = mService.events().list("primary")
            .setMaxResults(10)
            .setTimeMin(now)
            .setOrderBy("startTime")
            .setSingleEvents(true)
            .execute();
    List<Event> items = events.getItems();

    for (Event event : items) {
        DateTime start = event.getStart().getDateTime();
        if (start == null) {
            // All-day events don't have start times, so just use
            // the start date.
            start = event.getStart().getDate();
        }
        eventStrings.add(
                String.format("%s (%s)", event.getSummary(), start));
    }
    return eventStrings;
}
 
Example #12
Source File: AnnouncementThread.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean inRange(Announcement a, Event e) {
	long maxDifferenceMs = 5 * 60 * 1000; //5 minutes

	long announcementTimeMs = Integer.toUnsignedLong(a.getMinutesBefore() + (a.getHoursBefore() * 60)) * 60 * 1000;
	long timeUntilEvent = getEventStartMs(e) - System.currentTimeMillis();

	long difference = timeUntilEvent - announcementTimeMs;

	if (difference < 0) {
		//Event past, we can delete announcement depending on the type
		if (a.getAnnouncementType() == AnnouncementType.SPECIFIC)
			DatabaseManager.getManager().deleteAnnouncement(a.getAnnouncementId().toString());

		return false;
	} else {
		return difference <= maxDifferenceMs;
	}
}
 
Example #13
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 #14
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 #15
Source File: AnnouncementThread.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean inRange(Announcement a, Event e) {
	long maxDifferenceMs = 5 * 60 * 1000; //5 minutes

	long announcementTimeMs = Integer.toUnsignedLong(a.getMinutesBefore() + (a.getHoursBefore() * 60)) * 60 * 1000;
	long timeUntilEvent = getEventStartMs(e) - System.currentTimeMillis();

	long difference = timeUntilEvent - announcementTimeMs;

	if (difference < 0) {
		//Event past, we can delete announcement depending on the type
		if (a.getAnnouncementType() == AnnouncementType.SPECIFIC)
			DatabaseManager.getManager().deleteAnnouncement(a.getAnnouncementId().toString());

		return false;
	} else {
		return difference <= maxDifferenceMs;
	}
}
 
Example #16
Source File: EventUtils.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static PreEvent copyEvent(Snowflake guildId, Event event) {
	PreEvent pe = new PreEvent(guildId);
	pe.setSummary(event.getSummary());
	pe.setDescription(event.getDescription());
	pe.setLocation(event.getLocation());
	if (event.getColorId() != null)
		pe.setColor(EventColor.fromNameOrHexOrID(event.getColorId()));
	else
		pe.setColor(EventColor.RED);

	pe.setEventData(DatabaseManager.getManager().getEventData(guildId, event.getId()));

	return pe;
}
 
Example #17
Source File: SyncTokenSample.java    From java-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Sync an individual event. In this example we simply store it's string represenation to a file
 * system data store.
 */
private static void syncEvent(Event event) throws IOException {
  if ("cancelled".equals(event.getStatus()) && eventDataStore.containsKey(event.getId())) {
    eventDataStore.delete(event.getId());
    System.out.println(String.format("Deleting event: ID=%s", event.getId()));
  } else {
    eventDataStore.set(event.getId(), event.toString());
    System.out.println(
        String.format("Syncing event: ID=%s, Name=%s", event.getId(), event.getSummary()));
  }
}
 
Example #18
Source File: Utils.java    From java-samples with Apache License 2.0 5 votes vote down vote up
/** Creates a test event. */
public static Event createTestEvent(Calendar client, String summary) throws IOException {
  Date oneHourFromNow = Utils.getRelativeDate(java.util.Calendar.HOUR, 1);
  Date twoHoursFromNow = Utils.getRelativeDate(java.util.Calendar.HOUR, 2);
  DateTime start = new DateTime(oneHourFromNow, TimeZone.getTimeZone("UTC"));
  DateTime end = new DateTime(twoHoursFromNow, TimeZone.getTimeZone("UTC"));

  Event event = new Event().setSummary(summary)
      .setReminders(new Reminders().setUseDefault(false))
      .setStart(new EventDateTime().setDateTime(start))
      .setEnd(new EventDateTime().setDateTime(end));
  return client.events().insert("primary", event).execute();
}
 
Example #19
Source File: HolidayEventsLoader.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private String getCountryCode(Event holiday) {
  String calendarName = holiday.getCreator().getDisplayName();
  if (calendarName != null && calendarName.length() > 12) {
    String countryName = calendarName.substring(12);
    for (Locale locale : Locale.getAvailableLocales()) {
      if (locale.getDisplayCountry().equals(countryName)) {
        return locale.getCountry();
      }
    }
  }
  return NO_COUNTRY_CODE;
}
 
Example #20
Source File: HolidayEventsLoader.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch holidays from all calendars in Google Calendar API
 *
 * @param start Lower bound (inclusive) for an holiday's end time to filter by.
 * @param end Upper bound (exclusive) for an holiday's start time to filter by.
 */
private List<Event> getAllHolidays(long start, long end) throws Exception {
  List<Event> events = new ArrayList<>();
  for (String calendar : calendarList) {
    try {
      events.addAll(this.getCalendarEvents(calendar, start, end));
    } catch (GoogleJsonResponseException e) {
      LOG.warn("Fetch holiday events failed in calendar {}.", calendar, e);
    }
  }
  return events;
}
 
Example #21
Source File: GCalEventDownloader.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a detailed description of a <code>job</code> for logging purpose.
 *
 * @param job the job to create a detailed description for
 * @return a detailed description of the new <code>job</code>
 */
private String createJobInfo(Event event, JobDetail job) {
    if (job == null) {
        return "SchedulerJob [null]";
    }

    StringBuffer sb = new StringBuffer();
    sb.append("SchedulerJob [jobKey=").append(job.getKey().getName());
    sb.append(", jobGroup=").append(job.getKey().getGroup());

    try {
        List<? extends Trigger> triggers = scheduler.getTriggersOfJob(job.getKey());

        sb.append(", ").append(triggers.size()).append(" triggers=[");

        int maxTriggerLogs = 24;
        for (int triggerIndex = 0; triggerIndex < triggers.size()
                && triggerIndex < maxTriggerLogs; triggerIndex++) {
            Trigger trigger = triggers.get(triggerIndex);
            sb.append(trigger.getStartTime());
            if (triggerIndex < triggers.size() - 1 && triggerIndex < maxTriggerLogs - 1) {
                sb.append(", ");
            }
        }

        if (triggers.size() >= maxTriggerLogs) {
            sb.append(" and ").append(triggers.size() - maxTriggerLogs).append(" more ...");
        }

        if (triggers.size() == 0) {
            sb.append("there are no triggers - probably the event lies in the past");
        }
    } catch (SchedulerException e) {
    }

    sb.append("], content=").append(event.getDescription());

    return sb.toString();
}
 
Example #22
Source File: HolidayEventsLoader.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private List<Event> getCalendarEvents(String Calendar_id, long start, long end) throws Exception {
  GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(keyPath)).createScoped(SCOPES);
  Calendar service =
      new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("thirdeye").build();
  return service.events()
      .list(Calendar_id)
      .setTimeMin(new DateTime(start))
      .setTimeMax(new DateTime(end))
      .execute()
      .getItems();
}
 
Example #23
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 #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 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 #25
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 #26
Source File: GCalEventDownloader.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Checks the first {@link CalendarEventEntry} of <code>entries</code> for
 * completeness. If this first event is incomplete all other events will be
 * incomplete as well.
 *
 * @param list the set to check
 */
private static void checkIfFullCalendarFeed(List<Event> list) {
    if (list != null && !list.isEmpty()) {
        Event referenceEvent = list.get(0);
        if (referenceEvent.getICalUID() == null || referenceEvent.getStart().toString().isEmpty()) {
            logger.warn("calendar entries are incomplete - please make sure to use the full calendar feed");
        }

    }
}
 
Example #27
Source File: GCalEventDownloader.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a new quartz-job with jobData <code>content</code> in the scheduler
 * group <code>GCAL_SCHEDULER_GROUP</code> if <code>content</code> is not
 * blank.
 *
 * @param content the set of commands to be executed by the
 *            {@link ExecuteCommandJob} later on
 * @param event
 * @param isStartEvent indicator to identify whether this trigger will be
 *            triggering a start or an end command.
 *
 * @return the {@link JobDetail}-object to be used at further processing
 */
protected JobDetail createJob(String content, Event event, boolean isStartEvent) {
    String jobIdentity = event.getICalUID() + (isStartEvent ? "_start" : "_end");

    if (StringUtils.isBlank(content)) {
        logger.debug("content of job '{}' is empty -> no task will be created!", jobIdentity);
        return null;
    }

    JobDetail job = newJob(ExecuteCommandJob.class).usingJobData(ExecuteCommandJob.JOB_DATA_CONTENT_KEY, content)
            .withIdentity(jobIdentity, GCAL_SCHEDULER_GROUP).build();

    return job;
}
 
Example #28
Source File: AnnouncementThread.java    From DisCal-Discord-Bot with GNU Lesser General Public License v3.0 5 votes vote down vote up
private long getEventStartMs(Event e) {
	if (e.getStart().getDateTime() != null)
		return e.getStart().getDateTime().getValue();
	else
		return e.getStart().getDate().getValue();

}
 
Example #29
Source File: GoogleCalendarResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/create/event")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createCalendarEvent(@QueryParam("calendarId") String calendarId, String eventText) throws Exception {
    Map<String, Object> headers = new HashMap<>();
    headers.put("CamelGoogleCalendar.calendarId", calendarId);
    headers.put("CamelGoogleCalendar.text", eventText);
    Event response = producerTemplate.requestBodyAndHeaders("google-calendar://events/quickAdd", null, headers,
            Event.class);
    return Response
            .created(new URI("https://camel.apache.org/"))
            .entity(response.getId())
            .build();
}
 
Example #30
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);
        }
    }
}