Java Code Examples for java.time.Instant#atZone()

The following examples show how to use java.time.Instant#atZone() . 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: TimeUtil.java    From styx with Apache License 2.0 6 votes vote down vote up
/**
 * Gets an ordered list instants between firstInstant (inclusive) and lastInstant (exclusive)
 * according to the {@link Schedule}. This works in a reversed order, meaning firstInstant should
 * be after lastInstant.
 *
 * @param firstInstant The first instant
 * @param lastInstant  The last instant
 * @param schedule     The schedule of the workflow
 * @return instants within the range
 */
public static List<Instant> instantsInReversedRange(Instant firstInstant, Instant lastInstant,
                                                    Schedule schedule) {
  Preconditions.checkArgument(
      isAligned(firstInstant, schedule) && isAligned(lastInstant, schedule),
      "unaligned instant");
  Preconditions.checkArgument(!lastInstant.isAfter(firstInstant),
      "last instant should not be after first instant");

  final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule));
  final List<Instant> instants = new ArrayList<>();

  Instant currentInstant = firstInstant;
  while (currentInstant.isAfter(lastInstant)) {
    instants.add(currentInstant);
    final ZonedDateTime utcDateTime = currentInstant.atZone(UTC);
    currentInstant = executionTime.lastExecution(utcDateTime)
        .orElseThrow(IllegalArgumentException::new) // with unix cron, this should not happen
        .toInstant();
  }

  return instants;
}
 
Example 2
Source File: InterpreterLogicTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_parse_accurate_date() throws Exception {
  //Given
  String dateString = "2015-07-30 12:00:01.123";

  //When
  final Instant actual = helper.parseDate(dateString);

  //Then
  ZonedDateTime dt = actual.atZone(ZoneOffset.UTC);

  assertThat(dt.getLong(ChronoField.YEAR_OF_ERA)).isEqualTo(2015);
  assertThat(dt.getLong(ChronoField.MONTH_OF_YEAR)).isEqualTo(7);
  assertThat(dt.getLong(ChronoField.DAY_OF_MONTH)).isEqualTo(30);
  assertThat(dt.getLong(ChronoField.HOUR_OF_DAY)).isEqualTo(12);
  assertThat(dt.getLong(ChronoField.MINUTE_OF_HOUR)).isEqualTo(0);
  assertThat(dt.getLong(ChronoField.SECOND_OF_MINUTE)).isEqualTo(1);
  assertThat(dt.getLong(ChronoField.MILLI_OF_SECOND)).isEqualTo(123);
}
 
Example 3
Source File: InterpreterLogicTest.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_parse_simple_date() throws Exception {
  //Given
  String dateString = "2015-07-30 12:00:01";

  //When
  final Instant actual = helper.parseDate(dateString);

  //Then
  ZonedDateTime dt = actual.atZone(ZoneOffset.UTC);

  assertThat(dt.getLong(ChronoField.YEAR_OF_ERA)).isEqualTo(2015);
  assertThat(dt.getLong(ChronoField.MONTH_OF_YEAR)).isEqualTo(7);
  assertThat(dt.getLong(ChronoField.DAY_OF_MONTH)).isEqualTo(30);
  assertThat(dt.getLong(ChronoField.HOUR_OF_DAY)).isEqualTo(12);
  assertThat(dt.getLong(ChronoField.MINUTE_OF_HOUR)).isEqualTo(0);
  assertThat(dt.getLong(ChronoField.SECOND_OF_MINUTE)).isEqualTo(1);
}
 
Example 4
Source File: TCKInstant.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_atZone() {
    for (int i = 0; i < (24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i);
        ZonedDateTime test = instant.atZone(ZoneOffset.ofHours(1));
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonthValue(), 1);
        assertEquals(test.getDayOfMonth(), 1 + (i >= 23 * 60 * 60 ? 1 : 0));
        assertEquals(test.getHour(), ((i / (60 * 60)) + 1) % 24);
        assertEquals(test.getMinute(), (i / 60) % 60);
        assertEquals(test.getSecond(), i % 60);
    }
}
 
