Search in sources :

Example 16 with DateTime

use of com.google.api.client.util.DateTime in project jbpm-work-items by kiegroup.

the class AddEventWorkitemHandler method createNewEvent.

private static Event createNewEvent(String paramEventSummary, String paramEventStart, String paramEventEnd, String paramEventAttendees, String paramEventCreator) throws Exception {
    Event event = new Event();
    event.setSummary(paramEventSummary);
    DateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);
    if (paramEventStart != null) {
        DateTime startDateTime = new DateTime(format.parse(paramEventStart));
        event.setStart(new EventDateTime().setDateTime(startDateTime));
    }
    if (paramEventEnd != null) {
        DateTime endDateTime = new DateTime(format.parse(paramEventEnd));
        event.setEnd(new EventDateTime().setDateTime(endDateTime));
    }
    if (paramEventAttendees != null) {
        List<String> attendees = Arrays.asList(paramEventAttendees.split(","));
        List<EventAttendee> attendiesList = new ArrayList<>();
        for (String attendee : attendees) {
            EventAttendee newAttendee = new EventAttendee();
            newAttendee.setEmail(attendee);
            attendiesList.add(newAttendee);
        }
        event.setAttendees(attendiesList);
    }
    if (paramEventCreator != null) {
        Creator creator = new Creator();
        creator.setEmail(paramEventCreator);
        event.setCreator(creator);
    }
    return event;
}
Also used : EventDateTime(com.google.api.services.calendar.model.EventDateTime) EventAttendee(com.google.api.services.calendar.model.EventAttendee) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) ArrayList(java.util.ArrayList) Event(com.google.api.services.calendar.model.Event) Creator(com.google.api.services.calendar.model.Event.Creator) SimpleDateFormat(java.text.SimpleDateFormat) DateTime(com.google.api.client.util.DateTime) EventDateTime(com.google.api.services.calendar.model.EventDateTime)

Example 17 with DateTime

use of com.google.api.client.util.DateTime in project jbpm-work-items by kiegroup.

the class MediaUploadWorkitemHandler method executeWorkItem.

public void executeWorkItem(WorkItem workItem, WorkItemManager workItemManager) {
    Document docToUpload = (Document) workItem.getParameter("DocToUpload");
    String docMimeType = (String) workItem.getParameter("DocMimeType");
    String uploadPath = (String) workItem.getParameter("UploadPath");
    if (docToUpload != null && docMimeType != null && uploadPath != null) {
        try {
            Drive drive = auth.getDriveService(appName, clientSecret);
            File fileMetadata = new File();
            fileMetadata.setTitle(docToUpload.getName());
            fileMetadata.setAlternateLink(docToUpload.getLink());
            if (docToUpload.getLastModified() != null) {
                fileMetadata.setModifiedDate(new DateTime(docToUpload.getLastModified()));
            }
            java.io.File tempDocFile = java.io.File.createTempFile(FilenameUtils.getBaseName(docToUpload.getName()), "." + FilenameUtils.getExtension(docToUpload.getName()));
            FileOutputStream fos = new FileOutputStream(tempDocFile);
            fos.write(docToUpload.getContent());
            fos.close();
            FileContent mediaContent = new FileContent(docMimeType, tempDocFile);
            Drive.Files.Insert insert = drive.files().insert(fileMetadata, mediaContent);
            MediaHttpUploader uploader = insert.getMediaHttpUploader();
            uploader.setDirectUploadEnabled(true);
            uploader.setProgressListener(new MediaUploadProgressListener());
            insert.execute();
            workItemManager.completeWorkItem(workItem.getId(), null);
        } catch (Exception e) {
            handleException(e);
        }
    } else {
        logger.error("Missing upload document information.");
        throw new IllegalArgumentException("Missing upload document information.");
    }
}
Also used : MediaHttpUploader(com.google.api.client.googleapis.media.MediaHttpUploader) Document(org.jbpm.document.Document) DateTime(com.google.api.client.util.DateTime) FileContent(com.google.api.client.http.FileContent) FileOutputStream(java.io.FileOutputStream) Drive(com.google.api.services.drive.Drive) File(com.google.api.services.drive.model.File)

Example 18 with DateTime

use of com.google.api.client.util.DateTime in project SeriesGuide by UweTrottmann.

the class HexagonListsSync method download.

