Skip to content

Commit

Permalink
Add generation timestamp to metadata (#516)
Browse files Browse the repository at this point in the history
* Add generation timestamp to metadata

Co-authored-by: Daniel Beck <daniel-beck@users.noreply.github.com>
  • Loading branch information
daniel-beck and daniel-beck authored Apr 27, 2021
1 parent 4d0e446 commit ce77209
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/main/java/io/jenkins/update_center/json/WithSignature.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,32 @@
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.security.GeneralSecurityException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
* Support generation of JSON output with included checksum + signatures block for the same JSON output.
*/
public abstract class WithSignature {
private JsonSignature signature;
private final String generationTimestamp = DateTimeFormatter.ISO_DATE_TIME.format(Instant.now().atOffset(ZoneOffset.UTC).withNano(0));

@JSONField
public JsonSignature getSignature() {
return signature;
}

/**
* Returns a string with the current date and time in ISO-8601 format.
* It doesn't have fractional seconds and the timezone is always UTC ('Z').
*
* @return a string with the current date and time in the format YYYY-MM-DD'T'HH:mm:ss'Z'
*/
public String getGenerationTimestamp() {
return generationTimestamp;
}

/**
* Generate JSON checksums and add a signature block to the JSON written to the specified {@link Writer}.
*
Expand Down
29 changes: 29 additions & 0 deletions src/test/java/io/jenkins/update_center/TimestampTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package io.jenkins.update_center;

import io.jenkins.update_center.json.WithSignature;
import org.junit.Assert;
import org.junit.Test;

import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class TimestampTest {
@Test
public void checkTimestamp() throws Exception {
WithSignature w = new WithSignature() {
};

String timestamp = w.getGenerationTimestamp();

Assert.assertTrue("format as expected", timestamp.matches("^202[0-9][-][0-9]{2}[-][0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$"));

Instant parsed = Instant.parse(timestamp);

Assert.assertTrue("before now", parsed.isBefore(Instant.now()));
Assert.assertTrue("very recent", parsed.isAfter(Instant.now().minus(1, ChronoUnit.SECONDS)));

String timestamp2 = w.getGenerationTimestamp();
Assert.assertEquals("Doesn't change over time", timestamp, timestamp2);

}
}

0 comments on commit ce77209

Please sign in to comment.