Example 5
Source File: TCKInstant.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_atZone() {
    for (int i = 0; i < (24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i);
        ZonedDateTime test = instant.atZone(ZoneOffset.ofHours(1));
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonthValue(), 1);
        assertEquals(test.getDayOfMonth(), 1 + (i >= 23 * 60 * 60 ? 1 : 0));
        assertEquals(test.getHour(), ((i / (60 * 60)) + 1) % 24);
        assertEquals(test.getMinute(), (i / 60) % 60);
        assertEquals(test.getSecond(), i % 60);
    }
}
 
Example 6
Source File: TimeUtil.java    From styx with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the last execution instant for a {@link Schedule}, relative to a given instant. If
 * the given instant is exactly at an execution time of the schedule, it will be returned
 * as is.
 *
 * <p>e.g. an hourly schedule has a last execution instant at 13:00 relative to 13:22.
 *
 * @param instant  The instant to calculate the last execution instant relative to
 * @param schedule The schedule of executions
 * @return an instant at the last execution time
 */
public static Instant lastInstant(Instant instant, Schedule schedule) {
  final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule));
  final ZonedDateTime utcDateTime = instant.atZone(UTC);

  // executionTime.isMatch ignores seconds for unix cron
  // so we fail the check immediately if there is a sub-minute value
  return (instant.truncatedTo(ChronoUnit.MINUTES).equals(instant)
          && executionTime.isMatch(utcDateTime))
         ? instant
         : executionTime.lastExecution(utcDateTime)
             .orElseThrow(IllegalArgumentException::new) // with unix cron, this should not happen
             .toInstant();
}
 
Example 7
Source File: ParquetTypeConverterTest.java    From pxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testBinaryWithNanos() {
    Instant instant = Instant.parse("2019-03-15T03:52:48.123456Z"); // UTC
    ZonedDateTime localTime = instant.atZone(ZoneId.systemDefault());
    String expected = localTime.format(GreenplumDateTime.DATETIME_FORMATTER); // should be "2019-03-14 20:52:48.123456" in PST

    byte[] source = new byte[]{0, 106, 9, 53, -76, 12, 0, 0, -66, -125, 37, 0}; // represents 2019-03-14 20:52:48.1234567
    String timestamp = ParquetTypeConverter.bytesToTimestamp(source); // nanos get dropped
    assertEquals(expected, timestamp);
}
 
Example 8
Source File: TimeUtil.java    From styx with Apache License 2.0 5 votes vote down vote up
public static Instant previousInstant(Instant instant, Schedule schedule) {
  final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule));
  final ZonedDateTime utcDateTime = instant.atZone(UTC);

  return executionTime.lastExecution(utcDateTime)
      .orElseThrow(IllegalArgumentException::new) // with unix cron, this should not happen
      .toInstant();
}
 
Example 9
Source File: TimeUtil.java    From styx with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if a given instant is aligned with the execution times of a {@link Schedule}.
 *
 * @param instant  The instant to test
 * @param schedule The schedule to test against
 * @return true if the given instant aligns with the schedule
 */
public static boolean isAligned(Instant instant, Schedule schedule) {
  // executionTime.isMatch ignores seconds for unix cron
  // so we fail the check immediately if there is a sub-minute value
  if (!instant.truncatedTo(ChronoUnit.MINUTES).equals(instant)) {
    return false;
  }

  final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule));
  final ZonedDateTime utcDateTime = instant.atZone(UTC);

  return executionTime.isMatch(utcDateTime);
}
 