public boolean download(boolean hasMergedLists) {
    long currentTime = System.currentTimeMillis();
    DateTime lastSyncTime = new DateTime(HexagonSettings.getLastListsSyncTime(context));
    if (hasMergedLists) {
        Timber.d("download: lists changed since %s.", lastSyncTime);
    } else {
        Timber.d("download: all lists.");
    }
    HashSet<String> localListIds = ListsTools.getListIds(context);
    List<SgList> lists;
    String cursor = null;
    do {
        try {
            // get service each time to check if auth was removed
            Lists listsService = hexagonTools.getListsService();
            if (listsService == null) {
                // no longer signed in
                return false;
            }
            // use default server limit
            Lists.Get request = listsService.get();
            if (hasMergedLists) {
                request.setUpdatedSince(lastSyncTime);
            }
            if (!TextUtils.isEmpty(cursor)) {
                request.setCursor(cursor);
            }
            SgListList response = request.execute();
            if (response == null) {
                Timber.d("download: failed, response is null.");
                break;
            }
            cursor = response.getCursor();
            lists = response.getLists();
        } catch (IOException | IllegalArgumentException e) {
            // Note: JSON parser may throw IllegalArgumentException.
            Errors.logAndReportHexagon("get lists", e);
            return false;
        }
        if (lists == null || lists.size() == 0) {
            // empty response, assume we are done
            break;
        }
        if (!doListsDatabaseUpdate(lists, localListIds, hasMergedLists)) {
            // database update failed, abort
            return false;
        }
    } while (// fetch next batch
    !TextUtils.isEmpty(cursor));
    // set new last sync time
    if (hasMergedLists) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(HexagonSettings.KEY_LAST_SYNC_LISTS, currentTime).apply();
    }
    return true;
}
Also used : SgList(com.uwetrottmann.seriesguide.backend.lists.model.SgList) SgListList(com.uwetrottmann.seriesguide.backend.lists.model.SgListList) Lists(com.uwetrottmann.seriesguide.backend.lists.Lists) IOException(java.io.IOException) DateTime(com.google.api.client.util.DateTime)

Example 19 with DateTime

use of com.google.api.client.util.DateTime in project SeriesGuide by UweTrottmann.

the class HexagonEpisodeSync method downloadChangedFlags.

/**
 * Downloads all episodes changed since the last time this was called and applies changes to
 * the database.
 */
public boolean downloadChangedFlags(@NonNull Map<Integer, Long> tmdbIdsToShowIds) {
    long currentTime = System.currentTimeMillis();
    SgRoomDatabase database = SgRoomDatabase.getInstance(context);
    DateTime lastSyncTime = new DateTime(HexagonSettings.getLastEpisodesSyncTime(context));
    Timber.d("downloadChangedFlags: since %s", lastSyncTime);
    List<SgCloudEpisode> episodes;
    String cursor = null;
    boolean hasMoreEpisodes = true;
    Map<Long, ShowLastWatchedInfo> showIdsToLastWatched = new HashMap<>();
    while (hasMoreEpisodes) {
        try {
            // get service each time to check if auth was removed
            Episodes episodesService = hexagonTools.getEpisodesService();
            if (episodesService == null) {
                return false;
            }
            Episodes.GetSgEpisodes request = episodesService.getSgEpisodes().setUpdatedSince(// use default server limit
            lastSyncTime);
            if (!TextUtils.isEmpty(cursor)) {
                request.setCursor(cursor);
            }
            SgCloudEpisodeList response = request.execute();
            if (response == null) {
                // we're done here
                Timber.d("downloadChangedFlags: response was null, done here");
                break;
            }
            episodes = response.getEpisodes();
            // check for more items
            if (response.getCursor() != null) {
                cursor = response.getCursor();
            } else {
                hasMoreEpisodes = false;
            }
        } catch (IOException | IllegalArgumentException e) {
            // Note: JSON parser may throw IllegalArgumentException.
            Errors.logAndReportHexagon("get updated episodes", e);
            return false;
        }
        if (episodes == null || episodes.size() == 0) {
            // nothing to do here
            break;
        }
        // build batch of episode flag updates
        ArrayList<SgEpisode2UpdateByNumber> batch = new ArrayList<>();
        for (SgCloudEpisode episode : episodes) {
            Integer showTmdbId = episode.getShowTmdbId();
            Long showId = tmdbIdsToShowIds.get(showTmdbId);
            if (showId == null) {
                // ignore, show not added on this device
                continue;
            }
            Integer watchedFlag = episode.getWatchedFlag();
            Integer playsOrNull = null;
            if (watchedFlag != null) {
                if (watchedFlag == EpisodeFlags.WATCHED) {
                    // Note: plays may be null for legacy data. Protect against invalid data.
                    if (episode.getPlays() != null && episode.getPlays() >= 1) {
                        playsOrNull = episode.getPlays();
                    } else {
                        playsOrNull = 1;
                    }
                } else {
                    // Skipped or not watched.
                    playsOrNull = 0;
                }
                // record the latest last watched time and episode ID for a show
                if (!EpisodeTools.isUnwatched(watchedFlag)) {
                    ShowLastWatchedInfo lastWatchedInfo = showIdsToLastWatched.get(showId);
                    // episodes returned in reverse chrono order, so just get the first time
                    if (lastWatchedInfo == null && episode.getUpdatedAt() != null) {
                        long updatedAtMs = episode.getUpdatedAt().getValue();
                        showIdsToLastWatched.put(showId, new ShowLastWatchedInfo(updatedAtMs, episode.getSeasonNumber(), episode.getEpisodeNumber()));
                    }
                }
            }
            batch.add(new SgEpisode2UpdateByNumber(showId, episode.getEpisodeNumber(), episode.getSeasonNumber(), watchedFlag, playsOrNull, episode.getIsInCollection()));
        }
        // execute database update
        database.sgEpisode2Helper().updateWatchedAndCollectedByNumber(batch);
    }
    if (!showIdsToLastWatched.isEmpty()) {
        // Note: it is possible that this overwrites a more recently watched episode,
        // however, the next sync should contain this episode and restore it.
        database.sgShow2Helper().updateLastWatchedMsIfLaterAndLastWatchedEpisodeId(showIdsToLastWatched, database.sgEpisode2Helper());
    }
    // store new last sync time
    PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(HexagonSettings.KEY_LAST_SYNC_EPISODES, currentTime).apply();
    return true;
}
Also used : SgCloudEpisode(com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisode) SgRoomDatabase(com.battlelancer.seriesguide.provider.SgRoomDatabase) HashMap(java.util.HashMap) SgCloudEpisodeList(com.uwetrottmann.seriesguide.backend.episodes.model.SgCloudEpisodeList) ArrayList(java.util.ArrayList) IOException(java.io.IOException) DateTime(com.google.api.client.util.DateTime) SgEpisode2UpdateByNumber(com.battlelancer.seriesguide.provider.SgEpisode2UpdateByNumber) Episodes(com.uwetrottmann.seriesguide.backend.episodes.Episodes)

