下面列出了怎么用org.joda.time.Seconds的API类实例代码及写法,或者点击链接到github查看源代码。
protected static int dateDiff(Date beginDate, Date endDate, DateType type) {
//Interval interval = new Interval(beginDate.getTime(), endDate.getTime());
//Period p = interval.toPeriod();
DateTime start =new DateTime(beginDate);
DateTime end =new DateTime(endDate);
if (DateType.YEAR.equals(endDate)) {
return Years.yearsBetween(start, end).getYears();
} else if (DateType.MONTH.equals(type)) {
return Months.monthsBetween(start, end).getMonths();
} else if (DateType.WEEK.equals(type)) {
return Weeks.weeksBetween(start, end).getWeeks();
} else if (DateType.DAY.equals(type)) {
return Days.daysBetween(start, end).getDays();
} else if (DateType.HOUR.equals(type)) {
return Hours.hoursBetween(start, end).getHours();
} else if (DateType.MINUTE.equals(type)) {
return Minutes.minutesBetween(start, end).getMinutes();
} else if (DateType.SECOND.equals(type)) {
return Seconds.secondsBetween(start, end).getSeconds();
} else {
return 0;
}
}
/**
* Repeatedly pull messages from {@link #subscriptionPath()}, returns after receiving {@code n}
* messages or after waiting for {@code timeoutDuration}.
*/
public List<PubsubMessage> waitForNMessages(int n, Duration timeoutDuration)
throws IOException, InterruptedException {
List<PubsubMessage> receivedMessages = new ArrayList<>(n);
DateTime startTime = new DateTime();
int timeoutSeconds = timeoutDuration.toStandardSeconds().getSeconds();
receivedMessages.addAll(pull(n - receivedMessages.size()));
while (receivedMessages.size() < n
&& Seconds.secondsBetween(startTime, new DateTime()).getSeconds() < timeoutSeconds) {
Thread.sleep(1000);
receivedMessages.addAll(pull(n - receivedMessages.size()));
}
return receivedMessages;
}
/**
* Check if topics exist.
*
* @param project GCP project identifier.
* @param timeoutDuration Joda duration that sets a period of time before checking times out.
*/
public void checkIfAnySubscriptionExists(String project, Duration timeoutDuration)
throws InterruptedException, IllegalArgumentException, IOException, TimeoutException {
if (timeoutDuration.getMillis() <= 0) {
throw new IllegalArgumentException(String.format("timeoutDuration should be greater than 0"));
}
DateTime startTime = new DateTime();
int sizeOfSubscriptionList = 0;
while (sizeOfSubscriptionList == 0
&& Seconds.secondsBetween(new DateTime(), startTime).getSeconds()
< timeoutDuration.toStandardSeconds().getSeconds()) {
// Sleep 1 sec
Thread.sleep(1000);
sizeOfSubscriptionList =
listSubscriptions(projectPathFromPath(String.format("projects/%s", project)), topicPath())
.size();
}
if (sizeOfSubscriptionList > 0) {
return;
} else {
throw new TimeoutException("Timed out when checking if topics exist for " + topicPath());
}
}
@Test
public void testFormatSecondsByPeriod15M() throws ParseException {
Period period = new Period("PT15m");
Seconds seconds = period.toStandardSeconds();
Assert.assertEquals(15*60,seconds.getSeconds());
long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:12");
long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:45:00");
long result = UserProfileUtils.formatSecondsByPeriod(time,seconds);
Assert.assertEquals(expect,result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect,result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect,result);
}
@Test
public void testFormatSecondsByPeriod1H() throws ParseException {
Period period = new Period("PT1h");
Seconds seconds = period.toStandardSeconds();
Assert.assertEquals(60*60,seconds.getSeconds());
long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:12");
long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:00:00");
long result = UserProfileUtils.formatSecondsByPeriod(time,seconds);
Assert.assertEquals(expect,result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect,result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:30:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = UserProfileUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect,result);
}
@Test
public void testFormatSecondsByPeriod15M() throws ParseException {
Period period = new Period("PT15m");
Seconds seconds = period.toStandardSeconds();
Assert.assertEquals(15 * 60, seconds.getSeconds());
long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:12");
long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:45:00");
long result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect, result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect, result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect, result);
}
@Test
public void testFormatSecondsByPeriod1H() throws ParseException {
Period period = new Period("PT1h");
Seconds seconds = period.toStandardSeconds();
Assert.assertEquals(60 * 60, seconds.getSeconds());
long time = DateTimeUtil.humanDateToSeconds("2015-07-01 13:56:12");
long expect = DateTimeUtil.humanDateToSeconds("2015-07-01 13:00:00");
long result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect, result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:14:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect, result);
time = DateTimeUtil.humanDateToSeconds("2015-07-01 03:30:59");
expect = DateTimeUtil.humanDateToSeconds("2015-07-01 03:00:00");
result = TimePeriodUtils.formatSecondsByPeriod(time, seconds);
Assert.assertEquals(expect, result);
}
private static String dateToAge(String createdAt, DateTime now) {
if (createdAt == null) {
return "";
}
DateTimeFormatter dtf = DateTimeFormat.forPattern(DATE_TIME_FORMAT);
try {
DateTime created = dtf.parseDateTime(createdAt);
if (Seconds.secondsBetween(created, now).getSeconds() < 60) {
return Seconds.secondsBetween(created, now).getSeconds() + "s";
} else if (Minutes.minutesBetween(created, now).getMinutes() < 60) {
return Minutes.minutesBetween(created, now).getMinutes() + "m";
} else if (Hours.hoursBetween(created, now).getHours() < 24) {
return Hours.hoursBetween(created, now).getHours() + "h";
} else {
return Days.daysBetween(created, now).getDays() + "d";
}
} catch (IllegalArgumentException e) {
return "";
}
}
@Override
@SuppressWarnings("EqualsBetweenInconvertibleTypes") // SpecimenType knows how to do equals(Class<?>)
public Object create(Object request, SpecimenContext context) {
if (!(request instanceof SpecimenType)) {
return new NoSpecimen();
}
SpecimenType type = (SpecimenType) request;
if (!BaseSingleFieldPeriod.class.isAssignableFrom(type.getRawType())) {
return new NoSpecimen();
}
Duration duration = (Duration) context.resolve(Duration.class);
if (type.equals(Seconds.class)) return Seconds.seconds(Math.max(1, (int) duration.getStandardSeconds()));
if (type.equals(Minutes.class)) return Minutes.minutes(Math.max(1, (int) duration.getStandardMinutes()));
if (type.equals(Hours.class)) return Hours.hours(Math.max(1, (int) duration.getStandardHours()));
if (type.equals(Days.class)) return Days.days(Math.max(1, (int) duration.getStandardDays()));
if (type.equals(Weeks.class)) return Weeks.weeks(Math.max(1, (int) duration.getStandardDays() / 7));
if (type.equals(Months.class)) return Months.months(Math.max(1, (int) duration.getStandardDays() / 30));
if (type.equals(Years.class)) return Years.years(Math.max(1, (int) duration.getStandardDays() / 365));
return new NoSpecimen();
}
private String prepareDate(Date date){
DateTime busTimestamp = new DateTime(date);
DateTime now = new DateTime(Calendar.getInstance());
int time = Seconds.secondsBetween(busTimestamp, now).getSeconds();
if(time < 60) return context.getString(R.string.marker_seconds, String.valueOf(time));
time = Minutes.minutesBetween(busTimestamp, now).getMinutes();
if(time < 60) return context.getString(R.string.marker_minutes, String.valueOf(time));
time = Hours.hoursBetween(busTimestamp, now).getHours();
if(time < 24) return context.getString(R.string.marker_hours, String.valueOf(time));
time = Days.daysBetween(busTimestamp, now).getDays();
return context.getString(R.string.marker_days, String.valueOf(time));
}
private Map<String, Object> buildFields(FlowLogMessage msg) {
return new HashMap<String, Object>() {{
put("account_id", msg.getAccountId());
put("interface_id", msg.getInterfaceId());
put("src_addr", msg.getSourceAddress());
put("dst_addr", msg.getDestinationAddress());
put("src_port", msg.getSourcePort());
put("dst_port", msg.getDestinationPort());
put("protocol_number", msg.getProtocolNumber());
put("protocol", protocolNumbers.lookup(msg.getProtocolNumber()));
put("packets", msg.getPackets());
put("bytes", msg.getBytes());
put("capture_window_duration_seconds", Seconds.secondsBetween(msg.getCaptureWindowStart(), msg.getCaptureWindowEnd()).getSeconds());
put("action", msg.getAction());
put("log_status", msg.getLogStatus());
}};
}
@Test
public void difference_between_two_dates_joda () {
DateTime sinceGraduation = new DateTime(1984, 6, 4, 0, 0, GregorianChronology.getInstance());
DateTime currentDate = new DateTime(); //current date
Days diffInDays = Days.daysBetween(sinceGraduation, currentDate);
Hours diffInHours = Hours.hoursBetween(sinceGraduation, currentDate);
Minutes diffInMinutes = Minutes.minutesBetween(sinceGraduation, currentDate);
Seconds seconds = Seconds.secondsBetween(sinceGraduation, currentDate);
logger.info(diffInDays.getDays());
logger.info(diffInHours.getHours());
logger.info(diffInMinutes.getMinutes());
logger.info(seconds.getSeconds());
assertTrue(diffInDays.getDays() >= 10697);
assertTrue(diffInHours.getHours() >= 256747);
assertTrue(diffInMinutes.getMinutes() >= 15404876);
assertTrue(seconds.getSeconds() >= 924292577);
}
/**
* Adding this wait as the Sybase ASE logs can fill up quickly if you execute a lot of DDLs
* Hence, we put in a periodic check (currently going by every "maxLogCounter" updates executed)
* to see if the log level exceeds a "stopLogSpaceThreshold". If so, we wait till it gets back
* down to a "resumeLogSpaceThreshold"
*/
private void waitForLogSpace(Connection conn, JdbcHelper jdbc) {
this.curLogCounter.incrementAndGet();
// only trigger the check every "maxLogCounter" checks
if (this.curLogCounter.get() == maxLogCounter) {
boolean firstTime = true;
while (true) {
int percentFull = getPercentLogFullInDb(conn, jdbc);
int thresholdToCheck = firstTime ? stopLogSpaceThreshold : resumeLogSpaceThreshold;
firstTime = false;
if (percentFull < thresholdToCheck) {
break;
} else {
try {
Seconds seconds = Seconds.seconds(3);
LOG.info(String
.format("Pausing for %d seconds as the log level hit a high mark of %d; will resume when it gets back to %d",
seconds.getSeconds(), percentFull, resumeLogSpaceThreshold));
Thread.sleep(seconds.getSeconds() * 1000);
} catch (InterruptedException e) {
throw new DeployerRuntimeException(e);
}
}
}
this.curLogCounter.set(0); // reset the log counter after doing the check
} else if (this.curLogCounter.get() > maxLogCounter) {
// in this case, some concurrent execution caused the ID to exceed the maxLogCounter. In this case, just
// reset the counter to 0 (the thread that has the counter at the right value would execute this code
this.curLogCounter.set(0);
}
}
private void formatSeconds(DateTime now, DateTime then, StringBuilder text) {
int secondsBetween = Seconds.secondsBetween(now.toLocalTime(), then.toLocalTime()).getSeconds();
if (secondsBetween == 0) {
text.append(context.getString(R.string.now));
} else if (secondsBetween > 0) { // in N seconds
text.append(context.getResources().getQuantityString(R.plurals.carbon_inSeconds, secondsBetween, secondsBetween));
} else { // N seconds ago
text.append(context.getResources().getQuantityString(R.plurals.carbon_secondsAgo, -secondsBetween, -secondsBetween));
}
}
/**
* Set the year to the date of event
*/
public void setYear(int year) {
int secondsBetweenStartAndStop = Seconds.secondsBetween(
new DateTime(dateStart),
new DateTime(dateStop))
.getSeconds();
dateStart = new DateTime(dateStart).withYear(year).toDate();
dateStop = new DateTime(dateStart).plusSeconds(secondsBetweenStartAndStop).toDate();
}
@Test
public void testBetween(){
Date start = DateUtils.parse("2016-12-06 17:35:30");
Date end = DateUtils.parse("2016-12-06 17:35:33");
Period period = JodatimeUtils.between(start, end);
assertThat(period.getSeconds(), equalTo(Seconds.THREE.getSeconds()));
assertThat(Seconds.secondsBetween(new LocalDateTime(start), new LocalDateTime(end)), equalTo(Seconds.THREE));
}
public void on(DateTime instant, Runnable runnable) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("schedule runnable[%s] on %s", runnable, instant);
}
DateTime now = DateTime.now();
E.illegalArgumentIf(instant.isBefore(now));
Seconds seconds = Seconds.secondsBetween(now, instant);
executor().schedule(wrap(runnable), seconds.getSeconds(), TimeUnit.SECONDS);
}
public <T> Future<T> on(DateTime instant, Callable<T> callable) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("schedule callable[%s] on %s", callable, instant);
}
DateTime now = DateTime.now();
E.illegalArgumentIf(instant.isBefore(now));
Seconds seconds = Seconds.secondsBetween(now, instant);
return executor().schedule(callable, seconds.getSeconds(), TimeUnit.SECONDS);
}
private void delayedSchedule(JobManager manager, Job job) {
DateTime now = DateTime.now();
// add one seconds to prevent the next time be the current time (now)
DateTime next = cronExpr.nextTimeAfter(now.plusSeconds(1));
Seconds seconds = Seconds.secondsBetween(now, next);
ScheduledFuture future = manager.executor().schedule(job, seconds.getSeconds(), TimeUnit.SECONDS);
manager.futureScheduled(job.id(), future);
}
@TLFunctionAnnotation("Returns the difference between dates")
public static final Long dateDiff(TLFunctionCallContext context, Date lhs, Date rhs, DateFieldEnum unit) {
if (unit == DateFieldEnum.MILLISEC) { // CL-1087
return lhs.getTime() - rhs.getTime();
}
long diff = 0;
switch (unit) {
case SECOND:
// we have the difference in seconds
diff = (long) Seconds.secondsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getSeconds();
break;
case MINUTE:
// how many minutes'
diff = (long) Minutes.minutesBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getMinutes();
break;
case HOUR:
diff = (long) Hours.hoursBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getHours();
break;
case DAY:
// how many days is the difference
diff = (long) Days.daysBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getDays();
break;
case WEEK:
// how many weeks
diff = (long) Weeks.weeksBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getWeeks();
break;
case MONTH:
diff = (long) Months.monthsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getMonths();
break;
case YEAR:
diff = (long) Years.yearsBetween(new DateTime(rhs.getTime()), new DateTime(lhs.getTime())).getYears();
break;
default:
throw new TransformLangExecutorRuntimeException("Unknown time unit " + unit);
}
return diff;
}
protected boolean equalDates(DateTime expected, DateTime result, int eps) {
if (expected == null && result == null) {
return true;
}
int diff = Seconds.secondsBetween(expected, result).getSeconds();
return Math.abs(diff) <= eps;
}
public ConvertedTime getConvertedTime(long duration) {
Set<Seconds> keys = RULES.keySet();
for (Seconds seconds : keys) {
if (duration <= seconds.getSeconds()) {
return RULES.get(seconds).getConvertedTime(duration);
}
}
return new TimeConverter.OverTwoYears().getConvertedTime(duration);
}
@Transactional(readOnly = true)
@Secured("AFTER_ACL_COLLECTION_READ")
public SchedulerJob[] getActiveSchedulerJobs() {
List<SchedulerJob> activeJobs = new ArrayList<SchedulerJob>();
SchedulerJob[] schedulerJobs = getSchedulerJobs();
for (SchedulerJob job : schedulerJobs) {
boolean active = false;
Date now = new Date();
if (ScheduleConstants.ONCE_TYPE.equals(job.getTime().getType())) {
active = (job.getTime().getRunDate().compareTo(now) >= 0) || job.isRunning();
} else {
active = ((job.getTime().getStartActivationDate().compareTo(now) <= 0) &&
(job.getTime().getEndActivationDate().compareTo(now) >= 0)) || job.isRunning();
}
if (active) {
activeJobs.add(job);
Map<String, JobExecutionContext> runningJobs;
try {
runningJobs = QuartzUtil.getRunningJobs(scheduler);
} catch (SchedulerException e) {
throw new RuntimeException(e);
}
JobExecutionContext executionContext = runningJobs.get(job.getPath());
if (executionContext != null) {
Date fireTime = executionContext.getFireTime();
job.setRunTime(Seconds.secondsBetween(new DateTime(fireTime), new DateTime()).getSeconds());
}
}
}
schedulerJobs = activeJobs.toArray(new SchedulerJob[activeJobs.size()]);
return schedulerJobs;
}
/**
* Handles "GetMetricStatistics" request, as simple as without any filters
* to use.
*
* @param statistics
* Metric statistics.
* @param startTime
* Metric statistics start time.
* @param endTime
* Metric statistics end time.
* @param period
* Metric collection period.
* @param metricName
* Metric Name.
* @return a GetMetricStatisticsResult for metricName.
*/
private GetMetricStatisticsResponse getMetricStatistics(final String[] statistics,
final DateTime startTime,
final DateTime endTime, final int period, final String metricName) {
GetMetricStatisticsResponse ret = new GetMetricStatisticsResponse();
GetMetricStatisticsResult result = new GetMetricStatisticsResult();
Datapoints dataPoints = new Datapoints();
int dataPointsCount = Seconds.secondsBetween(startTime, endTime).getSeconds() / period;
DateTime newDate = startTime;
for (int counterDp = 0; counterDp < dataPointsCount; counterDp++) {
Datapoint dp = new Datapoint();
DateTime timeStamp = newDate.plusSeconds(period);
XMLGregorianCalendar timeStampXml = toXMLGregorianCalendar(timeStamp);
dp.setTimestamp(timeStampXml);
dp.setAverage(getMetricAverageValue(metricName));
dp.setSampleCount(getMetricSampleCountValue(metricName));
dp.setUnit(getMetricUnit(metricName));
dataPoints.getMember().add(dp);
newDate = timeStamp;
}
result.setDatapoints(dataPoints);
result.setLabel(metricName);
ret.setGetMetricStatisticsResult(result);
ResponseMetadata responseMetadata = new ResponseMetadata();
responseMetadata.setRequestId(UUID.randomUUID().toString());
ret.setResponseMetadata(responseMetadata);
return ret;
}
private static Seconds secondsBetween(ReadableInstant start, ReadableInstant end)
{
return Seconds.secondsBetween(start, end);
}
protected static int getRemainingTime() {
DateTime now = DateTime.now();
Seconds pastTime = Seconds.secondsBetween(Context.getStartCurrentScenario(), now);
int totalTimecalculated = pastTime.getSeconds() * Context.getDataInputProvider().getNbGherkinExample() / Context.getCurrentScenarioData();
return totalTimecalculated - pastTime.getSeconds();
}
@Override
public void serialize(Duration value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(FORMATTER.print(Seconds.seconds(value.seconds.intValue())));
}
private MessageProcessingResult ensureInstanceCreated(NotificationEvent event) throws Exception {
String instanceId = event.getDetail().getInstanceId();
StopWatch watch = new StopWatch();
watch.start();
MessageProcessingResult result = new MessageProcessingResult(event);
result.setSucceed(true);
try {
//Get EC2 instance
Instance inst = cloudInstanceStore.getInstance(instanceId);
if (inst != null) {
//Create the corresponding EsInstance
EsInstance esInstance = esInstanceFactory.createFromEC2(inst);
long version = cmdbInstanceStore.updateOrInsertInstance(esInstance);
if (version == 0) {
logger.info("Instance {} is created", instanceId);
//Created in ES
DateTime utcNow = DateTime.now(DateTimeZone.UTC);
DateTime enqueueTime = new DateTime(event.getSqsSentTime(), DateTimeZone.UTC);
int sinceEnqueued = Seconds.secondsBetween(enqueueTime, utcNow).getSeconds();
int
sinceLaunched =
Seconds.secondsBetween(new DateTime(esInstance.getAwsLaunchTime()), utcNow)
.getSeconds();
//First time instance created
Stats.addMetric(StatsUtil.getStatsName("ec2_creation", "since_enqueued"),
sinceEnqueued > 0 ? sinceEnqueued : 0);
Stats.addMetric(StatsUtil.getStatsName("ec2_creation", "since_launched"),
sinceLaunched > 0 ? sinceLaunched : 0);
} else {
logger.info("Instance {} is updated", instanceId);
}
logger.info("Create Instance {} in ElasticSearch", instanceId);
onInstanceCreation(esInstance, result);
Tag nameTag = AwsUtilities.getAwsTag(inst, "Name");
if (nameTag == null) {
result.setError(MessageProcessingResult.MessageProcessingError.NO_NAME_TAG);
} else if (State.PENDING.name().equalsIgnoreCase(esInstance.getState())) {
//Still pending. Put back to the queue and wait it into running
result.setError(MessageProcessingResult.MessageProcessingError.STILL_PENDING);
} else {
onInstanceCreation(esInstance, result);
}
try {
syncWithDailySnapshot(event, esInstance);
} catch (Exception ex) {
logger.error("Failed to sync with daily snapshot {} with error {}", instanceId,
ex.getMessage());
}
} else {
result.setError(MessageProcessingResult.MessageProcessingError.NOT_EXIST_IN_EC_2);
}
return result;
} finally {
watch.stop();
result.setDuration(watch.getTime());
}
}
private boolean shouldWeNotify(StatusBarNotification sbn) {
String source = sbn.getPackageName();
Notification notification = sbn.getNotification();
if ((notification.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT) {
return false;
}
/* do not display messages from "android"
* This includes keyboard selection message, usb connection messages, etc
* Hope it does not filter out too much, we will see...
*/
if (source.equals("android") ||
source.equals("com.android.systemui") ||
source.equals("com.android.dialer") ||
source.equals("com.android.mms") ||
source.equals("com.cyanogenmod.eleven") ||
source.equals("com.fsck.k9") ||
source.startsWith("com.motorola")) {
return false;
}
App app = AppsSQLite.getInstance(NotificationListener.this).getApp(source);
boolean passedTime = isAppInQueue(source);
if(!passedTime) {
if (lastNotificationMillis != -1) {
if (Seconds.secondsBetween(new DateTime(lastNotificationMillis), new DateTime(System.currentTimeMillis())).getSeconds() < 5) {
passedTime = false;
} else {
lastNotificationMillis = System.currentTimeMillis();
}
} else {
lastNotificationMillis = System.currentTimeMillis();
}
}
Log.i(TAG, "passedTime: " + passedTime);
if (app != null) {
Log.i(TAG, "app.shouldWeNotify(): " + app.shouldWeNotify());
}
return !passedTime && app != null && app.shouldWeNotify();
}
@Test
public void creates_instance_of_Seconds() {
Seconds seconds = fixture.create(Seconds.class);
assertThat(seconds, notNullValue());
assertThat(seconds, is(Seconds.seconds(31536000)));
}