Example 10
Source File: VulnerabilityController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
@RequestMapping(path = "/v1/trend/compliance/vulnerabilities", method = RequestMethod.POST)
public ResponseEntity<Object> getVulnTrend(@RequestBody(required = true) CompliantTrendRequest request) {

	Map<String, Object> response = new HashMap<>();
	String assetGroup = request.getAg();

	Date input = request.getFrom();

	if (input == null) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeZone(TimeZone.getTimeZone("UTC"));
		cal.add(Calendar.DATE, NEG_THIRTY);
		input = cal.getTime();
	}

	Instant instant = input.toInstant();
	ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
	LocalDate fromDate = zdt.toLocalDate();
	LocalDate toDate = LocalDate.now();

	if (Strings.isNullOrEmpty(assetGroup)) {
		return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
	}

	try {
		Map<String, Object> ruleTrendProgressList = vulnerabilityService.getTrendProgress(assetGroup, null,
				fromDate, toDate, "vulncompliance");
		response.put(RESPONSE, ruleTrendProgressList);
	} catch (ServiceException e) {
		LOGGER.error("Exception in getVulnTrend", e.getMessage());
		return ResponseUtils.buildFailureResponse(e);
	}
	return ResponseUtils.buildSucessResponse(response);
}
 
Example 11
Source File: DateFunctions.java    From jphp with Apache License 2.0 5 votes vote down vote up
public static Memory localtime(Environment env, TraceInfo traceInfo, long time, boolean isAssociative) {
    ZoneId zone = zoneId(env, traceInfo);

    Instant instant = Instant.ofEpochSecond(time);
    ZonedDateTime dateTime = instant.atZone(zone);

    Memory[] ret = new Memory[9];

    ret[0] = LongMemory.valueOf(dateTime.getSecond());
    ret[1] = LongMemory.valueOf(dateTime.getMinute());
    ret[2] = LongMemory.valueOf(dateTime.getHour());
    ret[3] = LongMemory.valueOf(dateTime.getDayOfMonth());
    ret[4] = LongMemory.valueOf(dateTime.getMonthValue() - 1);
    ret[5] = LongMemory.valueOf(dateTime.getYear() - 1900);
    ret[6] = LongMemory.valueOf(dateTime.getDayOfWeek().getValue());
    ret[7] = LongMemory.valueOf(dateTime.getDayOfYear() - 1);
    Duration ds = zone.getRules().getDaylightSavings(instant);
    ret[8] = ds.isZero() ? Memory.CONST_INT_0 : Memory.CONST_INT_1;

    if (isAssociative) {
        Memory[] struct = LocaltimeStructureHolder.VALUE;
        ArrayMemory array = ArrayMemory.createHashed(ret.length);
        for (int i = 0; i < struct.length; i++) {
            array.put(struct[i], ret[i]);
        }

        return array;
    }

    return ArrayMemory.of(ret);
}
 
Example 12
Source File: TrendController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the Tagging compliance trend.This request expects asset group,domain
 * and from as mandatory.If API receives asset group,domain and from as
 * request parameters, it gives weekly based details of compliance trend
 * from mentioned date to till date for tagging
 *
 * @param request
 *            the request
 * @return ResponseEntity
 */

@RequestMapping(path = "/v1/trend/compliance/tagging", method = RequestMethod.POST)
public ResponseEntity<Object> getTagTrend(@RequestBody(required = true) CompliantTrendRequest request) {

    Map<String, Object> response = new HashMap<>();
    String assetGroup = request.getAg();

    Date input = request.getFrom();

    if (input == null) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.add(Calendar.DATE, NEG_THIRTY);
        input = cal.getTime();
    }

    Instant instant = input.toInstant();
    ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
    LocalDate fromDate = zdt.toLocalDate();
    LocalDate toDate = LocalDate.now();

    if (Strings.isNullOrEmpty(assetGroup)) {
        return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
    }

    try {
        Map<String, Object> ruleTrendProgressList = trendService.getTrendProgress(assetGroup, null, fromDate,
                toDate, "tagcompliance");
        response.put(RESPONSE, ruleTrendProgressList);
    } catch (ServiceException e) {
        LOGGER.error("Exception in getTagTrend" , e.getMessage());
        return ResponseUtils.buildFailureResponse(e);
    }
    return ResponseUtils.buildSucessResponse(response);
}
 
