下面列出了com.google.protobuf.FieldMask#org.threeten.bp.Instant 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void test_Paris_getStandardOffset() {
ZoneRules test = europeParis();
ZonedDateTime zdt = createZDT(1840, 1, 1, ZoneOffset.UTC);
while (zdt.getYear() < 2010) {
Instant instant = zdt.toInstant();
if (zdt.toLocalDate().isBefore(LocalDate.of(1911, 3, 11))) {
assertEquals(test.getStandardOffset(instant), ZoneOffset.ofHoursMinutesSeconds(0, 9, 21));
} else if (zdt.toLocalDate().isBefore(LocalDate.of(1940, 6, 14))) {
assertEquals(test.getStandardOffset(instant), OFFSET_ZERO);
} else if (zdt.toLocalDate().isBefore(LocalDate.of(1944, 8, 25))) {
assertEquals(test.getStandardOffset(instant), OFFSET_PONE);
} else if (zdt.toLocalDate().isBefore(LocalDate.of(1945, 9, 16))) {
assertEquals(test.getStandardOffset(instant), OFFSET_ZERO);
} else {
assertEquals(test.getStandardOffset(instant), OFFSET_PONE);
}
zdt = zdt.plusMonths(6);
}
}
@Override
public boolean print(DateTimePrintContext context, StringBuilder buf) {
ZoneId zone = context.getValue(TemporalQueries.zoneId());
if (zone == null) {
return false;
}
if (zone.normalized() instanceof ZoneOffset) {
buf.append(zone.getId());
return true;
}
TemporalAccessor temporal = context.getTemporal();
boolean daylight = false;
if (temporal.isSupported(INSTANT_SECONDS)) {
Instant instant = Instant.ofEpochSecond(temporal.getLong(INSTANT_SECONDS));
daylight = zone.getRules().isDaylightSavings(instant);
}
TimeZone tz = TimeZone.getTimeZone(zone.getId());
int tzstyle = (textStyle.asNormal() == TextStyle.FULL ? TimeZone.LONG : TimeZone.SHORT);
String text = tz.getDisplayName(daylight, tzstyle, context.getLocale());
buf.append(text);
return true;
}
/**
* Updates a finding's state to INACTIVE.
*
* @param findingName The finding to update.
*/
// [START update_finding_state]
static Finding setFindingState(FindingName findingName) {
try (SecurityCenterClient client = SecurityCenterClient.create()) {
// FindingName findingName = FindingName.of(/*organization=*/"123234324",
// /*source=*/"423432321", /*findingId=*/"samplefindingid2");
// Use the current time as the finding "event time".
Instant eventTime = Instant.now();
Finding response =
client.setFindingState(
findingName,
State.INACTIVE,
Timestamp.newBuilder()
.setSeconds(eventTime.getEpochSecond())
.setNanos(eventTime.getNano())
.build());
System.out.println("Updated Finding: " + response);
return response;
} catch (IOException e) {
throw new RuntimeException("Couldn't create client.", e);
}
}
public static void verifyIasSignature(KeyStore trustStore, String certificates, String signatureBody, String signature, Quote quote)
throws SignatureException
{
if (certificates == null || certificates.isEmpty()) {
throw new SignatureException("No certificates.");
}
try {
SigningCertificate signingCertificate = new SigningCertificate(certificates, trustStore);
signingCertificate.verifySignature(signatureBody, signature);
SignatureBodyEntity signatureBodyEntity = JsonUtil.fromJson(signatureBody, SignatureBodyEntity.class);
if (signatureBodyEntity.getVersion() != SIGNATURE_BODY_VERSION) {
throw new SignatureException("Unexpected signed quote version " + signatureBodyEntity.getVersion());
}
if (!MessageDigest.isEqual(ByteUtil.trim(signatureBodyEntity.getIsvEnclaveQuoteBody(), 432), ByteUtil.trim(quote.getQuoteBytes(), 432))) {
throw new SignatureException("Signed quote is not the same as RA quote: " + Hex.toStringCondensed(signatureBodyEntity.getIsvEnclaveQuoteBody()) + " vs " + Hex.toStringCondensed(quote.getQuoteBytes()));
}
if (!"OK".equals(signatureBodyEntity.getIsvEnclaveQuoteStatus())) {
throw new SignatureException("Quote status is: " + signatureBodyEntity.getIsvEnclaveQuoteStatus());
}
if (Instant.from(ZonedDateTime.of(LocalDateTime.from(DateTimeFormatter.ofPattern("yyy-MM-dd'T'HH:mm:ss.SSSSSS").parse(signatureBodyEntity.getTimestamp())), ZoneId.of("UTC")))
.plus(Period.ofDays(1))
.isBefore(Instant.now()))
{
throw new SignatureException("Signature is expired");
}
} catch (CertificateException | CertPathValidatorException | IOException e) {
throw new SignatureException(e);
}
}
@Override
public ZoneOffset getStandardOffset(Instant instant) {
long epochSec = instant.getEpochSecond();
int index = Arrays.binarySearch(standardTransitions, epochSec);
if (index < 0) {
// switch negative insert position to start of matched range
index = -index - 2;
}
return standardOffsets[index + 1];
}
/**
* Returns Assets and metadata about assets activity (e.g. added, removed, no change) between
* between <code>asOf.minus(timespan)</code> and <code>asOf</code>.
*
* @param timeSpan The time-range to compare assets over.
* @param asOf The instant in time to query for. If null, current time is assumed.
*/
// [START list_asset_changes_status_changes]
static ImmutableList<ListAssetsResult> listAssetAndStatusChanges(
OrganizationName organizationName, Duration timeSpan, Instant asOf) {
try (SecurityCenterClient client = SecurityCenterClient.create()) {
// Start setting up a request for to search for all assets in an organization.
// OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324");
ListAssetsRequest.Builder request =
ListAssetsRequest.newBuilder()
.setParent(organizationName.toString())
.setFilter(
"security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"");
request
.getCompareDurationBuilder()
.setSeconds(timeSpan.getSeconds())
.setNanos(timeSpan.getNano());
// Set read time to either the instant passed in or now.
asOf = MoreObjects.firstNonNull(asOf, Instant.now());
request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano());
// Call the API.
ListAssetsPagedResponse response = client.listAssets(request.build());
// This creates one list for all assets. If your organization has a large number of assets
// this can cause out of memory issues. You can process them incrementally by returning
// the Iterable returned response.iterateAll() directly.
ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll());
System.out.println("Projects:");
System.out.println(results);
return results;
} catch (IOException e) {
throw new RuntimeException("Couldn't create client.", e);
}
}
private void setupBuildSection() {
buildNameView.setText(BuildConfig.VERSION_NAME);
buildCodeView.setText(String.valueOf(BuildConfig.VERSION_CODE));
buildShaView.setText(BuildConfig.GIT_SHA);
TemporalAccessor buildTime = Instant.ofEpochSecond(BuildConfig.GIT_TIMESTAMP);
buildDateView.setText(DATE_DISPLAY_FORMAT.format(buildTime));
}
/** Example of running a query with timestamp query parameters. */
public void runQueryWithTimestampParameters() throws InterruptedException {
// [START bigquery_query_params_timestamps]
// BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
ZonedDateTime timestamp = LocalDateTime.of(2016, 12, 7, 8, 0, 0).atZone(ZoneOffset.UTC);
String query = "SELECT TIMESTAMP_ADD(@ts_value, INTERVAL 1 HOUR);";
// Note: Standard SQL is required to use query parameters.
QueryJobConfiguration queryConfig =
QueryJobConfiguration.newBuilder(query)
.addNamedParameter(
"ts_value",
QueryParameterValue.timestamp(
// Timestamp takes microseconds since 1970-01-01T00:00:00 UTC
timestamp.toInstant().toEpochMilli() * 1000))
.build();
// Print the results.
DateTimeFormatter formatter = DateTimeFormatter.ISO_INSTANT.withZone(ZoneOffset.UTC);
for (FieldValueList row : bigquery.query(queryConfig).iterateAll()) {
System.out.printf(
"%s\n",
formatter.format(
Instant.ofEpochMilli(
// Timestamp values are returned in microseconds since 1970-01-01T00:00:00
// UTC,
// but org.joda.time.DateTime constructor accepts times in milliseconds.
row.get(0).getTimestampValue() / 1000)
.atOffset(ZoneOffset.UTC)));
System.out.printf("\n");
}
// [END bigquery_query_params_timestamps]
}
public void setDate(LocalDate date) {
//CONVERT LocalDate args into MS DateFromat String
Instant instant = date.atStartOfDay(ZoneId.of("UTC").normalized()).toInstant();
long timeInMillis = instant.toEpochMilli();
this.date = "/Date(" + Long.toString(timeInMillis) + "+0000)/";
}
public void test_London_preTimeZones() {
ZoneRules test = europeLondon();
ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC);
Instant instant = old.toInstant();
ZoneOffset offset = ZoneOffset.ofHoursMinutesSeconds(0, -1, -15);
assertEquals(test.getOffset(instant), offset);
checkOffset(test, old.toLocalDateTime(), offset, 1);
assertEquals(test.getStandardOffset(instant), offset);
assertEquals(test.getDaylightSavings(instant), Duration.ZERO);
assertEquals(test.isDaylightSavings(instant), false);
}
public void setExpectedPaymentDate(LocalDate expectedPaymentDate) {
//CONVERT LocalDate args into MS DateFromat String
Instant instant = expectedPaymentDate.atStartOfDay(ZoneId.of("UTC").normalized()).toInstant();
long timeInMillis = instant.toEpochMilli();
this.expectedPaymentDate = "/Date(" + Long.toString(timeInMillis) + "+0000)/";
}
public void setJournalDate(LocalDate journalDate) {
//CONVERT LocalDate args into MS DateFromat String
Instant instant = journalDate.atStartOfDay(ZoneId.of("UTC").normalized()).toInstant();
long timeInMillis = instant.toEpochMilli();
this.journalDate = "/Date(" + Long.toString(timeInMillis) + "+0000)/";
}
private static void printZone(Zone zone) {
System.out.printf("%nName: %s%n", zone.getName());
System.out.printf("ID: %s%n", zone.getGeneratedId());
System.out.printf("Description: %s%n", zone.getDescription());
System.out.printf(
"Created: %s%n", FORMATTER.format(Instant.ofEpochMilli(zone.getCreationTimeMillis())));
System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.getNameServers()));
}
@Override
protected void onRestart() {
// If locked and PIN enabled, display the PIN
if (!HentoidApp.isUnlocked() && !Preferences.getAppLockPin().isEmpty() && Preferences.isLockOnAppRestore()) {
// Evaluate if any set delay has passed; if so, the app gets locked
int lockDelayCode = Preferences.getLockTimer();
int lockDelaySec;
switch (lockDelayCode) {
case Preferences.Constant.PREF_LOCK_TIMER_10S:
lockDelaySec = 10;
break;
case Preferences.Constant.PREF_LOCK_TIMER_30S:
lockDelaySec = 30;
break;
case Preferences.Constant.PREF_LOCK_TIMER_1M:
lockDelaySec = 60;
break;
case Preferences.Constant.PREF_LOCK_TIMER_2M:
lockDelaySec = 120;
break;
default:
lockDelaySec = 0;
}
if ((Instant.now().toEpochMilli() - HentoidApp.getLockInstant()) / 1000 > lockDelaySec) {
Intent intent = new Intent(this, UnlockActivity.class);
startActivity(intent);
} else {
HentoidApp.setUnlocked(true); // Auto-unlock when we're back to the app under the delay
}
}
super.onRestart();
}
public void setDate(LocalDate date) {
//CONVERT LocalDate args into MS DateFromat String
Instant instant = date.atStartOfDay(ZoneId.of("UTC").normalized()).toInstant();
long timeInMillis = instant.toEpochMilli();
this.date = "/Date(" + Long.toString(timeInMillis) + "+0000)/";
}
public LongPositionVector(
Optional<Address> address,
Instant timestamp,
Position position,
boolean isPositionConfident,
double speedMetersPerSecond,
double headingDegreesFromNorth)
{
this.address = address;
this.timestamp = timestamp;
this.position = position;
this.isPositionConfident = isPositionConfident;
this.speedMetersPerSecond = speedMetersPerSecond;
this.headingDegreesFromNorth = headingDegreesFromNorth;
}
public void setPayPeriodEndDate(LocalDate payPeriodEndDate) {
//CONVERT LocalDate args into MS DateFromat String
Instant instant = payPeriodEndDate.atStartOfDay(ZoneId.of("UTC").normalized()).toInstant();
long timeInMillis = instant.toEpochMilli();
this.payPeriodEndDate = "/Date(" + Long.toString(timeInMillis) + "+0000)/";
}
public void test_NewYork_preTimeZones() {
ZoneRules test = americaNewYork();
ZonedDateTime old = createZDT(1800, 1, 1, ZoneOffset.UTC);
Instant instant = old.toInstant();
ZoneOffset offset = ZoneOffset.of("-04:56:02");
assertEquals(test.getOffset(instant), offset);
checkOffset(test, old.toLocalDateTime(), offset, 1);
assertEquals(test.getStandardOffset(instant), offset);
assertEquals(test.getDaylightSavings(instant), Duration.ZERO);
assertEquals(test.isDaylightSavings(instant), false);
}
public void setDate(LocalDate date) {
//CONVERT LocalDate args into MS DateFromat String
Instant instant = date.atStartOfDay(ZoneId.of("UTC").normalized()).toInstant();
long timeInMillis = instant.toEpochMilli();
this.date = "/Date(" + Long.toString(timeInMillis) + "+0000)/";
}
@Bean
@ConditionalOnMissingBean(ThreeTenModule.class)
ThreeTenModule threeTenModule() {
ThreeTenModule module = new ThreeTenModule();
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
return module;
}
public void setStartDate(LocalDate startDate) {
//CONVERT LocalDate args into MS DateFromat String
Instant instant = startDate.atStartOfDay(ZoneId.of("UTC").normalized()).toInstant();
long timeInMillis = instant.toEpochMilli();
this.startDate = "/Date(" + Long.toString(timeInMillis) + "+0000)/";
}
private void mergeInstantFields0(ZoneId selectedZone) {
Instant instant = Instant.ofEpochSecond(fieldValues.remove(INSTANT_SECONDS));
ChronoZonedDateTime<?> zdt = chrono.zonedDateTime(instant, selectedZone);
if (date == null) {
addObject(zdt.toLocalDate());
} else {
resolveMakeChanges(INSTANT_SECONDS, zdt.toLocalDate());
}
addFieldValue(SECOND_OF_DAY, (long) zdt.toLocalTime().toSecondOfDay());
}
@Override
public ZoneOffsetTransition nextTransition(Instant instant) {
if (savingsInstantTransitions.length == 0) {
return null;
}
long epochSec = instant.getEpochSecond();
// check if using last rules
if (epochSec >= savingsInstantTransitions[savingsInstantTransitions.length - 1]) {
if (lastRules.length == 0) {
return null;
}
// search year the instant is in
int year = findYear(epochSec, wallOffsets[wallOffsets.length - 1]);
ZoneOffsetTransition[] transArray = findTransitionArray(year);
for (ZoneOffsetTransition trans : transArray) {
if (epochSec < trans.toEpochSecond()) {
return trans;
}
}
// use first from following year
if (year < Year.MAX_VALUE) {
transArray = findTransitionArray(year + 1);
return transArray[0];
}
return null;
}
// using historic rules
int index = Arrays.binarySearch(savingsInstantTransitions, epochSec);
if (index < 0) {
index = -index - 1; // switched value is the next transition
} else {
index += 1; // exact match, so need to add one to get the next
}
return new ZoneOffsetTransition(savingsInstantTransitions[index], wallOffsets[index], wallOffsets[index + 1]);
}
@Override
public ZoneOffset getOffset(Instant instant) {
long epochSec = instant.getEpochSecond();
// check if using last rules
if (lastRules.length > 0 &&
epochSec > savingsInstantTransitions[savingsInstantTransitions.length - 1]) {
int year = findYear(epochSec, wallOffsets[wallOffsets.length - 1]);
ZoneOffsetTransition[] transArray = findTransitionArray(year);
ZoneOffsetTransition trans = null;
for (int i = 0; i < transArray.length; i++) {
trans = transArray[i];
if (epochSec < trans.toEpochSecond()) {
return trans.getOffsetBefore();
}
}
return trans.getOffsetAfter();
}
// using historic rules
int index = Arrays.binarySearch(savingsInstantTransitions, epochSec);
if (index < 0) {
// switch negative insert position to start of matched range
index = -index - 2;
}
return wallOffsets[index + 1];
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Fixed) {
return offset.equals(((Fixed) obj).offset);
}
if (obj instanceof StandardZoneRules) {
StandardZoneRules szr = (StandardZoneRules) obj;
return szr.isFixedOffset() && offset.equals(szr.getOffset(Instant.EPOCH));
}
return false;
}
private void moveToErrors(long contentId) {
Content content = dao.selectContent(contentId);
if (null == content) return;
content.setStatus(StatusContent.ERROR);
content.setDownloadDate(Instant.now().toEpochMilli()); // Needs a download date to appear the right location when sorted by download date
dao.insertContent(content);
dao.deleteQueue(content);
HentoidApp.trackDownloadEvent("Error");
notificationManager.notify(new DownloadErrorNotification(content));
}
public LongPositionVector(
Address address,
Instant timestamp,
Position position,
boolean isPositionConfident,
double speedMetersPerSecond,
double headingDegreesFromNorth)
{
this(Optional.of(address),
timestamp,
position,
isPositionConfident,
speedMetersPerSecond,
headingDegreesFromNorth);
}
@Test
public void now_Clock() {
Instant instant = LocalDateTime.of(2010, 12, 31, 0, 0).toInstant(ZoneOffset.UTC);
Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
YearMonth test = YearMonth.now(clock);
assertEquals(test.getYear(), 2010);
assertEquals(test.getMonth(), Month.DECEMBER);
}
@Bean
@ConditionalOnMissingBean(ThreeTenModule.class)
ThreeTenModule threeTenModule() {
ThreeTenModule module = new ThreeTenModule();
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
return module;
}
public void setTerminationDate(LocalDate terminationDate) {
//CONVERT LocalDate args into MS DateFromat String
Instant instant = terminationDate.atStartOfDay(ZoneId.of("UTC").normalized()).toInstant();
long timeInMillis = instant.toEpochMilli();
this.terminationDate = "/Date(" + Long.toString(timeInMillis) + "+0000)/";
}