我正在尝试将一些代码从joda时间移植到Java时间。
JodaTime可以这样指定当年的后备值
parser.withDefaultYear((new DateTime(DateTimeZone.UTC)).getYear()).parseDateTime(text);
Run Code Online (Sandbox Code Playgroud)
不管解析器的外观如何(如果包含一年或不包含一年),都将对其进行解析。
那里的java.time变得更加严格。即使有DateTimeFormatterBuilder.parseDefaulting()允许您指定后备方法的方法,也只有在您要解析的日期中未指定该特定字段或将其标记为可选时,该方法才有效。
如果您对传入的日期格式没有任何控制权(由用户提供),则这将使调用时变得非常困难parseDefaulting。
是否有任何解决方法,可以在其中指定通用回退日期(如果未指定其值,则格式化程序将使用其值)之类的东西,或者在格式化程序中指定后,如何配置未使用的回退值?
以下是最小,完整和可验证的示例。
public static DateTimeFormatter ofPattern(String pattern) {
return new DateTimeFormatterBuilder()
.appendPattern(pattern)
.parseDefaulting(ChronoField.YEAR, 1970)
.toFormatter(Locale.ROOT);
}
public void testPatterns() {
// works
assertThat(LocalDate.from(ofPattern("MM/dd").parse("12/06")).toString(), is("1970-12-06"));
assertThat(LocalDate.from(ofPattern("uuuu/MM/dd").parse("2018/12/06")).toString(), is("2018-12-06"));
// fails with exception, as it uses year of era
assertThat(LocalDate.from(ofPattern("yyyy/MM/dd").parse("2018/12/06")).toString(), is("2018-12-06"));
}
Run Code Online (Sandbox Code Playgroud)
所需的结果:测试应解析字符串并通过(“呈绿色”)。
观察到的结果:测试的最后一行引发异常,并显示以下消息和堆栈跟踪。
文本'2018/12/06'无法解析:发现冲突:1970年与2018年不同
Exception in thread "main" java.time.format.DateTimeParseException: Text '2018/12/06' could not be parsed: Conflict found: Year 1970 differs from Year 2018
at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1959)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1820)
at com.ajax.mypackage.MyTest.testPatterns(MyTest.java:33) …Run Code Online (Sandbox Code Playgroud) 昨天我一直在深入研究 spring security yaml 以使其与 Okta SAML 一起使用。登录有效,但响应 XML 包含显然无法自动提取到属性映射中的用户属性。响应包含这样的字段
<saml2:Attribute Name="user.lastName" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:unspecified">
<saml2:AttributeValue xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="xs:string">
Surname
</saml2:AttributeValue>
</saml2:Attribute>
Run Code Online (Sandbox Code Playgroud)
一旦认证成功,我想把这些放在认证信息中。通过 github/oauth 登录时,OAuth2AuthenticatedPrincipal该类具有属性映射,但Saml2AuthenticatedPrincipal唯一具有名称。
解决这个问题的正确方法是什么?
现在我正在考虑通过第二次解析提供的 XML 响应(通过)(或将它们放入会话)AuthenticationSuccessHandler来填充Saml2AuthenticatedPrincipalWithAttributes包含所有属性的自定义类.getDetails()。
我有一种预感,这可能不是春季做事的方式,我很想获得第二意见。当你在谷歌搜索时主要找到 spring security saml 的例子,在它合并到 spring security 之前,它似乎处理的事情有点不同,因为提到的类不再存在。
感谢大家的帮助!