Example 13
Source File: TCKInstant.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_atZone() {
    for (int i = 0; i < (24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i);
        ZonedDateTime test = instant.atZone(ZoneOffset.ofHours(1));
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonthValue(), 1);
        assertEquals(test.getDayOfMonth(), 1 + (i >= 23 * 60 * 60 ? 1 : 0));
        assertEquals(test.getHour(), ((i / (60 * 60)) + 1) % 24);
        assertEquals(test.getMinute(), (i / 60) % 60);
        assertEquals(test.getSecond(), i % 60);
    }
}
 
Example 14
Source File: TrendController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the vulnerabilities trend.This request expects asset group and from
 * as mandatory.If API receives asset group and from as request parameters,
 * it gives weekly based details of compliance trend from mentioned date to
 * till date for vulnerabilities
 *
 * @param request
 *            the request
 * @return ResponseEntity
 */

@RequestMapping(path = "/v1/trend/compliance/vulnerabilities", method = RequestMethod.POST)
public ResponseEntity<Object> getVulnTrend(@RequestBody(required = true) CompliantTrendRequest request) {

    Map<String, Object> response = new HashMap<>();
    String assetGroup = request.getAg();

    Date input = request.getFrom();

    if (input == null) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.add(Calendar.DATE, NEG_THIRTY);
        input = cal.getTime();
    }

    Instant instant = input.toInstant();
    ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
    LocalDate fromDate = zdt.toLocalDate();
    LocalDate toDate = LocalDate.now();

    if (Strings.isNullOrEmpty(assetGroup)) {
        return ResponseUtils.buildFailureResponse(new Exception(ASSET_MANDATORY));
    }

    try {
        Map<String, Object> ruleTrendProgressList = trendService.getTrendProgress(assetGroup, null, fromDate,
                toDate, "vulncompliance");
        response.put(RESPONSE, ruleTrendProgressList);
    } catch (ServiceException e) {
        LOGGER.error("Exception in getVulnTrend" , e.getMessage());
        return ResponseUtils.buildFailureResponse(e);
    }
    return ResponseUtils.buildSucessResponse(response);
}
 
Example 15
Source File: TrendController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the rule trend.This request expects asset group,ruleId and from as
 * mandatory.If API receives asset group,ruleId and from as request
 * parameters, it gives weekly based details of compliance trend from
 * mentioned date to till date for ruleId.
 *
 * @param request
 *            the request
 * @return ResponseEntity
 */

@RequestMapping(path = "/v1/trend/compliancebyrule", method = RequestMethod.POST)
public ResponseEntity<Object> getRuleTrend(@RequestBody(required = true) RuleTrendRequest request) {

    Map<String, Object> response = new HashMap<>();
    String assetGroup = request.getAg();
    String ruleId = request.getRuleid();

    Date input = request.getFrom();

    if (input == null) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.add(Calendar.DATE, NEG_THIRTY);
        input = cal.getTime();
    }

    Instant instant = input.toInstant();
    ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
    LocalDate fromDate = zdt.toLocalDate();
    LocalDate toDate = LocalDate.now();

    if (Strings.isNullOrEmpty(assetGroup) || Strings.isNullOrEmpty(ruleId)) {
        return ResponseUtils.buildFailureResponse(new Exception("assetGroup/ruleId is Mandatory"));
    }

    try {
        Map<String, Object> ruleTrendProgressList = trendService.getTrendProgress(assetGroup, ruleId, fromDate,
                toDate, "issuecompliance");
        response.put(RESPONSE, ruleTrendProgressList);
    } catch (ServiceException e) {
        LOGGER.error("Exception in getRuleTrend" , e.getMessage());
        return ResponseUtils.buildFailureResponse(e);
    }
    return ResponseUtils.buildSucessResponse(response);
}
 
