org.joda.time.DateTime Java Examples

The following examples show how to use org.joda.time.DateTime. 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: FutureAction.java    From FlareBot with MIT License 6 votes vote down vote up
public FutureAction(long guildId, long channelId, long responsible, long target, String content,
                    DateTime expires, DateTime created, Action action) {
    this.guildId = guildId;
    this.channelId = channelId;
    this.responsible = responsible;
    this.target = target;
    this.content = content;
    this.expires = expires;
    this.created = created;
    this.action = action;

    if (expires.minus(created.getMillis()).getMillis() > Integer.MAX_VALUE) {
        delete();
        return;
    }
    this.delay = new Period(expires.minus(created.getMillis()).getMillis());
}
 
Example #2
Source File: AzkabanJobLauncher.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
/**
 * Uses the properties {@link ConfigurationKeys#AZKABAN_EXECUTION_DAYS_LIST},
 * {@link ConfigurationKeys#AZKABAN_EXECUTION_TIME_RANGE}, and
 * {@link TimeRangeChecker#isTimeInRange(List, String, String, DateTime)} to determine if the current job should
 * continue its execution based on the extra scheduled parameters defined in the config.
 *
 * @return true if this job should be launched, false otherwise.
 */
private boolean isCurrentTimeInRange() {
  Splitter splitter = Splitter.on(",").omitEmptyStrings().trimResults();

  if (this.props.contains(ConfigurationKeys.AZKABAN_EXECUTION_DAYS_LIST) && this.props
      .contains(ConfigurationKeys.AZKABAN_EXECUTION_TIME_RANGE)) {

    List<String> executionTimeRange =
        splitter.splitToList(this.props.getProperty(ConfigurationKeys.AZKABAN_EXECUTION_TIME_RANGE));
    List<String> executionDays =
        splitter.splitToList(this.props.getProperty(ConfigurationKeys.AZKABAN_EXECUTION_DAYS_LIST));
    Preconditions.checkArgument(executionTimeRange.size() == 2,
        "The property " + ConfigurationKeys.AZKABAN_EXECUTION_DAYS_LIST
            + " should be a comma separated list of two entries");

    return TimeRangeChecker.isTimeInRange(executionDays, executionTimeRange.get(0), executionTimeRange.get(1),
        new DateTime(DateTimeZone.forID(ConfigurationKeys.PST_TIMEZONE_NAME)));
  }

  return true;
}
 
Example #3
Source File: AccessFilter.java    From OpenSAML-ref-project-demo-v3 with Apache License 2.0 6 votes vote down vote up
private AuthnRequest buildAuthnRequest() {
    AuthnRequest authnRequest = OpenSAMLUtils.buildSAMLObject(AuthnRequest.class);
    //请求时间:该对象创建的时间,以判断其时效性
    authnRequest.setIssueInstant(new DateTime());
    //目标URL:目标地址,IDP地址
    authnRequest.setDestination(getIPDSSODestination());
    //传输SAML断言所需要的绑定:也就是用何种协议使用Artifact来取回真正的认证信息,
    authnRequest.setProtocolBinding(SAMLConstants.SAML2_ARTIFACT_BINDING_URI);
    //SP地址: 也就是SAML断言返回的地址
    authnRequest.setAssertionConsumerServiceURL(getAssertionConsumerEndpoint());
    //请求的ID:为当前请求设置ID,一般为随机数
    authnRequest.setID(OpenSAMLUtils.generateSecureRandomId());
    //Issuer: 发行人信息,也就是SP的ID,一般是SP的URL
    authnRequest.setIssuer(buildIssuer());
    //NameID:IDP对于用户身份的标识;NameID policy是SP关于NameID是如何创建的说明
    authnRequest.setNameIDPolicy(buildNameIdPolicy());
    // 请求认证上下文(requested Authentication Context):
    // SP对于认证的要求,包含SP希望IDP如何验证用户,也就是IDP要依据什么来验证用户身份。
    authnRequest.setRequestedAuthnContext(buildRequestedAuthnContext());

    return authnRequest;
}
 
