- From: Jean-Guilhem Rouel via cvs-syncmail <cvsmail@w3.org>
- Date: Fri, 28 Aug 2009 12:39:58 +0000
- To: www-validator-cvs@w3.org
Update of /sources/public/2006/unicorn/src/org/w3c/unicorn/util In directory hutz:/tmp/cvs-serv22368/src/org/w3c/unicorn/util Added Files: ListFiles.java LocaleFactory.java Templates.java TemplateHelper.java Property.java Unmarshaller.java LocalizedString.java UCNProperties.java XHTMLize.java Log Message: Merging dev2 in HEAD --- NEW FILE: LocalizedString.java --- // $Id: LocalizedString.java,v 1.2 2009/08/28 12:39:56 jean-gui Exp $ // Author: Jean-Guilhem Rouel // (c) COPYRIGHT MIT, ERCIM and Keio, 2006. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.unicorn.util; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * LocalizedString<br /> * Created: May 30, 2006 11:55:23 AM<br /> * * @author Jean-Guilhem ROUEL & Damien LEROY */ public class LocalizedString { private static final Log logger = LogFactory.getLog(LocalizedString.class); private static String DEFAULT_LANGUAGE = "en"; private Map<String, String> mapOfString = null; /** * Default constructor for LocalizedString. * */ public LocalizedString() { LocalizedString.logger.trace("Constructor"); this.mapOfString = new LinkedHashMap<String, String>(); } /** * Constructs a LocalizedString with an initial string paired with a * language. * * @param s * The string to be localized. * @param lang * The corresponding language. */ public LocalizedString(String s, String lang) { this(); mapOfString.put(lang, s); } /** * Looks for the existence of a specified sLocale string in the map. * * @param sLocale * The string to look for. * @return True if the sLocale string is in the map, else false. */ public boolean hasLocale(final String sLocale) { return null != this.mapOfString.get(sLocale); } /** * Adds a message and its corresponding localization to the mapOfString * attribute. * * @param sLocale * The localization. * @param sMessage * The message to be written. * @return The previous value associated with specified key, or null if * there was no mapping for key. */ public String addLocalization(final String sLocale, final String sMessage) { LocalizedString.logger.trace("addLocalization"); LocalizedString.logger.debug("Locale : " + sLocale + "."); LocalizedString.logger.debug("Message : " + sMessage + "."); return this.mapOfString.put(sLocale, sMessage); } /** * Finds and returns the message corresponding to the specified localization * in the mapOfString. * * @param sLocale * The localization wanted. * @return The message corresponding to the localization or if there's none, * the one corresponding to the default language. */ public String getLocalization(final String sLocale) { final String sMessage = this.mapOfString.get(sLocale); if (null != sMessage) { return sMessage; } return this.mapOfString.get(Property.get("DEFAULT_LANGUAGE")); } /** * Returns the keys available in the mapOfString. * * @return A set with all the keys. */ public Set<String> getSetOfLocale() { return this.mapOfString.keySet(); } /** * Returns the message in in DEFAULT_LANGUAGE (en) or in the first language * in the list. */ @Override public String toString() { String res = this.mapOfString.get(Property.get("DEFAULT_LANGUAGE")); if (res == null) { for (String s : this.mapOfString.values()) { return s; } } if (res == null) { return ""; } return res; } } --- NEW FILE: TemplateHelper.java --- // $Id: TemplateHelper.java,v 1.2 2009/08/28 12:39:56 jean-gui Exp $ // Author: Thomas GAMBET. // (c) COPYRIGHT MIT, ERCIM ant Keio, 2009. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.unicorn.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.MalformedURLException; import java.util.Iterator; import java.util.Properties; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; import org.w3c.unicorn.Framework; /** * TemplateHelper provides functionalities to merge properties object, to load * properties objects in a velocity context, to get an internationalized * template, and to write internationalized templates to a file. * * @author Thomas GAMBET */ public class TemplateHelper { public static final Log logger = LogFactory.getLog(TemplateHelper.class); private static VelocityContext context = new VelocityContext(); private static VelocityEngine engine; // = new VelocityEngine(); public static void init() { engine = Framework.getVelocityEngine(); //Properties aProperties = new Properties(); /*Properties aProperties = Property.getProps("velocity.properties"); try { //aProperties.load(Property.getPropertyFileURL("velocity.properties") // .openStream()); aProperties.put(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Property.get("PATH_TO_TEMPLATES")); engine.init(aProperties); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ } @SuppressWarnings("finally") public static Properties getPropsFromFile(File propFile) { Properties props = new Properties(); try { props.load(propFile.toURI().toURL().openStream()); } catch (IOException e) { logger.error("Unable to load properties file : " + e.getMessage(), e); e.printStackTrace(); } finally { return props; } } public static Properties getMergeProps(Properties defaultProps, Properties sourceProps) { Properties propMerge = new Properties(); Set<Object> keys = defaultProps.keySet(); Iterator<Object> itr = keys.iterator(); String key; while (itr.hasNext()) { key = itr.next().toString(); if (sourceProps.containsKey(key)) { propMerge.put(key, sourceProps.get(key)); } else { propMerge.put(key, defaultProps.get(key)); } } keys = sourceProps.keySet(); itr = keys.iterator(); while (itr.hasNext()) { key = itr.next().toString(); if (!defaultProps.containsKey(key)) { propMerge.put(key, sourceProps.get(key)); } } return propMerge; } public static Properties getMergePropsFromFiles(File defaultPropFile, File sourcePropFile) { Properties defaultProps = new Properties(); Properties sourceProps = new Properties(); try { defaultProps.load(defaultPropFile.toURI().toURL().openStream()); } catch (IOException e) { logger.error("Unable to load default language properties : " + e.getMessage(), e); e.printStackTrace(); return null; } try { sourceProps.load(sourcePropFile.toURI().toURL().openStream()); } catch (IOException e) { logger.error("Unable to find desired language properties : " + e.getMessage(), e); e.printStackTrace(); return defaultProps; } return getMergeProps(defaultProps, sourceProps); /* * Properties propMerge = new Properties(); * * Set<Object> keys = defaultProps.keySet(); Iterator<Object> itr = * keys.iterator(); String key; * * while (itr.hasNext()) { key = itr.next().toString(); if * (sourceProps.containsKey(key)) propMerge.put(key, * sourceProps.get(key)); else propMerge.put(key, * defaultProps.get(key)); } * * return propMerge; */ } public static void loadInVelocityContext(Properties props, VelocityContext context) { Set<Object> keys = props.keySet(); Iterator<Object> itr = keys.iterator(); String key; while (itr.hasNext()) { key = itr.next().toString(); context.put(key, props.get(key)); } } public static Template getInternationalizedTemplate(String templateName, String langCode, VelocityContext context) { if (langCode != null) { context.put("lang", langCode); // Error templates have the same language properties file that their // coresponding non-error template String langFileName = templateName; if (templateName.length() > 6 && templateName.substring(templateName.length() - 6, templateName.length()).equals(".error")) { langFileName = templateName.substring(0, templateName.length() - 6); } // Language file for this template File langFile = new File(Property.get("PATH_TO_LANGUAGE_FILES") + langFileName + "." + langCode + ".properties"); // Default language file File defaultLangFile = new File(Property .get("PATH_TO_LANGUAGE_FILES") + langFileName + "." + Property.get("DEFAULT_LANGUAGE") + ".properties"); // Merge the properties or use default language Properties mergedProps = new Properties(); if (langFile.exists()) { mergedProps = getMergePropsFromFiles(defaultLangFile, langFile); } else { try { mergedProps.load(defaultLangFile.toURI().toURL() .openStream()); } catch (IOException e1) { logger.error("IOException : " + e1.getMessage(), e1); e1.printStackTrace(); } } File generalLangFile = new File(Property .get("PATH_TO_LANGUAGE_FILES") + "general." + langCode + ".properties"); if (!generalLangFile.exists()) { generalLangFile = new File(Property .get("PATH_TO_LANGUAGE_FILES") + "general." + Property.get("DEFAULT_LANGUAGE") + ".properties"); } mergedProps = getMergeProps(mergedProps, getPropsFromFile(generalLangFile)); // Load in velocity context TemplateHelper.loadInVelocityContext(mergedProps, context); } // Return the template try { Template resultTemplate = engine.getTemplate(templateName + ".vm", "UTF-8"); return resultTemplate; } catch (Exception e) { logger.error("Error : " + e.getMessage(), e); e.printStackTrace(); return null; } } public static String generateFileFromTemplate(String templateName, String langCode, String destination, String fileExtension, VelocityContext context) { String destFileName; String tempFileName; String[] split = templateName.split("/"); if (split.length > 0) { tempFileName = split[split.length - 1]; } else { tempFileName = templateName; } if (langCode != null) { destFileName = tempFileName + "." + langCode + "." + fileExtension; } else { destFileName = tempFileName + "." + fileExtension; } if ((new File(destination + destFileName)).exists()) { return destination + destFileName; } if (langCode != null) { File langFile = new File(Property.get("PATH_TO_LANGUAGE_FILES") + templateName + "." + langCode + ".properties"); if (!langFile.exists() && !langCode.equals(Property.get("DEFAULT_LANGUAGE"))) { return generateFileFromTemplate(templateName, Property .get("DEFAULT_LANGUAGE"), destination, fileExtension, context); } } Template template = getInternationalizedTemplate(templateName, langCode, context); try { OutputStreamWriter fileWriter = new OutputStreamWriter( new FileOutputStream(destination + destFileName), "UTF-8"); template.merge(context, fileWriter); fileWriter.close(); } catch (Exception e) { logger.error("Error : " + e.getMessage(), e); e.printStackTrace(); } return destination + destFileName; } public static String generateFileFromTemplate(String templateName, String langCode, String destination, String fileExtension) { return generateFileFromTemplate(templateName, langCode, destination, fileExtension, context); } } --- NEW FILE: Unmarshaller.java --- // $Id: Unmarshaller.java,v 1.2 2009/08/28 12:39:56 jean-gui Exp $ // Author: Damien LEROY. // (c) COPYRIGHT MIT, ERCIM ant Keio, 2006. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.unicorn.util; import java.io.IOException; import java.net.URL; /** * Interface for all unmarshaller class in package unicorn. * * @author Damien LEROY */ public interface Unmarshaller { public void addURL(final URL aURL) throws IOException; public void unmarshal() throws Exception; } --- NEW FILE: LocaleFactory.java --- // $Id: LocaleFactory.java,v 1.2 2009/08/28 12:39:56 jean-gui Exp $ // Author: Jean-Guilhem Rouel // (c) COPYRIGHT MIT, ERCIM and Keio, 2006. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.unicorn.util; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Locale; /** * LocaleFactory<br /> * Created: May 30, 2006 12:08:37 PM<br /> * * @author Jean-Guilhem ROUEL */ public class LocaleFactory { private static final LinkedHashMap<String, Locale> mapOfLocale = new LinkedHashMap<String, Locale>(); /** * Finds a Locale object among the mapOfLocale entries, given its name. * * @param sLocale * The name of the Locale. * @return The corresponding Locale object. */ public static Locale getLocale(final String sLocale) { return LocaleFactory.mapOfLocale.get(sLocale); } /** * Returns the values available in the mapOfLocale. * * @return The collection of values. */ public static Collection<Locale> values() { return LocaleFactory.mapOfLocale.values(); } static { final Locale[] tLocale = Locale.getAvailableLocales(); for (final Locale aLocale : tLocale) { final String sLanguage = aLocale.getLanguage(); final String sCountry = aLocale.getCountry(); LocaleFactory.mapOfLocale.put(sLanguage + "-" + sCountry, aLocale); } } } --- NEW FILE: Templates.java --- package org.w3c.unicorn.util; import java.io.Writer; import org.apache.velocity.VelocityContext; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; import org.w3c.unicorn.Framework; public class Templates { public static void write(String templateName, VelocityContext context, Writer writer) { try { Framework.getVelocityEngine().mergeTemplate(templateName, "UTF-8", context, writer); } catch (ResourceNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseErrorException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MethodInvocationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } --- NEW FILE: XHTMLize.java --- package org.w3c.unicorn.util; import org.apache.commons.lang.StringEscapeUtils; import org.apache.velocity.app.event.ReferenceInsertionEventHandler; import org.w3c.unicorn.Framework; import org.w3c.unicorn.response.A; import org.w3c.unicorn.response.Code; import org.w3c.unicorn.response.Img; /** * Escape all XML Entities in the reference insertion. Specifically, the * following conversions are performed: * <DL> * <DT>&</DT> * <DD>&amp;</DD> * <DT><</DT> * <DD>&lt;</DD> * <DT>></DT> * <DD>&gt;</DD> * <DT>"</DT> * <DD>&quot;</DD> * </DL> * * @author <a href="mailto:wglass@forio.com">Will Glass-Husain</a> */ public class XHTMLize implements ReferenceInsertionEventHandler { /** * Escape the XML entities for all inserted references. */ public Object referenceInsert(final String sReference, final Object oValue) { if (oValue == null) { return null; } if (oValue instanceof A) { A link = (A) oValue; return insertA(link); } if (oValue instanceof Img) { Img image = (Img) oValue; return insertImg(image); } if (oValue instanceof Code) { Code code = (Code) oValue; return insertCode(code); } if (sReference.startsWith("$noEscape_")) return oValue.toString(); else return StringEscapeUtils.escapeHtml(oValue.toString()); } /** * Insert a link * * @param aLink * link to insert * @return return the object containing the link */ private Object insertA(final A aLink) { String sResultat = "<a href=\"" + StringEscapeUtils.escapeHtml(aLink.getHref()) + "\">"; for (final Object oElement : aLink.getContent()) { if (oElement instanceof Img) { sResultat += insertImg((Img) oElement); } else { sResultat += StringEscapeUtils.escapeHtml(oElement.toString()); } } sResultat += "</a>"; return sResultat; } /** * Insert code tag into the tags * * @param aCode * code to insert * @return object with code inserted */ private Object insertCode(final Code aCode) { String sResultat = "<code>"; for (final Object oElement : aCode.getContent()) { if (oElement instanceof A) { sResultat += insertA((A) oElement); } else if (oElement instanceof Img) { sResultat += insertImg((Img) oElement); } else { sResultat += StringEscapeUtils.escapeHtml(oElement.toString()); } } sResultat += "</code>"; return sResultat; } /** * Insert an img tag * * @param img * image path to insert * @return the string containing the image tag */ private String insertImg(final Img aImage) { return "<img src=\"" + StringEscapeUtils.escapeHtml(aImage.getSrc()) + "\" alt=\"" + StringEscapeUtils.escapeHtml(aImage.getAlt()) + "\"/>"; } } --- NEW FILE: UCNProperties.java --- package org.w3c.unicorn.util; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; public class UCNProperties extends Properties { private static final long serialVersionUID = 1L; static Logger logger = Logger.getLogger("Framework"); private Pattern pattern = Pattern.compile("\\$\\{[a-zA-Z_0-9]*\\}"); @Override public synchronized void load(InputStream inStream) throws IOException { super.load(inStream); this.parse(); } public void parse() { for(Object key : this.keySet()) { logger.trace("Parsing Property : \"" + key + "\" => \"" + this.getProperty((String) key)); Matcher matcher = pattern.matcher(this.getProperty((String) key)); if (matcher.find()) { matcher.reset(); while (matcher.find()) { String match = matcher.group(); logger.trace("> Pattern matched with: \"" + match + "\""); String foundKey = (String) match.subSequence(2, match.length()-1); if (!this.containsKey(foundKey)) { logger.warn("> String \"" + foundKey + "\" is not an existing property."); } else { String foundProp = this.getProperty(foundKey); logger.trace("> Found coresponding property: \"" + foundKey + "\" => \"" + foundProp +"\""); String subst = this.getProperty((String) key); subst = subst.replace(match, foundProp); this.put(key, subst); matcher = pattern.matcher(this.getProperty((String) key)); } } logger.trace("> Parsed property: \"" + key + "\" => \"" + this.getProperty((String) key) + "\""); } else { logger.trace("> No nested property found"); } } } @Override public String toString() { String result = ""; for(Object key : this.keySet()) { result += "\n\t"+key+"\t=>\t"+this.getProperty((String) key); } return result; } } --- NEW FILE: Property.java --- package org.w3c.unicorn.util; import java.util.Properties; import org.w3c.unicorn.Framework; public class Property { public static String get(String key) { return Framework.getUnicornPropertiesFiles().get("unicorn.properties").getProperty(key); } public static String get(String key1, String key2) { return Framework.getUnicornPropertiesFiles().get("unicorn.properties").getProperty(key1) + Framework.getUnicornPropertiesFiles().get("unicorn.properties").getProperty(key2); } public static Properties getProps(String fileName) { return Framework.getUnicornPropertiesFiles().get(fileName); } } --- NEW FILE: ListFiles.java --- // $Id: ListFiles.java,v 1.2 2009/08/28 12:39:56 jean-gui Exp $ // Author: Jean-Guilhem Rouel // (c) COPYRIGHT MIT, ERCIM and Keio, 2006. // Please first read the full copyright statement in file COPYRIGHT.html package org.w3c.unicorn.util; import java.io.File; import java.io.FileFilter; import java.io.FileNotFoundException; import java.io.FilenameFilter; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * ListFiles<br /> * Created: Jun 26, 2006 2:17:42 PM<br /> * This class provides static methods to list files into a directory. * * @author Jean-Guilhem ROUEL */ public class ListFiles { private static final Log logger = LogFactory.getLog(ListFiles.class); /** * List all files matching a pattern in a directory * * @param sDirectory * the directory to list * @param sFilterPattern * only filenames matching this pattern will be returned * @return an array of files matching the pattern * @throws FileNotFoundException */ public static File[] listFiles(final String sDirectory, final String sFilterPattern) {//throws FileNotFoundException { ListFiles.logger.trace("listFiles(String, String)"); ListFiles.logger.trace("Directory : " + sDirectory + "."); ListFiles.logger.trace("Filter pattern : " + sFilterPattern + "."); final File aDirectory = new File(sDirectory); final Pattern aPattern = Pattern.compile(sFilterPattern); final FilenameFilter aFilenameFilter = new FilenameFilter() { public boolean accept(File aDirectory, String sName) { File aFile = new File(aDirectory.getPath() + sName); if (aFile.isDirectory()) { return false; } Matcher matcher = aPattern.matcher(sName); return matcher.find(); } }; final File[] tFile = aDirectory.listFiles(aFilenameFilter); return tFile; } /** * List all files in a directory * * @param sDirectory * the directory to list * @return an array of files * @throws FileNotFoundException */ public static File[] listFiles(final String sDirectory) throws FileNotFoundException { ListFiles.logger.trace("listFiles(String)"); if (ListFiles.logger.isDebugEnabled()) { ListFiles.logger.debug("Directory : " + sDirectory + "."); } final File aDirectory = new File(sDirectory); final FileFilter aFileFilter = new FileFilter() { public boolean accept(File aFile) { return !aFile.isDirectory(); } }; final File[] tFile = aDirectory.listFiles(aFileFilter); if (null == tFile) { throw new FileNotFoundException("File in " + sDirectory + " not found."); } return tFile; } /** * For testing purpose * * @param args * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { File[] files = listFiles("/home/jean"); for (final File file : files) { System.out.println(file.getAbsolutePath()); } System.out.println("----------------------------------"); files = listFiles("/home/jean", ".+\\..+"); for (final File file : files) { System.out.println(file.getAbsolutePath()); } } }
Received on Friday, 28 August 2009 12:40:09 UTC