List of usage examples for org.joda.time DateTime getMillis
public long getMillis()
From source file:com.battlelancer.seriesguide.util.TimeTools.java
License:Apache License
private static DateTime applyUnitedStatesCorrections(@Nullable String country, @NonNull String localTimeZone, @NonNull DateTime dateTime) { // assumed base time zone for US shows by trakt is America/New_York // EST UTC5:00, EDT UTC4:00 // east feed (default): simultaneously in Eastern and Central // delayed 1 hour in Mountain // delayed three hours in Pacific // <==> // same local time in Eastern + Pacific (e.g. 20:00) // same local time in Central + Mountain (e.g. 19:00) // not a US show or no correction necessary (getting east feed) if (!ISO3166_1_UNITED_STATES.equals(country) || localTimeZone.equals(TIMEZONE_ID_US_EASTERN) || localTimeZone.equals(TIMEZONE_ID_US_EASTERN_DETROIT) || localTimeZone.equals(TIMEZONE_ID_US_CENTRAL)) { return dateTime; }/*from w w w . j ava 2 s . com*/ int offset = 0; if (localTimeZone.equals(TIMEZONE_ID_US_MOUNTAIN)) { // MST UTC7:00, MDT UTC6:00 offset += 1; } else if (localTimeZone.equals(TIMEZONE_ID_US_ARIZONA)) { // is always UTC-07:00, so like Mountain, but no DST boolean noDstInEastern = DateTimeZone.forID(TIMEZONE_ID_US_EASTERN) .isStandardOffset(dateTime.getMillis()); if (noDstInEastern) { offset += 1; } else { offset += 2; } } else if (localTimeZone.equals(TIMEZONE_ID_US_PACIFIC)) { // PST UTC8:00 or PDT UTC7:00 offset += 3; } dateTime = dateTime.plusHours(offset); return dateTime; }
From source file:com.battlelancer.seriesguide.util.TraktTask.java
License:Apache License
@Override protected Response doInBackground(Void... params) { // we need this value in onPostExecute, so preserve it here mAction = TraktAction.valueOf(mArgs.getString(InitBundle.TRAKTACTION)); // check for network connection if (!AndroidUtils.isNetworkConnected(mContext)) { Response r = new Response(); r.status = TraktStatus.FAILURE;//from ww w. j a v a2s. co m r.error = mContext.getString(R.string.offline); return r; } // get authenticated trakt TraktV2 trakt = ServiceUtils.getTraktV2WithAuth(mContext); if (trakt == null) { // no valid credentials Response r = new Response(); r.status = TraktStatus.FAILURE; r.error = mContext.getString(R.string.trakt_error_credentials); return r; } // last chance to abort if (isCancelled()) { return null; } Response r = null; try { switch (mAction) { case CHECKIN_EPISODE: case CHECKIN_MOVIE: { return doCheckInAction(trakt.checkin()); } case COMMENT: { return doCommentAction(trakt.comments()); } } } catch (RetrofitError e) { Timber.e(e, mAction.toString() + " failed"); r = new Response(); r.status = TraktStatus.FAILURE; r.error = mContext.getString(R.string.trakt_error_general); } catch (OAuthUnauthorizedException e) { TraktCredentials.get(mContext).setCredentialsInvalid(); r = new Response(); r.status = TraktStatus.FAILURE; r.error = mContext.getString(R.string.trakt_error_credentials); } catch (CheckinInProgressException e) { CheckinResponse checkinResponse = new CheckinResponse(); checkinResponse.status = TraktStatus.FAILURE; DateTime expiresAt = e.getExpiresAt(); checkinResponse.wait = expiresAt == null ? -1 : (int) ((expiresAt.getMillis() - System.currentTimeMillis()) / 1000); r = checkinResponse; } return r; }
From source file:com.battlelancer.seriesguide.util.TraktTools.java
License:Apache License
/** * Downloads trakt movie watched flags and mirrors them in the local database. Does NOT upload * any flags (e.g. trakt is considered the truth). *//*ww w. jav a 2 s .c o m*/ public static UpdateResult downloadWatchedMovies(Context context, DateTime watchedAt) { if (watchedAt == null) { Timber.e("downloadWatchedMovies: null watched_at"); return UpdateResult.INCOMPLETE; } long lastWatchedAt = TraktSettings.getLastMoviesWatchedAt(context); if (!watchedAt.isAfter(lastWatchedAt)) { // not initial sync, no watched flags have changed Timber.d("downloadWatchedMovies: no changes since " + lastWatchedAt); return UpdateResult.SUCCESS; } TraktV2 trakt = ServiceUtils.getTraktV2WithAuth(context); if (trakt == null) { return UpdateResult.INCOMPLETE; } // download watched movies List<BaseMovie> watchedMovies; try { watchedMovies = trakt.sync().watchedMovies(Extended.DEFAULT_MIN); } catch (RetrofitError e) { Timber.e(e, "downloadWatchedMovies: download failed"); return UpdateResult.INCOMPLETE; } catch (OAuthUnauthorizedException e) { TraktCredentials.get(context).setCredentialsInvalid(); return UpdateResult.INCOMPLETE; } if (watchedMovies == null) { Timber.e("downloadWatchedMovies: null response"); return UpdateResult.INCOMPLETE; } if (watchedMovies.isEmpty()) { Timber.d("downloadWatchedMovies: no watched movies on trakt"); return UpdateResult.SUCCESS; } // apply watched flags for all watched trakt movies that are in the local database ArrayList<ContentProviderOperation> batch = new ArrayList<>(); Set<Integer> localMovies = MovieTools.getMovieTmdbIdsAsSet(context); if (localMovies == null) { return UpdateResult.INCOMPLETE; } Set<Integer> unwatchedMovies = new HashSet<>(localMovies); for (BaseMovie movie : watchedMovies) { if (movie.movie == null || movie.movie.ids == null || movie.movie.ids.tmdb == null) { // required values are missing continue; } if (!localMovies.contains(movie.movie.ids.tmdb)) { // movie NOT in local database // add a shell entry for storing watched state batch.add(ContentProviderOperation.newInsert(SeriesGuideContract.Movies.CONTENT_URI) .withValue(SeriesGuideContract.Movies.TMDB_ID, movie.movie.ids.tmdb) .withValue(SeriesGuideContract.Movies.WATCHED, true) .withValue(SeriesGuideContract.Movies.IN_COLLECTION, false) .withValue(SeriesGuideContract.Movies.IN_WATCHLIST, false).build()); } else { // movie IN local database // set movie watched batch.add(ContentProviderOperation .newUpdate(SeriesGuideContract.Movies.buildMovieUri(movie.movie.ids.tmdb)) .withValue(SeriesGuideContract.Movies.WATCHED, true).build()); unwatchedMovies.remove(movie.movie.ids.tmdb); } } // remove watched flags from all remaining local movies for (Integer tmdbId : unwatchedMovies) { batch.add(ContentProviderOperation.newUpdate(SeriesGuideContract.Movies.buildMovieUri(tmdbId)) .withValue(SeriesGuideContract.Movies.WATCHED, false).build()); } // apply database updates try { DBUtils.applyInSmallBatches(context, batch); } catch (OperationApplicationException e) { Timber.e(e, "downloadWatchedMovies: updating watched flags failed"); return UpdateResult.INCOMPLETE; } // save last watched instant PreferenceManager.getDefaultSharedPreferences(context).edit() .putLong(TraktSettings.KEY_LAST_MOVIES_WATCHED_AT, watchedAt.getMillis()).commit(); Timber.d("downloadWatchedMovies: success, last watched_at " + watchedAt.getMillis()); return UpdateResult.SUCCESS; }
From source file:com.battlelancer.seriesguide.util.TraktTools.java
License:Apache License
/** * Downloads trakt movie ratings and applies the latest ones to the database. * * <p> To apply all ratings, set {@link TraktSettings#KEY_LAST_MOVIES_RATED_AT} to 0. *//*from w w w. j a v a 2 s. c o m*/ public static UpdateResult downloadMovieRatings(Context context, DateTime ratedAt) { if (ratedAt == null) { Timber.e("downloadMovieRatings: null rated_at"); return UpdateResult.INCOMPLETE; } long lastRatedAt = TraktSettings.getLastMoviesRatedAt(context); if (!ratedAt.isAfter(lastRatedAt)) { // not initial sync, no ratings have changed Timber.d("downloadMovieRatings: no changes since " + lastRatedAt); return UpdateResult.SUCCESS; } TraktV2 trakt = ServiceUtils.getTraktV2WithAuth(context); if (trakt == null) { return UpdateResult.INCOMPLETE; } // download rated shows List<RatedMovie> ratedMovies; try { ratedMovies = trakt.sync().ratingsMovies(RatingsFilter.ALL, Extended.DEFAULT_MIN); } catch (RetrofitError e) { Timber.e(e, "downloadMovieRatings: download failed"); return UpdateResult.INCOMPLETE; } catch (OAuthUnauthorizedException e) { TraktCredentials.get(context).setCredentialsInvalid(); return UpdateResult.INCOMPLETE; } if (ratedMovies == null) { Timber.e("downloadMovieRatings: null response"); return UpdateResult.INCOMPLETE; } if (ratedMovies.isEmpty()) { Timber.d("downloadMovieRatings: no ratings on trakt"); return UpdateResult.SUCCESS; } // trakt last activity rated_at timestamp is set after the rating timestamp // so include ratings that are a little older long ratedAtThreshold = lastRatedAt - 5 * DateUtils.MINUTE_IN_MILLIS; // go through ratings, latest first (trakt sends in that order) ArrayList<ContentProviderOperation> batch = new ArrayList<>(); for (RatedMovie movie : ratedMovies) { if (movie.rating == null || movie.movie == null || movie.movie.ids == null || movie.movie.ids.tmdb == null) { // skip, can't handle continue; } if (movie.rated_at != null && movie.rated_at.isBefore(ratedAtThreshold)) { // no need to apply older ratings again break; } // if a movie does not exist, this update will do nothing ContentProviderOperation op = ContentProviderOperation .newUpdate(SeriesGuideContract.Movies.buildMovieUri(movie.movie.ids.tmdb)) .withValue(SeriesGuideContract.Movies.RATING_USER, movie.rating.value).build(); batch.add(op); } // apply database updates try { DBUtils.applyInSmallBatches(context, batch); } catch (OperationApplicationException e) { Timber.e(e, "downloadMovieRatings: database update failed"); return UpdateResult.INCOMPLETE; } // save last rated instant PreferenceManager.getDefaultSharedPreferences(context).edit() .putLong(TraktSettings.KEY_LAST_MOVIES_RATED_AT, ratedAt.getMillis()).commit(); Timber.d("downloadMovieRatings: success, last rated_at " + ratedAt.getMillis()); return UpdateResult.SUCCESS; }
From source file:com.bazaarvoice.dropwizard.caching.memcached.MemcachedResponseStore.java
License:Apache License
@Override public void put(String key, CachedResponse response) { checkNotNull(key);/*from w ww . j a v a2s . co m*/ checkArgument(key.length() > 0, "key can not be empty"); checkNotNull(response); if (!_readOnly) { DateTime expires = response.getExpires().orNull(); if (expires != null) { _client.set(buildKey(key), (int) (expires.getMillis() / 1000), response, CachedResponseTranscoder.INSTANCE); } } }
From source file:com.bearded.common.time.TimeUtils.java
License:Apache License
/** * Obtains the number of milliseconds from a given {@link DateTime} * * @param dateTime that will be used to calculate the difference. * @return {@link long} with the number of milliseconds. *///from w w w .j a v a 2s . c o m public static long millisecondsFromNow(@NonNull DateTime dateTime) { return millisecondsFromNow(dateTime.getMillis()); }
From source file:com.bearded.common.time.TimeUtils.java
License:Apache License
/** * Convert a given timestamp into ISO 8601 {@link java.lang.String} * * @param datetime that will be converted to the ISO 8601 convention. * @return {@link java.lang.String} with the date in seconds following the ISO 8601 conventions. *///w w w. ja v a 2s.c o m @NonNull public static String timestampToISOString(@NonNull DateTime datetime) { return timestampToISOString(datetime.getMillis()); }
From source file:com.bitbreeds.webrtc.sctp.impl.HeartBeatService.java
License:Open Source License
/** * Calculates RTT value//from w w w . jav a 2 s . c o m * Resets shutdown timers * * @param heartBeatInfo from ack */ public void receiveHeartBeatAck(byte[] heartBeatInfo) { UUID uuid = new UUID(bytesToLong(copyRange(heartBeatInfo, new ByteRange(0, 8))), bytesToLong(copyRange(heartBeatInfo, new ByteRange(8, 16)))); DateTime time = rttMap.get(uuid); if (time == null) { throw new IllegalArgumentException("Ack with unkown uuid: " + uuid + " map contains: " + rttMap); } else { rttMillis = DateTime.now().getMillis() - time.getMillis(); synchronized (mutex) { rttMap = rttMap.minus(uuid); } } }
From source file:com.bluexml.xforms.controller.mapping.MappingToolCommon.java
License:Open Source License
/** * Gets the date time from date and time. * /*from w w w . jav a2 s .com*/ * @param date * the date * @param time * the time * @return the date time from date and time */ protected String getDateTimeFromDateAndTime(String date, String time) { DateTime rdate = new DateTime(DatatypeConverter.parseDate(date)); DateTime rtime = new DateTime(DatatypeConverter.parseTime(time)); long millis = rdate.getMillis() - rdate.getMillisOfDay() + rtime.getMillisOfDay(); return DateTimeConverter.convert_XFormsToAlfresco_DateTime(millis); }
From source file:com.boha.golfkids.util.NewGolfGroupUtil.java
private static void generateExampleTournament(boolean isLive, GolfGroup gg, List<Player> pList, int clubID, String tournamentName, int rounds, boolean useAgeGroups, int holesPerRound, int gender, DataUtil dataUtil, PlatformUtil platformUtil) throws DataException { DateTime dt = new DateTime(); dt = dt.minusDays(7);/* w ww.j av a2 s . com*/ // TournamentDTO t = new TournamentDTO(); t.setTourneyName(tournamentName); t.setGolfRounds(rounds); t.setStartDate(dt.getMillis()); t.setClubID(clubID); t.setGolfGroupID(gg.getGolfGroupID()); t.setHolesPerRound(holesPerRound); t.setExampleFlag(1); t.setTournamentType(RequestDTO.STROKE_PLAY_INDIVIDUAL); if (holesPerRound == 9) { t.setPar(36); } else { t.setPar(72); } if (rounds > 1) { for (int i = 0; i < rounds; i++) { dt = dt.plusDays(i); } t.setEndDate(dt.getMillis()); } else { t.setEndDate(t.getStartDate()); } if (useAgeGroups) { t.setUseAgeGroups(1); } ResponseDTO r = dataUtil.addTournament(t, platformUtil); Tournament tournament = new Tournament(); List<TournamentDTO> tList = r.getTournaments(); for (TournamentDTO tn : tList) { if (tn.getTourneyName().equalsIgnoreCase(t.getTourneyName())) { tournament = dataUtil.getTournamentByID(tn.getTournamentID()); break; } } List<LeaderBoard> list = addPlayersToTournament(pList, tournament, gender, dataUtil, platformUtil); log.log(Level.INFO, "LeaderBoard items generated, about to score: {0}", list.size()); List<TourneyScoreByRound> tsbrList = generateScores(list, tournament.getTournamentID(), dataUtil, tournament.getGolfRounds()); if (isLive) { generateScoresForLiveLeaderBoard(tsbrList, list, tournament, dataUtil, rounds); } log.log(Level.OFF, "Sample Tournament generated: {0} - {1}", new Object[] { gg.getGolfGroupName(), tournamentName }); }