Example #4
Source File: StatisticsXmlReportGenerator.java    From megatron-java with Apache License 2.0 6 votes vote down vote up
private Map<String, Long> fetchNoOfLogEntriesPerEntryType(DbManager dbManager, DateTime startDate, boolean onlyMatchedEntries) throws MegatronException {
        TimePeriod timePeriod = createWeekTimePeriod(startDate);
        log.debug("Fetching no. of log entries for period: " + timePeriod.getFormattedPeriodString(TimePeriod.LONG_FORMAT));
        
//        // create dummy
//        Map<String, Long> result = new HashMap<String, Long>();
//        int intervalStart = onlyMatchedEntries ? 5000 : 8000;
//        int intervalEnd = onlyMatchedEntries ? 12000 : 15000;
//        result.put("\u00d6vrigt", randomLong(intervalStart, intervalEnd));
//        result.put("Skr\u00e4ppost (RBL)", randomLong(intervalStart, intervalEnd));
//        result.put("Foo", randomLong(intervalStart, intervalEnd));
//        result.put("Botn\u00e4t", randomLong(intervalStart, intervalEnd));
//        result.put("Bar", randomLong(intervalStart, intervalEnd));
//        return result;
        
        return dbManager.fetchNoOfLogEntriesPerEntryType(timePeriod.getStartDate(), timePeriod.getEndDate(), onlyMatchedEntries);
    }
 
Example #5
Source File: RdeUploadActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunWithLock_sftpCooldownNotPassed_throws204() {
  RdeUploadAction action = createAction(URI.create("sftp://user:password@localhost:32323/"));
  action.sftpCooldown = standardHours(2);
  DateTime stagingCursor = DateTime.parse("2010-10-18TZ");
  DateTime uploadCursor = DateTime.parse("2010-10-17TZ");
  DateTime sftpCursor = uploadCursor.minusMinutes(97); // Within the 2 hour cooldown period.
  persistResource(Cursor.create(RDE_STAGING, stagingCursor, Registry.get("tld")));
  persistResource(Cursor.create(RDE_UPLOAD_SFTP, sftpCursor, Registry.get("tld")));
  NoContentException thrown =
      assertThrows(NoContentException.class, () -> action.runWithLock(uploadCursor));
  assertThat(thrown)
      .hasMessageThat()
      .isEqualTo(
          "Waiting on 120 minute SFTP cooldown for TLD tld to send 2010-10-17T00:00:00.000Z "
              + "upload; last upload attempt was at 2010-10-16T22:23:00.000Z (97 minutes ago)");
}
 
Example #6
Source File: ResaveAllEppResourcesActionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void test_mapreduceResolvesPendingTransfer() throws Exception {
  DateTime now = DateTime.now(UTC);
  // Set up a contact with a transfer that implicitly completed five days ago.
  ContactResource contact =
      persistContactWithPendingTransfer(
          persistActiveContact("meh789"),
          now.minusDays(10),
          now.minusDays(10),
          now.minusDays(10));
  assertThat(contact.getTransferData().getTransferStatus()).isEqualTo(TransferStatus.PENDING);
  runMapreduce();

  ofy().clearSessionCache();
  // The transfer should be effective after the contact is re-saved, as it should've been
  // projected to the current time.
  ContactResource resavedContact = ofy().load().entity(contact).now();
  assertThat(resavedContact.getTransferData().getTransferStatus())
      .isEqualTo(TransferStatus.SERVER_APPROVED);
}
 
Example #7
Source File: UpdateAutoTimestampTranslatorFactory.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Override
SimpleTranslator<UpdateAutoTimestamp, Date> createTranslator() {
  return new SimpleTranslator<UpdateAutoTimestamp, Date>() {

    /**
     * Load an existing timestamp. It can be assumed to be non-null since if the field is null in
     * Datastore then Objectify will skip this translator and directly load a null.
     */
    @Override
    public UpdateAutoTimestamp loadValue(Date datastoreValue) {
      // Load an existing timestamp, or treat it as START_OF_TIME if none exists.
      return UpdateAutoTimestamp.create(new DateTime(datastoreValue, UTC));
    }

    /** Save a timestamp, setting it to the current time. */
    @Override
    public Date saveValue(UpdateAutoTimestamp pojoValue) {
      return tm().getTransactionTime().toDate();
    }};
}
 
Example #8
Source File: KubeApiServerIntegrator.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private boolean isNodeReadyForGc(V1Node node) {
    Optional<V1NodeCondition> stoppedConditionOpt = node.getStatus().getConditions().stream()
            .filter(c -> c.getType().equalsIgnoreCase(STOPPED) && Boolean.parseBoolean(c.getStatus()))
            .findAny();
    if (stoppedConditionOpt.isPresent()) {
        return true;
    }

    Optional<V1NodeCondition> readyConditionOpt = node.getStatus().getConditions().stream()
            .filter(c -> c.getType().equalsIgnoreCase(READY))
            .findAny();
    if (!readyConditionOpt.isPresent()) {
        return false;
    }
    V1NodeCondition readyCondition = readyConditionOpt.get();
    boolean status = Boolean.parseBoolean(readyCondition.getStatus());
    DateTime lastHeartbeatTime = readyCondition.getLastHeartbeatTime();
    return !status &&
            lastHeartbeatTime != null &&
            clock.isPast(lastHeartbeatTime.getMillis() + directKubeConfiguration.getNodeGcTtlMs());
}
 
