001/* 002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 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 * 016 * Contributors: 017 * stan 018 * 019 * $Id$ 020 */ 021 022package org.nuxeo.ecm.platform.rendering.fm.extensions; 023 024import java.text.DateFormat; 025import java.util.Date; 026import java.util.List; 027import java.util.Locale; 028 029import freemarker.template.SimpleDate; 030import freemarker.template.SimpleScalar; 031import freemarker.template.TemplateMethodModelEx; 032import freemarker.template.TemplateModelException; 033 034/** 035 * Format a date with the specified locale. 036 * 037 * @author <a href="mailto:stan@nuxeo.com">Sun Seng David TAN</a> 038 */ 039public class FormatDate implements TemplateMethodModelEx { 040 041 @Override 042 public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { 043 if (arguments.size() != 2) { 044 throw new TemplateModelException( 045 "Invalid number of arguments for formatDate(Date date, String locale) method"); 046 } 047 if (!(arguments.get(0) instanceof SimpleDate && arguments.get(1) instanceof SimpleScalar)) { 048 throw new TemplateModelException( 049 "Invalid arguments format for the method formatDate : expecting (Date date, String local)."); 050 } 051 SimpleScalar scalar = (SimpleScalar) arguments.get(1); 052 if (scalar == null) { 053 throw new TemplateModelException("the argument local is not defined"); 054 } 055 056 SimpleDate simpledate = (SimpleDate) arguments.get(0); 057 if (simpledate == null) { 058 throw new TemplateModelException("the argument date is not defined"); 059 } 060 061 Date date = simpledate.getAsDate(); 062 063 Locale locale = new Locale(scalar.getAsString()); 064 065 DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale); 066 067 return new SimpleScalar(df.format(date)); 068 } 069 070}