001/* 002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * stan 011 * 012 * $Id$ 013 */ 014 015package org.nuxeo.ecm.platform.rendering.fm.extensions; 016 017import java.text.DateFormat; 018import java.util.Date; 019import java.util.List; 020import java.util.Locale; 021 022import freemarker.template.SimpleDate; 023import freemarker.template.SimpleScalar; 024import freemarker.template.TemplateMethodModelEx; 025import freemarker.template.TemplateModelException; 026 027/** 028 * Format a date with the specified locale. 029 * 030 * @author <a href="mailto:stan@nuxeo.com">Sun Seng David TAN</a> 031 */ 032public class FormatDate implements TemplateMethodModelEx { 033 034 public Object exec(List arguments) throws TemplateModelException { 035 if (arguments.size() != 2) { 036 throw new TemplateModelException( 037 "Invalid number of arguments for formatDate(Date date, String locale) method"); 038 } 039 if (!(arguments.get(0) instanceof SimpleDate && arguments.get(1) instanceof SimpleScalar)) { 040 throw new TemplateModelException( 041 "Invalid arguments format for the method formatDate : expecting (Date date, String local)."); 042 } 043 SimpleScalar scalar = (SimpleScalar) arguments.get(1); 044 if (scalar == null) { 045 throw new TemplateModelException("the argument local is not defined"); 046 } 047 048 SimpleDate simpledate = (SimpleDate) arguments.get(0); 049 if (simpledate == null) { 050 throw new TemplateModelException("the argument date is not defined"); 051 } 052 053 Date date = simpledate.getAsDate(); 054 055 Locale locale = new Locale(scalar.getAsString()); 056 057 DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, locale); 058 059 return new SimpleScalar(df.format(date)); 060 } 061 062}