Example #9
Source File: MessagesControllerTest.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
@Test(timeout = 5000)
@Category({UnitTest.class})
public void itGetsAllMessages() throws
    InvalidInputException,
    InvalidConfigurationException,
    TimeSeriesParseException {

    // Arrange
    IMessages messages = mock(IMessages.class);
    MessagesController controller = new MessagesController(mock(IMessages.class));
    ArrayList<MessageServiceModel> msgs = new ArrayList<MessageServiceModel>() {{
        add(new MessageServiceModel());
        add(new MessageServiceModel());
    }};
    MessageListServiceModel res = new MessageListServiceModel(msgs, null);
    when(messages.getList(
        DateTime.now(), DateTime.now(), "asc", 0, 100, new String[0]))
        .thenReturn(res);

    // Act
    Result response = controller.list(null, null, null, null, null, null);

    // Assert
    assertThat(response.body().isKnownEmpty(), is(false));
}
 
Example #10
Source File: TestGJChronology.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testFactory_Zone_RI() {
    GJChronology chrono = GJChronology.getInstance(TOKYO, new Instant(0L));
    assertEquals(TOKYO, chrono.getZone());
    assertEquals(new Instant(0L), chrono.getGregorianCutover());
    assertSame(GJChronology.class, GJChronology.getInstance(TOKYO, new Instant(0L)).getClass());
    
    DateTime cutover = new DateTime(1582, 10, 15, 0, 0, 0, 0, DateTimeZone.UTC);
    chrono = GJChronology.getInstance(TOKYO, null);
    assertEquals(TOKYO, chrono.getZone());
    assertEquals(cutover.toInstant(), chrono.getGregorianCutover());
}
 
Example #11
Source File: QuotaManagerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_rebate() throws Exception {
  DateTime grantedTokenRefillTime = clock.nowUtc();
  response = QuotaResponse.create(true, USER_ID, grantedTokenRefillTime);
  QuotaRebate rebate = QuotaRebate.create(response);
  Future<?> unusedFuture = quotaManager.releaseQuota(rebate);
  verify(tokenStore).scheduleRefresh();
  verify(tokenStore).put(USER_ID, grantedTokenRefillTime);
  verifyNoMoreInteractions(tokenStore);
}
 
Example #12
Source File: TestISODateTimeFormat.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testFormat_basicOrdinalDateTimeNoMillis() {
    DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC);
    assertEquals("2004161T102030Z", ISODateTimeFormat.basicOrdinalDateTimeNoMillis().print(dt));
    
    dt = dt.withZone(LONDON);
    assertEquals("2004161T112030+0100", ISODateTimeFormat.basicOrdinalDateTimeNoMillis().print(dt));
    
    dt = dt.withZone(PARIS);
    assertEquals("2004161T122030+0200", ISODateTimeFormat.basicOrdinalDateTimeNoMillis().print(dt));
}
 
Example #13
Source File: TestCallableQuery.java    From chronos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  dao = new H2TestJobDaoImpl();
  dao.setDrivers(drivers);
  dao.init();
  PowerMockito.mockStatic(Utils.class);
  when(Utils.getCurrentTime())
    .thenReturn(new DateTime(0).withZone(DateTimeZone.UTC));
}
 
Example #14
Source File: AnswerInformationTest.java    From mamute with Apache License 2.0 5 votes vote down vote up
private AnswerInformation newVersion(int minus) {
	return TimeMachine.goTo(new DateTime().minusSeconds(minus)).andExecute(new Block<AnswerInformation>() {
		@Override
		public AnswerInformation run() {
			return new AnswerInformation(notMarked("do this and that with ruby like that: lol"), null, "");
		}
	});
}
 
Example #15
Source File: TestISODateTimeFormat.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testFormat_hourMinuteSecondMillis() {
    DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC);
    assertEquals("10:20:30.040", ISODateTimeFormat.hourMinuteSecondMillis().print(dt));
    
    dt = dt.withZone(LONDON);
    assertEquals("11:20:30.040", ISODateTimeFormat.hourMinuteSecondMillis().print(dt));
    
    dt = dt.withZone(PARIS);
    assertEquals("12:20:30.040", ISODateTimeFormat.hourMinuteSecondMillis().print(dt));
}
 
