001/* 002 * Copyright 2021 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.runtime.i18n; 017 018import java.time.LocalDate; 019import java.time.format.DateTimeFormatter; 020import java.time.format.FormatStyle; 021import java.util.Locale; 022 023import org.apache.cocoon.transformation.I18nTransformer; 024import org.apache.cocoon.xml.AttributesImpl; 025import org.xml.sax.ContentHandler; 026import org.xml.sax.SAXException; 027 028import org.ametys.core.util.DateUtils; 029 030/** 031 * Allow to use {@link LocalDate} as a parameter for {@link I18nizableText}. 032 */ 033public class I18nizableDate implements FormatableI18nizable, I18nizableTextParameter 034{ 035 private LocalDate _date; 036 private DateTimeFormatter _formatter; 037 private String _pattern; 038 039 /** 040 * Build an {@link I18nizableDate} from {@link LocalDate} and style. 041 * @param date the value 042 * @param style the style to use for formatting 043 */ 044 public I18nizableDate(LocalDate date, FormatStyle style) 045 { 046 _date = date; 047 _formatter = DateTimeFormatter.ofLocalizedDate(style); 048 _pattern = style.name(); 049 } 050 051 /** 052 * Build an {@link I18nizableDate} from {@link LocalDate} and pattern. 053 * @param date the value 054 * @param pattern the pattern to use for formatting 055 */ 056 public I18nizableDate(LocalDate date, String pattern) 057 { 058 _date = date; 059 _formatter = DateTimeFormatter.ofPattern(pattern); 060 _pattern = pattern; 061 } 062 063 public void toSAX(ContentHandler handler) throws SAXException 064 { 065 AttributesImpl atts = new AttributesImpl(); 066 atts.addCDATAAttribute(I18nTransformer.I18N_NAMESPACE_URI, "pattern", "pattern", _pattern); 067 atts.addCDATAAttribute(I18nTransformer.I18N_NAMESPACE_URI, "src-pattern", "src-pattern", "yyyy-MM-dd"); 068 atts.addCDATAAttribute(I18nTransformer.I18N_NAMESPACE_URI, "value", "value", DateUtils.localDateToString(_date)); 069 070 handler.startElement(I18nTransformer.I18N_NAMESPACE_URI, "date", "i18n:date", atts); 071 handler.endElement(I18nTransformer.I18N_NAMESPACE_URI, "date", "i18n:date"); 072 } 073 074 public void toSAXAsParam(ContentHandler handler) throws SAXException 075 { 076 toSAX(handler); 077 } 078 079 public String format(Locale locale) 080 { 081 return _formatter.withLocale(locale).format(_date); 082 } 083}