Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CedarJava/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
# Changelog

## Unreleased
* Added Schema conversion APIs [#325](https://github.com/cedar-policy/cedar-java/pull/325)
* Added Level Validation [#327](https://github.com/cedar-policy/cedar-java/pull/327)
* Added DateTime extension support [#328](https://github.com/cedar-policy/cedar-java/pull/328)

## 4.3.1
### Added
* Added Zig version validation for publishing artifacts [#306](https://github.com/cedar-policy/cedar-java/pull/306)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.cedarpolicy.model.exception.InvalidValueDeserializationException;
import com.cedarpolicy.value.CedarList;
import com.cedarpolicy.value.CedarMap;
import com.cedarpolicy.value.DateTime;
import com.cedarpolicy.value.Decimal;
import com.cedarpolicy.value.EntityIdentifier;
import com.cedarpolicy.value.EntityTypeName;
Expand Down Expand Up @@ -74,8 +75,7 @@ public Value deserialize(JsonParser parser, DeserializationContext context) thro
} else if (node.isObject()) {
Iterator<Map.Entry<String, JsonNode>> iter = node.fields();
// Do two passes, one to check if it is an escaped entity or extension and a second to
// write into a
// map
// write into a map
EscapeType escapeType = EscapeType.UNRECOGNIZED;
int count = 0;
while (iter.hasNext()) {
Expand Down Expand Up @@ -127,6 +127,8 @@ public Value deserialize(JsonParser parser, DeserializationContext context) thro
return new Decimal(arg.textValue());
} else if (fn.textValue().equals("unknown")) {
return new Unknown(arg.textValue());
} else if (fn.textValue().equals("datetime")) {
return new DateTime(arg.textValue());
} else {
throw new InvalidValueDeserializationException(parser,
"Invalid function type: " + fn.toString(), node.asToken(), Map.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.cedarpolicy.model.exception.InvalidValueSerializationException;
import com.cedarpolicy.value.CedarList;
import com.cedarpolicy.value.CedarMap;
import com.cedarpolicy.value.DateTime;
import com.cedarpolicy.value.Decimal;
import com.cedarpolicy.value.EntityUID;
import com.cedarpolicy.value.IpAddress;
Expand Down Expand Up @@ -102,6 +103,16 @@ public void serialize(
jsonGenerator.writeString(value.toString());
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
} else if (value instanceof DateTime) {
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName(EXTENSION_ESCAPE_SEQ);
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("fn");
jsonGenerator.writeString("datetime");
jsonGenerator.writeFieldName("arg");
jsonGenerator.writeString(value.toString());
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
} else {
// It is recommended that you extend the Value classes in
// main.java.com.cedarpolicy.model.value or that you convert your class to a CedarMap
Expand Down
125 changes: 125 additions & 0 deletions CedarJava/src/main/java/com/cedarpolicy/value/DateTime.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* Copyright Cedar Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.cedarpolicy.value;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
* Represents a Cedar datetime extension value. DateTime values are encoded as strings in the
* following formats (Follows ISO 8601 standard):
*
* "YYYY-MM-DD" (date only) "YYYY-MM-DDThh:mm:ssZ" (UTC) "YYYY-MM-DDThh:mm:ss.SSSZ" (UTC with
* millisecond precision) "YYYY-MM-DDThh:mm:ss(+/-)hhmm" (With timezone offset in hours and minutes)
* "YYYY-MM-DDThh:mm:ss.SSS(+/-)hhmm" (With timezone offset in hours and minutes and millisecond
* precision)
*
*/
public class DateTime extends Value {

private static class DateTimeValidator {

private static final List<DateTimeFormatter> FORMATTERS = Arrays.asList(
DateTimeFormatter.ofPattern("uuuu-MM-dd").withResolverStyle(ResolverStyle.STRICT),
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss'Z'")
.withResolverStyle(ResolverStyle.STRICT),
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS'Z'")
.withResolverStyle(ResolverStyle.STRICT),
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXX")
.withResolverStyle(ResolverStyle.STRICT),
DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXX")
.withResolverStyle(ResolverStyle.STRICT));

/**
* Validates a datetime string against the supported formats. Automatically enforces range
* constraints: - Month: 01-12 - Day: 01-31 (considering month-specific limits) - Hour:
* 00-23 - Minute: 00-59 - Second: 00-59
*
* @param dateTimeString the string to validate
* @return true if valid, false otherwise
*/
public static boolean isValid(String dateTimeString) {
if (dateTimeString == null || dateTimeString.trim().isEmpty()) {
return false;
}

return FORMATTERS.stream().anyMatch(formatter -> canParse(formatter, dateTimeString));
}

private static boolean canParse(DateTimeFormatter formatter, String dateTimeString) {
try {
formatter.parse(dateTimeString);
return true;
} catch (DateTimeParseException e) {
return false;
}
}
}

/** Datetime as a string. */
private final String dateTime;

/**
* Construct DateTime.
*
* @param dateTime DateTime as a String.
*/
@SuppressFBWarnings("CT_CONSTRUCTOR_THROW")
public DateTime(String dateTime) throws NullPointerException, IllegalArgumentException {
if (!DateTimeValidator.isValid(dateTime)) {
throw new IllegalArgumentException(
"Input string is not a valid DateTime format: " + dateTime);
}
this.dateTime = dateTime;
}

/** Convert DateTime to Cedar expr that can be used in a Cedar policy. */
@Override
public String toCedarExpr() {
return "datetime(\"" + dateTime + "\")";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worried about this being valid, but should be fine since dateTime is validated on construction, cannot be mutated externally since it's private and it's set once.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. It's final and only assigned after validation so should be ok. This is what we do for IpAddress as well

}

/** Equals. */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DateTime dateTime1 = (DateTime) o;
return dateTime.equals(dateTime1.dateTime);
}

/** Hash. */
@Override
public int hashCode() {
return Objects.hash(dateTime);
}

/** As a string. */
@Override
public String toString() {
return dateTime;
}
}
Loading