Example #16
Source File: TestDateTimeFormat.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public void testFormat_dayOfWeekText() {
    DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC);
    DateTimeFormatter f = DateTimeFormat.forPattern("EEEE").withLocale(Locale.UK);
    assertEquals(dt.toString(), "Wednesday", f.print(dt));
    
    dt = dt.withZone(NEWYORK);
    assertEquals(dt.toString(), "Wednesday", f.print(dt));
    
    dt = dt.withZone(TOKYO);
    assertEquals(dt.toString(), "Wednesday", f.print(dt));
    
    f = f.withLocale(Locale.FRENCH);
    assertEquals(dt.toString(), "mercredi", f.print(dt));
}
 
Example #17
Source File: Energy.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
public Energy(String logdate, long l, double interval) {

        if (logdate.length() == 8) {

            if (!logdate.equals("FFFFFFFF")) {

                int year = 0;
                int month = 0;
                long minutes = 0;

                year = Integer.parseInt(StringUtils.left(logdate, 2), 16) + 2000;
                month = Integer.parseInt(StringUtils.mid(logdate, 2, 2), 16);
                minutes = Long.parseLong(StringUtils.right(logdate, 4), 16);

                time = new DateTime(year, month, 1, 0, 0, DateTimeZone.UTC).plusMinutes((int) minutes)
                        .toDateTime(DateTimeZone.getDefault()).minusHours(1);

            } else {
                time = DateTime.now();
                this.interval = interval;
                this.pulses = 0;
            }

        } else {
            time = DateTime.now();
        }

        this.interval = interval;
        this.pulses = l;

    }
 
Example #18
Source File: FacebookUserstreamProvider.java    From streams with Apache License 2.0 5 votes vote down vote up
@Override
public StreamsResultSet readRange(DateTime start, DateTime end) {
  LOGGER.debug("{} readRange", STREAMS_ID);
  this.start = start;
  this.end = end;
  readCurrent();
  return (StreamsResultSet) providerQueue.iterator();
}
 
Example #19
Source File: GanttDiagram.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void generateYearsViewMonthsViewAndDays() {

        DateTime firstMonthDateTime = getFirstInstant();
        DateTime lastMontDateTime = getLastInstant();

        if (firstMonthDateTime != null && lastMontDateTime != null) {
            while ((firstMonthDateTime.getYear() < lastMontDateTime.getYear())
                    || (firstMonthDateTime.getYear() == lastMontDateTime.getYear() && firstMonthDateTime.getDayOfYear() <= lastMontDateTime
                            .getDayOfYear())) {

                getDays().add(firstMonthDateTime);

                YearMonthDay day = firstMonthDateTime.toYearMonthDay().withDayOfMonth(1);
                if (getMonthsView().containsKey(day)) {
                    getMonthsView().put(day, getMonthsView().get(day) + 1);
                } else {
                    getMonthsView().put(day, 1);
                }

                if (getYearsView().containsKey(Integer.valueOf(firstMonthDateTime.getYear()))) {
                    getYearsView().put(Integer.valueOf(firstMonthDateTime.getYear()),
                            getYearsView().get(Integer.valueOf(firstMonthDateTime.getYear())) + 1);
                } else {
                    getYearsView().put(Integer.valueOf(firstMonthDateTime.getYear()), 1);
                }

                firstMonthDateTime = firstMonthDateTime.plusDays(1);
            }
        }
    }
 
Example #20
Source File: DataType.java    From spork with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static byte[] toBytes(Object o, byte type) throws ExecException {
    switch (type) {
    case BOOLEAN:
        //return ((Boolean) o).booleanValue() ? new byte[] {1} : new byte[] {0};
        return ((Boolean) o).toString().getBytes();
    case BYTE:
        return new byte[] {((Byte) o)};

    case BIGINTEGER:
    case BIGDECIMAL:
    case INTEGER:
    case DOUBLE:
    case FLOAT:
    case LONG:
        return ((Number) o).toString().getBytes();

    case DATETIME:
        return ((DateTime) o).toString().getBytes();

    case CHARARRAY:
        return ((String) o).getBytes();
    case MAP:
        return mapToString((Map<String, Object>) o).getBytes();
    case TUPLE:
        return ((Tuple) o).toString().getBytes();
    case BYTEARRAY:
        return ((DataByteArray) o).get();
    case BAG:
        return ((DataBag) o).toString().getBytes();
    case NULL:
        return null;
    default:
        int errCode = 1071;
        String msg = "Cannot convert a " + findTypeName(o) +
        " to a ByteArray";
        throw new ExecException(msg, errCode, PigException.INPUT);

    }
}
 
