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:[email protected]">Sun Seng David TAN</a> 038 */ 039public class FormatDate implements TemplateMethodModelEx { 040 041 public Object exec(List arguments) throws TemplateModelException { 042 if (arguments.size() != 2) { 043 throw new TemplateModelException( 044 "Invalid number of arguments for formatDate(Date date, String locale) method"); 045 } 046 if (!(arguments.get(0) instanceof SimpleDate && arguments.get(1) instanceof SimpleScalar)) { 047 throw new TemplateModelException( 048 "Invalid arguments format for the method formatDate : expecting (Date date, String local)."); 049 } 050 SimpleScalar scalar = (SimpleScalar) arguments.get(1); 051 if (scalar == null) { 052 throw new TemplateModelException("the argument local is not defined"); 053 } 054 055 SimpleDate simpledate = (SimpleDate) arguments.get(0); 056 if (simpledate == null) { 057 throw new TemplateModelException("the argument date is not defined"); 058 } 059 060 Date date = simpledate.getAsDate(); 061 062 Locale locale = new Locale(scalar.getAsString()); 063 064 DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale); 065 066 return new SimpleScalar(df.format(date)); 067 } 068 069}