Example 20 with DateTime

use of com.google.api.client.util.DateTime in project SeriesGuide by UweTrottmann.

the class HexagonShowSync method download.

/**
 * Downloads shows from Hexagon and updates existing shows with new property values. Any
 * shows not yet in the local database, determined by the given TMDB ID map, will be added
 * to the given map.
 *
 * When merging shows (e.g. just signed in) also downloads legacy cloud shows.
 */
public boolean download(Map<Integer, Long> tmdbIdsToShowIds, HashMap<Integer, SearchResult> toAdd, boolean hasMergedShows) {
    List<SgShow2CloudUpdate> updates = new ArrayList<>();
    Set<Long> toUpdate = new HashSet<>();
    long currentTime = System.currentTimeMillis();
    DateTime lastSyncTime = new DateTime(HexagonSettings.getLastShowsSyncTime(context));
    if (hasMergedShows) {
        Timber.d("download: changed shows since %s", lastSyncTime);
    } else {
        Timber.d("download: all shows");
    }
    boolean success = downloadShows(updates, toUpdate, toAdd, tmdbIdsToShowIds, hasMergedShows, lastSyncTime);
    if (!success)
        return false;
    // to encourage users to update the app.
    if (!hasMergedShows) {
        boolean successLegacy = downloadLegacyShows(updates, toUpdate, toAdd, tmdbIdsToShowIds);
        if (!successLegacy)
            return false;
    }
    // Apply all updates
    SgRoomDatabase.getInstance(context).sgShow2Helper().updateForCloudUpdate(updates);
    if (hasMergedShows) {
        // set new last sync time
        PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(HexagonSettings.KEY_LAST_SYNC_SHOWS, currentTime).apply();
    }
    return true;
}
Also used : ArrayList(java.util.ArrayList) SgShow2CloudUpdate(com.battlelancer.seriesguide.provider.SgShow2CloudUpdate) DateTime(com.google.api.client.util.DateTime) HashSet(java.util.HashSet)

Aggregations

DateTime (com.google.api.client.util.DateTime)41 Event (com.google.api.services.calendar.model.Event)13 EventDateTime (com.google.api.services.calendar.model.EventDateTime)13 IOException (java.io.IOException)12 ArrayList (java.util.ArrayList)10 Date (java.util.Date)9 Calendar (com.google.api.services.calendar.Calendar)8 Events (com.google.api.services.calendar.model.Events)7 File (com.google.api.services.drive.model.File)7 CalendarData (com.cloudcraftgaming.discal.api.object.calendar.CalendarData)6 SimpleDateFormat (java.text.SimpleDateFormat)6 Test (org.junit.Test)6 Map (java.util.Map)5 ParseException (java.text.ParseException)4 GuildSettings (com.cloudcraftgaming.discal.api.object.GuildSettings)3 EventData (com.cloudcraftgaming.discal.api.object.event.EventData)3 Recurrence (com.cloudcraftgaming.discal.api.object.event.Recurrence)3 WebGuild (com.cloudcraftgaming.discal.api.object.web.WebGuild)3 FileList (com.google.api.services.drive.model.FileList)3 StorageObject (com.google.api.services.storage.model.StorageObject)3