Example #21
Source File: UserPersonalInfoValidator.java    From mamute with Apache License 2.0 5 votes vote down vote up
public boolean validate(UserPersonalInfo info) {
	brutalValidator.validate(info);
	if(validator.hasErrors()){
		return false;
	}
	
	if (info.getUser() == null) {
	    validator.add(messageFactory.build("error", "user.errors.wrong"));
	    return false;
	}
	
	if (!info.getUser().getEmail().equals(info.getEmail())){
		emailValidator.validate(info.getEmail());
	}
	
	if (info.getBirthDate() != null && info.getBirthDate().getYear() > DateTime.now().getYear()-12){
		validator.add(messageFactory.build("error", "user.errors.invalid_birth_date.min_age"));
	}

	if(!info.getUser().getName().equals(info.getName())){
		DateTime nameLastTouchedAt = info.getUser().getNameLastTouchedAt();
		if (nameLastTouchedAt != null && nameLastTouchedAt.isAfter(new DateTime().minusDays(30))) {
			validator.add(messageFactory.build(
					"error", 
					"user.errors.name.min_time", 
					nameLastTouchedAt.plusDays(30).toString(DateTimeFormat.forPattern(bundle.getMessage("date.joda.simple.pattern")))
			));
		}
	}
	
	return !validator.hasErrors();
}
 
Example #22
Source File: OneTimeInvoiceLineItemTest.java    From Partner-Center-Java with MIT License 5 votes vote down vote up
@Test
void getPCToBCExchangeRateDate()
{
    OneTimeInvoiceLineItem lineItem = new OneTimeInvoiceLineItem();
    DateTime value = DateTime.now();

    lineItem.setPCToBCExchangeRateDate(value);

    assertEquals(value, lineItem.getPCToBCExchangeRateDate());
}
 
Example #23
Source File: EdOrgExtractorTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void testExecuteAgain() {
    File tenantDir = Mockito.mock(File.class);
    DateTime time = new DateTime();
    extractor.execute("Midgar", tenantDir, time);
    Mockito.verify(mockExtractMap, Mockito.times(1)).archiveFiles();
    Mockito.verify(mockExtractMap, Mockito.times(1)).buildManifestFiles(time);
    Mockito.verify(mockExtractMap, Mockito.times(1)).closeFiles();
}
 
Example #24
Source File: JSON.java    From nifi-api-client-java with Apache License 2.0 5 votes vote down vote up
/**
 * JSON constructor.
 *
 * @param apiClient An instance of ApiClient
 */
public JSON(ApiClient apiClient) {
    this.apiClient = apiClient;
    gson = new GsonBuilder()
        .registerTypeAdapter(Date.class, new DateAdapter(apiClient))
        .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
        .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
        .create();
}
 
Example #25
Source File: TimeExpressionUtils.java    From liteflow with Apache License 2.0 5 votes vote down vote up
/**
 * 通过任务版本获取对应的时间
 * @param version
 * @return
 */
public static Date getDateByVersion(String version){
    TimeUnit[] timeUnits = TimeUnit.values();
    String versionExpression = "";
    for(TimeUnit t : timeUnits){
        if(version.length() == t.getVersionExpression().length()){
            versionExpression = t.getVersionExpression();
            break;
        }
    }
    DateTimeFormatter format = DateTimeFormat.forPattern(versionExpression);
    DateTime dateTime = DateTime.parse(version, format);
    return dateTime.toDate();

}
 
Example #26
Source File: TestDateTimeFunctions.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testLocalTimestamp()
{
    Session localSession = Session.builder(session)
            .setStart(Instant.ofEpochMilli(new DateTime(2017, 3, 1, 14, 30, 0, 0, DATE_TIME_ZONE).getMillis()))
            .build();
    try (FunctionAssertions localAssertion = new FunctionAssertions(localSession)) {
        localAssertion.assertFunctionString("LOCALTIMESTAMP", TimestampType.TIMESTAMP, "2017-03-01 14:30:00.000");
    }
}
 
Example #27
Source File: DateTimeConverter.java    From alchemy with MIT License 5 votes vote down vote up
@Override
public Object decode(Class clazz, Object o, MappedField mappedField) {
    final Long instant = (Long) o;
    if (instant == null) {
        return null;
    }
    return new DateTime(instant);
}
 
Example #28
Source File: WakeUpAtSetTimeView.java    From sleep-cycle-alarm with GNU General Public License v3.0 5 votes vote down vote up
@Override
public DateTime getDateTime() {
    if (dateTime == null) {
        dateTime = DateTime.now();
    }
    return dateTime;
}
 
Example #29
Source File: ConsentWithStatusType.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public DateTime getRevokedate() {
   return this.revokedate;
}
 
Example #30
Source File: RequestType.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public DateTime getTime() {
   return this.time;
}