Example 16
Source File: TrendController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the compliant trend.This request expects asset group,domain and from
 * as mandatory.If API receives asset group,domain and from as request
 * parameters, it gives weekly based details of compliance info from
 * mentioned date to till date by rule category
 *
 * @param request
 *            the request
 * @return ResponseEntity
 * @RequestBody request
 */

@RequestMapping(path = "/v1/trend/compliance", method = RequestMethod.POST)

public ResponseEntity<Object> getCompliantTrend(@RequestBody(required = true) CompliantTrendRequest request) {
    Map<String, Object> response = new HashMap<>();
    String assetGroup = request.getAg();

    Date input = request.getFrom();

    if (input == null) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.add(Calendar.DATE, NEG_THIRTY);
        input = cal.getTime();
    }

    Instant instant = input.toInstant();
    ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
    LocalDate fromDate = zdt.toLocalDate();
    Map<String, String> filter = request.getFilters();

    if (Strings.isNullOrEmpty(assetGroup) || MapUtils.isEmpty(filter) || Strings.isNullOrEmpty(filter.get(DOMAIN))) {
        return ResponseUtils.buildFailureResponse(new Exception(ASSET_GROUP_DOMAIN));
    }

    String domain = filter.get(DOMAIN);
    try {
        Map<String, Object> trendData = trendService.getComplianceTrendProgress(assetGroup, fromDate, domain);
        response.put(RESPONSE, trendData);
    } catch (ServiceException e) {
        LOGGER.error("Exception in getCompliantTrend()" ,e.getMessage());
        return ResponseUtils.buildFailureResponse(e);
    }
    return ResponseUtils.buildSucessResponse(response);
}
 
Example 17
Source File: TCKInstant.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_atZone() {
    for (int i = 0; i < (24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i);
        ZonedDateTime test = instant.atZone(ZoneOffset.ofHours(1));
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonthValue(), 1);
        assertEquals(test.getDayOfMonth(), 1 + (i >= 23 * 60 * 60 ? 1 : 0));
        assertEquals(test.getHour(), ((i / (60 * 60)) + 1) % 24);
        assertEquals(test.getMinute(), (i / 60) % 60);
        assertEquals(test.getSecond(), i % 60);
    }
}
 
Example 18
Source File: TCKInstant.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_atZone() {
    for (int i = 0; i < (24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i);
        ZonedDateTime test = instant.atZone(ZoneOffset.ofHours(1));
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonthValue(), 1);
        assertEquals(test.getDayOfMonth(), 1 + (i >= 23 * 60 * 60 ? 1 : 0));
        assertEquals(test.getHour(), ((i / (60 * 60)) + 1) % 24);
        assertEquals(test.getMinute(), (i / 60) % 60);
        assertEquals(test.getSecond(), i % 60);
    }
}
 
Example 19
Source File: ToolDatePlus.java    From protools with Apache License 2.0 4 votes vote down vote up
public static LocalDateTime date2LocalDateTime(final Date date) {
    Instant instant = date.toInstant();
    ZonedDateTime zdt = instant.atZone(DEFAULT_ZONE_ID);
    return zdt.toLocalDateTime();
}
 
Example 20
Source File: AtsDbReader.java    From ats-framework with Apache License 2.0 3 votes vote down vote up
/**
 * Convert some time stamp (milliseconds since Epoch) to a time zone
 *
 * @param timestamp - the date/time in milliseconds
 * @param zoneId    - the zone ID of the Time zone you want to convert the time stamp. You can use
 *                    {@link AtsDbReader#UTC_ZONE_ID} for UTC and {@link AtsDbReader#SYSTEM_DEFAULT_ZONE_ID} for
 *                    the system default one
 * @return {@link ZonedDateTime}. You can use the toString() method on the returned object as well
 */
@PublicAtsApi
public ZonedDateTime convertTimestampToZone(long timestamp, ZoneId zoneId) {

    Instant instant = Instant.ofEpochMilli(timestamp);
    ZonedDateTime zonedDateTime = instant.atZone(zoneId);
    return zonedDateTime;
}