Nuiton-utils-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
August 2008
- 2 participants
- 110 discussions
[Lutinutil-commits] r966 - in trunk: lutinutil/src/main/java/org/codelutin/util lutinutil-no-i18n/src/main/java/org/codelutin/util
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
04 Aug '08
Author: tchemit
Date: 2008-08-04 14:07:30 +0000 (Mon, 04 Aug 2008)
New Revision: 966
Added:
trunk/lutinutil/src/main/java/org/codelutin/util/CollectionUtil.java
trunk/lutinutil/src/main/java/org/codelutin/util/FileUtil.java
trunk/lutinutil/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java
trunk/lutinutil/src/main/java/org/codelutin/util/SortedProperties.java
trunk/lutinutil/src/main/java/org/codelutin/util/StringUtil.java
trunk/lutinutil/src/main/java/org/codelutin/util/StringUtilException.java
Removed:
trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/CollectionUtil.java
trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/FileUtil.java
trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java
trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/SortedProperties.java
trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtil.java
trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtilException.java
Log:
go back to lutinutil : maven-i18n-plugin will not used the lutinutil dependancy anoy longer
Copied: trunk/lutinutil/src/main/java/org/codelutin/util/CollectionUtil.java (from rev 953, trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/CollectionUtil.java)
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/util/CollectionUtil.java (rev 0)
+++ trunk/lutinutil/src/main/java/org/codelutin/util/CollectionUtil.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -0,0 +1,155 @@
+/* *##%
+ * Copyright (C) 2006
+ * Code Lutin, C�dric Pineau, Benjamin Poussin
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *##%*/
+
+/* *
+ * CollectionUtil.java
+ *
+ * Created: 23 f�vr. 2006 09:03:39
+ *
+ * @author poussin
+ * @version $Revision$
+ *
+ * Last update: $Date$
+ * by : $Author$
+ */
+
+package org.codelutin.util;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+
+/** @author poussin */
+
+public class CollectionUtil {
+
+ /**
+ * Ajoute a la collection tous les elements pass�s en parametre
+ *
+ * @param col la collection
+ * @param e les elements a ajouter
+ * @return la collection pass� en parametre
+ */
+ static public <A, E extends Collection<A>> E addAll(E col, A... e) {
+ Collections.addAll(col, e);
+ return col;
+ }
+
+ /**
+ * Ajoute a la liste tous les elements pass�s en parametre
+ *
+ * @param col la liste
+ * @param pos le premier index o� ins�rer les donn�es
+ * @param e les elements a ajouter
+ * @return la liste pass� en parametre
+ */
+ static public <A, E extends List<A>> E addAll(E col, int pos, A... e) {
+ col.addAll(pos, Arrays.asList(e));
+ return col;
+ }
+
+ /**
+ * Permet de convertir une liste non typ�e, en une liste typ�e.
+ * <p/>
+ * La liste en entr�e en juste bien cast�e.
+ * <p/>
+ * On effectue une v�rification sur le typage des �lements de la liste.
+ * <p/>
+ * Note : <b>Aucune liste n'est cr�ee, ni recopi�e</b>
+ *
+ * @param list la liste � convertir
+ * @param type le type des �l�ments de la liste
+ * @return la liste typ�e
+ * @throws IllegalArgumentException si un �l�ment de la liste en entr�e n'est
+ * pas en ad�quation avec le type voulue.
+ */
+ @SuppressWarnings({"unchecked"})
+ static public <O> List<O> toGenericList(List list, Class<O> type) throws IllegalArgumentException {
+ if (list.isEmpty()) {
+ return list;
+ }
+ for (Object o : list) {
+ if (!(type.isAssignableFrom(o.getClass()))) {
+ throw new IllegalArgumentException("can not cast List with object of type " + o.getClass() + " to " + type + " type!");
+ }
+ }
+ return list;
+ }
+
+ /**
+ * Permet de convertir une collection non typ�e, en une collection typ�e.
+ * <p/>
+ * La collection en entr�e en juste bien cast�e.
+ * <p/>
+ * On effectue une v�rification sur le typage des �lements de la collection.
+ * <p/>
+ * Note : <b>Aucune collection n'est cr�ee, ni recopi�e</b>
+ *
+ * @param list la collection � convertir
+ * @param type le type des �l�ments de la collection
+ * @return la collection typ�e
+ * @throws IllegalArgumentException si un �l�ment de la collection en entr�e n'est
+ * pas en ad�quation avec le type voulue.
+ */
+ @SuppressWarnings({"unchecked"})
+ static public <O> Collection<O> toGenericCollection(Collection list, Class<O> type) throws IllegalArgumentException {
+ if (list.isEmpty()) {
+ return list;
+ }
+ for (Object o : list) {
+ if (!(type.isAssignableFrom(o.getClass()))) {
+ throw new IllegalArgumentException("can not cast Collection with object of type " + o.getClass() + " to " + type + " type!");
+ }
+ }
+ return list;
+ }
+
+ /**
+ * Permet de convertir un ensemble non typ�e, en un ensemble typ�e.
+ * <p/>
+ * L'ensemble en entr�e en juste bien cast�e.
+ * <p/>
+ * On effectue une v�rification sur le typage des �lements de la collection.
+ * <p/>
+ * Note : <b>Aucun ensemble n'est cr�ee, ni recopi�e</b>
+ *
+ * @param list l'ensemble � convertir
+ * @param type le type des �l�ments de l'ensemble
+ * @return l'ensemble typ�e
+ * @throws IllegalArgumentException si un �l�ment de l'ensemble en entr�e n'est
+ * pas en ad�quation avec le type voulue.
+ */
+ @SuppressWarnings({"unchecked"})
+ static public <O> Set<O> toGenericSet(Set list, Class<O> type) throws IllegalArgumentException {
+ if (list.isEmpty()) {
+ return list;
+ }
+ for (Object o : list) {
+ if (!(type.isAssignableFrom(o.getClass()))) {
+ throw new IllegalArgumentException("can not cast Set with object of type " + o.getClass() + " to " + type + " type!");
+ }
+ }
+ return list;
+ }
+}
+
+
Property changes on: trunk/lutinutil/src/main/java/org/codelutin/util/CollectionUtil.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: trunk/lutinutil/src/main/java/org/codelutin/util/FileUtil.java (from rev 953, trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/FileUtil.java)
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/util/FileUtil.java (rev 0)
+++ trunk/lutinutil/src/main/java/org/codelutin/util/FileUtil.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -0,0 +1,781 @@
+/* *##%
+ * Copyright (C) 2002, 2003, 2004 Code Lutin, C�dric Pineau,
+ * Benjamin Poussin
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *##%*/
+
+/* *
+ * FileUtil.java
+ *
+ * Created: 22 nov. 2004
+ *
+ * @author Benjamin Poussin <poussin(a)codelutin.com>
+ * @version $Revision$
+ *
+ * Mise a jour: $Date$
+ * par : $Author$
+ */
+
+package org.codelutin.util;
+
+import org.apache.commons.logging.LogFactory;
+
+import javax.swing.JFileChooser;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.FileFilter;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.nio.channels.FileChannel;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.LinkedList;
+import java.util.List;
+
+public class FileUtil { // FileUtil
+
+ /** to use log facility, just put in your code: log.info(\"...\"); */
+ static private org.apache.commons.logging.Log log = LogFactory.getLog(FileUtil.class);
+
+ /** Encoding par defaut utilis� si non sp�cifi� */
+ static public String ENCODING = "ISO-8859-1";
+ static protected File currentDirectory = new File(".");
+
+ static public void setCurrentDirectory(File dir) {
+ currentDirectory = dir;
+ }
+
+ static public class PatternChooserFilter extends javax.swing.filechooser.FileFilter {
+ protected String pattern = null;
+ protected String description = null;
+
+ public PatternChooserFilter(String pattern, String description) {
+ this.pattern = pattern;
+ this.description = description;
+ }
+
+ @Override
+ public boolean accept(File f) {
+ return f.isDirectory() || f.getAbsolutePath().matches(pattern);
+ }
+
+ @Override
+ public String getDescription() {
+ return description;
+ }
+
+ }
+
+
+ /**
+ * Retourne le nom du fichier entre dans la boite de dialogue.
+ * Si le bouton annuler est utilis�, ou qu'il y a une erreur retourne null.
+ *
+ * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre donn�es
+ * par deux, le pattern du filtre + la description du filtre
+ * @return
+ * @see #getFile(javax.swing.filechooser.FileFilter[])
+ */
+ static public File getFile(String... patternOrDescriptionFilters) {
+ if (patternOrDescriptionFilters.length % 2 != 0) {
+ throw new IllegalArgumentException("Arguments must be (pattern, description) couple");
+ }
+ javax.swing.filechooser.FileFilter[] filters = new javax.swing.filechooser.FileFilter[patternOrDescriptionFilters.length / 2];
+ for (int i = 0; i < filters.length; i++) {
+ String pattern = patternOrDescriptionFilters[i * 2];
+ String description = patternOrDescriptionFilters[i * 2 + 1];
+ filters[i] = new PatternChooserFilter(pattern, description);
+ }
+ File result;
+ result = getFile(filters);
+ return result;
+ }
+
+ /**
+ * Retourne le nom du fichier entre dans la boite de dialogue.
+ * Si le bouton annuler est utilis�, ou qu'il y a une erreur retourne null.
+ *
+ * @param filters les filtres a ajouter
+ * @return
+ */
+ static public File getFile(javax.swing.filechooser.FileFilter... filters) {
+ try {
+ JFileChooser chooser = new JFileChooser(currentDirectory);
+
+ chooser.setDialogType(JFileChooser.CUSTOM_DIALOG);
+ if (filters.length > 0) {
+ if (filters.length == 1) {
+ chooser.setFileFilter(filters[0]);
+ } else {
+ for (javax.swing.filechooser.FileFilter filter : filters) {
+ chooser.addChoosableFileFilter(filter);
+ }
+ }
+ }
+ chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
+ int returnVal = chooser.showDialog(null, "Ok");
+ if (returnVal == JFileChooser.APPROVE_OPTION) {
+ File theFile = chooser.getSelectedFile();
+ if (theFile != null) {
+ currentDirectory = theFile;
+ return theFile.getAbsoluteFile();
+ }
+ }
+ }
+ catch (Exception eee) {
+ log.warn("Erreur:", eee);
+ }
+ return null;
+ }
+
+ /**
+ * @param title le nom de la boite de dialogue
+ * @param approvalText
+ * @return le nom du repertoire entre dans la boite de dialogue.
+ * Si le bouton annuler est utilis�, ou qu'il y a une erreur retourne
+ * null.
+ */
+ static public String getDirectory(String title, String approvalText) {
+ try {
+ JFileChooser chooser = new JFileChooser(currentDirectory);
+ chooser.setDialogType(JFileChooser.CUSTOM_DIALOG);
+ chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
+ chooser.setDialogTitle(title);
+ int returnVal = chooser.showDialog(null, approvalText);
+ if (returnVal == JFileChooser.APPROVE_OPTION) {
+ File theFile = chooser.getSelectedFile();
+ if (theFile != null) {
+ currentDirectory = theFile;
+ if (theFile.isDirectory()) {
+ return theFile.getAbsolutePath();
+ }
+ }
+ } else {
+ return null;
+ }
+ } catch (Exception eee) {
+ log.warn("Erreur:", eee);
+ }
+ return null;
+ }
+
+ /**
+ * @return le nom du repertoire entre dans la boite de dialogue.
+ * Si le bouton annuler est utilis�, ou qu'il y a une erreur retourne
+ * null.
+ */
+ static public String getDirectory() {
+ return getDirectory("Ok", "Ok");
+ }
+
+ /**
+ * Permet de convertir un fichier en un tableau de byte
+ *
+ * @param file
+ * @return
+ * @throws IOException
+ */
+ static public byte[] fileToByte(File file) throws IOException {
+ InputStream in = new BufferedInputStream(new FileInputStream(file));
+ ByteArrayOutputStream result = new ByteArrayOutputStream();
+ BufferedOutputStream tmp = new BufferedOutputStream(result);
+ for (int b = in.read(); b != -1; b = in.read()) {
+ tmp.write(b);
+ }
+ in.close();
+ tmp.close();
+
+ return result.toByteArray();
+ }
+
+ /**
+ * Permet de convertir des bytes en fichier, le fichier sera automatiquement
+ * supprim� a la fin de la JVM.
+ *
+ * @param bytes
+ * @return le fichier temporaire contenant les bytes
+ * @throws IOException
+ */
+ static public File byteToFile(byte[] bytes) throws IOException {
+ File file = File.createTempFile("FileUtil-byteToFile", ".tmp");
+ byteToFile(bytes, file);
+ return file;
+ }
+
+ /**
+ * Permet de convertir des bytes en fichier
+ *
+ * @param bytes
+ * @param file le fichier dans lequel il faut ecrire les bytes
+ * @return le fichier pass� en parametre
+ * @throws IOException
+ */
+ static public File byteToFile(byte[] bytes, File file) throws IOException {
+ OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
+ out.write(bytes);
+ out.close();
+ return file;
+ }
+
+ /**
+ * Retourne un Reader utilisant l'encoding par defaut {@link #ENCODING}
+ *
+ * @param file
+ * @return
+ * @throws IOException
+ */
+ static public BufferedReader getReader(File file) throws IOException {
+ return getReader(file, ENCODING);
+ }
+
+ /**
+ * Retourne un reader utilisant l'encoding choisi et plac� dans un
+ * BufferedReader
+ *
+ * @param file
+ * @param encoding (ISO-8859-1, UTF-8, ...)
+ * @return
+ * @throws IOException
+ */
+ static public BufferedReader getReader(File file, String encoding) throws IOException {
+ FileInputStream inf = new FileInputStream(file);
+ InputStreamReader in = new InputStreamReader(inf, encoding);
+// FileReader in = new FileReader(file);
+ BufferedReader result = new BufferedReader(in);
+ return result;
+ }
+
+ /**
+ * Retourne un Writer utilisant l'encoding par defaut {@link #ENCODING}
+ *
+ * @param file
+ * @return
+ * @throws IOException
+ */
+ static public BufferedWriter getWriter(File file) throws IOException {
+ return getWriter(file, ENCODING);
+ }
+
+ /**
+ * Retourne un writer utilisant l'encoding choisi et plac� dans un
+ * BufferedWriter
+ *
+ * @param file
+ * @param encoding (ISO-8859-1, UTF-8, ...)
+ * @return
+ * @throws IOException
+ */
+ static public BufferedWriter getWriter(File file, String encoding) throws IOException {
+ FileOutputStream outf = new FileOutputStream(file);
+ OutputStreamWriter out = new OutputStreamWriter(outf, encoding);
+// FileWriter out = new FileWriter(file);
+ BufferedWriter result = new BufferedWriter(out);
+ return result;
+ }
+
+ public static void main(String[] args) {
+
+ }
+
+ /**
+ * Permet de creer un nouveu repertoire temporaire, l'effacement du
+ * r�pertoire est a la charge de l'appelant
+ *
+ * @param prefix le prefix du fichier
+ * @param suffix le suffix du fichier
+ * @param tmpdir le r�pertoire temporaire ou il faut creer le repertoire
+ * si null on utilise java.io.tmpdir
+ * @return le fichier pointant sur le nouveau repertoire
+ * @throws java.io.IOException
+ */
+ static public File createTempDirectory(String prefix, String suffix, File tmpdir) throws IOException {
+ if (tmpdir == null) {
+ tmpdir = new File(System.getProperty("java.io.tmpdir"));
+ }
+ File result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix);
+ while (result.exists()) {
+ result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix);
+ }
+ if (!result.mkdirs()) {
+ throw new IOException("Can't create temporary directory: " + result);
+ }
+ return result;
+ }
+
+ /**
+ * Permet de creer un nouveu repertoire temporaire, l'effacement du
+ * r�pertoire est a la charge de l'appelant
+ *
+ * @param prefix
+ * @param suffix
+ * @return
+ * @throws java.io.IOException
+ */
+ static public File createTempDirectory(String prefix, String suffix) throws IOException {
+ return createTempDirectory(prefix, suffix, null);
+ }
+
+ /**
+ * Regarde si le fichier f1 est plus recent que le fichier f2
+ *
+ * @param f1
+ * @param f2
+ * @return vrai si f1 est plus recent que f2
+ */
+ static public boolean isNewer(File f1, File f2) {
+ boolean result = f1.lastModified() > f2.lastModified();
+ return result;
+ }
+
+ /**
+ * Permet de lire un fichier et de retourner sont contenu sous forme d'une
+ * chaine de carateres
+ *
+ * @param file le fichier a lire
+ * @return
+ * @throws IOException
+ */
+ static public String readAsString(File file) throws IOException {
+ StringBuffer result = new StringBuffer();
+ char[] cbuf = new char[2000];
+ BufferedReader in = getReader(file);
+ int nb = in.read(cbuf);
+ while (nb != -1) {
+ result.append(cbuf, 0, nb);
+ nb = in.read(cbuf);
+ }
+ in.close();
+ return result.toString();
+ }
+
+ /**
+ * Permet de sauver une chaine directement dans un fichier
+ *
+ * @param file Le fichier dans lequel il faut ecrire la chaine
+ * @param content Le texte a ecrire dans le fichier
+ * @throws IOException if any pb while writing
+ */
+ static public void writeString(File file, String content) throws IOException {
+ file.getParentFile().mkdirs();
+ BufferedWriter out = getWriter(file);
+ out.write(content);
+ out.close();
+ }
+
+ /**
+ * Permet de sauver une chaine directement dans un fichier
+ *
+ * @param file Le fichier dans lequel il faut ecrire la chaine
+ * @param content Le texte a ecrire dans le fichier
+ * @param encoding encoding to use
+ * @throws IOException if any pb while writing
+ */
+ static public void writeString(File file, String content, String encoding) throws IOException {
+ file.getParentFile().mkdirs();
+ BufferedWriter out = getWriter(file, encoding);
+ out.write(content);
+ out.close();
+ }
+
+ /**
+ * Permet de donner une representation fichier pour une chaine de caractere.
+ * Le fichier sera automatiquement effac� � la fin de la JVM.
+ *
+ * @param content le contenu du fichier temporaire
+ * @return le fichier qui contient content
+ * @throws IOException
+ */
+ static public File getTempFile(String content) throws IOException {
+ return getTempFile(content, "");
+ }
+
+ /**
+ * Permet de donner une representation fichier pour une chaine de caractere.
+ * Le fichier sera automatiquement effac� � la fin de la JVM.
+ *
+ * @param content le contenu du fichier temporaire
+ * @param fileSuffix l'extension du fichier cr��
+ * @return le fichier qui contient content
+ * @throws IOException
+ */
+ static public File getTempFile(String content, String fileSuffix) throws IOException {
+ File result = File.createTempFile("tmp-" + FileUtil.class.getName(), fileSuffix);
+ result.deleteOnExit();
+ writeString(result, content);
+ return result;
+ }
+
+ /**
+ * Equivalent de la methode basename unix.
+ * basename("/tmp/toto.xml", ".xml") -> "toto"
+ *
+ * @param file le fichier dont on souhaite le nom sans le chemin
+ * @param suffixes si present represente le suffixe a eliminer du fichier
+ * s'il est trouv�
+ * @return le nom du fichier sans le suffixe si trouv�.
+ */
+ static public String basename(File file, String... suffixes) {
+ String result = file.getName();
+ for (String suffixe : suffixes) {
+ if (result.endsWith(suffixe)) {
+ result = result.substring(0, result.length() - suffixe.length());
+ break;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Permet de r�cup�rer l'extension d'un fichier
+ *
+ * @param file le fichier dont on souhaite l'extension
+ * @param extchars la liste des caracteres pouvant former l'extension
+ * dans l'ordre de preference. Si vide on utilise ".".
+ * @return l'extension ou la chaine vide si le fichier n'a pas d'extension
+ * l'extension ne contient pas le chaine de delimitation
+ */
+ static public String extension(File file, String... extchars) {
+ String result = "";
+ String name = file.getName();
+
+ if (extchars.length == 0) {
+ extchars = new String[]{"."};
+ }
+ for (String extchar : extchars) {
+ int pos = name.lastIndexOf(extchar);
+ if (pos != -1) {
+ result = name.substring(pos + extchar.length());
+ break;
+ }
+ }
+ return result;
+ }
+
+ static public interface FileAction {
+ public boolean doAction(File f);
+ }
+
+ /**
+ * Retourne tous les sous r�pertoires du r�pertoire pass� en argument.
+ *
+ * @param directory un r�pertoire
+ * @return une liste d'objet {@link java.io.File} de r�pertoires et ceci
+ * recursivement � partir de directory, si directory
+ * n'est pas un r�pertoire la liste est vide.
+ */
+ public static List<File> getSubDirectories(File directory) {
+ class DirectoryFilter implements FileFilter {
+ public boolean accept(File f) {
+ return f.isDirectory();
+ }
+ }
+ return getFilteredElements(directory, new DirectoryFilter(), true);
+ }
+
+ /**
+ * Retourne tous les fichiers du r�pertoire pass� en argument.
+ *
+ * @param directory un r�pertoire
+ * @return une liste d'objet {@link java.io.File} des fichiers et ceci
+ * recursivement � partir de directory, si directory n'est pas un
+ * r�pertoire la liste est vide
+ */
+ public static List<File> getFiles(File directory) {
+ class NormalFileFilter implements FileFilter {
+ public boolean accept(File f) {
+ return f.isFile();
+ }
+ }
+ return getFilteredElements(directory, new NormalFileFilter(), true);
+ }
+
+ /**
+ * Retourne les fichiers d'un r�pertoire qui s'attisfont un certain pattern.
+ * La recherche est faite r�cursivement dans les sous r�pertoires
+ *
+ * @param directory le r�pertoire � partir duquel il faut faire la recherche
+ * @param pattern le pattern que doit respecter le fichier pour �tre dans la
+ * liste r�sultante
+ * @param recursively
+ * @return une liste d'objet {@link java.io.File} qui ont s'attisfait le
+ * pattern.
+ */
+ public static List<File> find(File directory, final String pattern, boolean recursively) {
+ final String root = directory.getAbsolutePath();
+ final int rootLength = root.length();
+
+ return getFilteredElements(directory, new FileFilter() {
+ public boolean accept(File f) {
+ String longFilename = f.getAbsolutePath();
+ // + 1 to remove the first / or \
+ String filename = longFilename.substring(rootLength + 1);
+ return filename.matches(pattern);
+ }
+ }, recursively);
+ }
+
+ /**
+ * Retourne la liste de toutes les fichiers ou r�pertoire qui s'attisfont
+ * le filtre
+ *
+ * @param directory repertoire � partir duquel il faut faire la recherche
+ * @param ff le filtre � appliquer pour savoir si le fichier parcouru doit
+ * �tre conserv� dans les r�sultats, ou null pour tous les fichiers
+ * @param recursively
+ * @return une liste d'objet {@link java.io.File}, qui s'attisfont le filtre
+ */
+ public static List<File> getFilteredElements(File directory, FileFilter ff, boolean recursively) {
+ ArrayList<File> result = new ArrayList<File>();
+ LinkedList<File> todo = new LinkedList<File>();
+ if (directory.isDirectory()) {
+ todo.addAll(Arrays.asList(directory.listFiles()));
+ }
+ while (todo.size() > 0) {
+ File file = todo.removeFirst();
+ if (recursively && file.isDirectory()) {
+ File[] childs = file.listFiles();
+ if (childs != null) { // null if we don't have access to directory
+ todo.addAll(Arrays.asList(childs));
+ }
+ }
+ if (ff == null || ff.accept(file)) {
+ result.add(file);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Supprime recursivement tout le contenu d'un r�pertoire.
+ *
+ * @param directory
+ * @return vrai si tout se passe bien, false si la suppression d'un �lement
+ * se passe mal
+ */
+ public static boolean deleteRecursively(String directory) {
+ return deleteRecursively(new File(directory));
+ }
+
+ /**
+ * Supprime recursivement tout le contenu d'un r�pertoire.
+ *
+ * @param directory
+ * @return vrai si tout se passe bien, false si la suppression d'un �lement
+ * se passe mal
+ */
+ public static boolean deleteRecursively(File directory) {
+ return walkBefore(directory, new FileAction() {
+ public boolean doAction(File f) {
+ return f.delete();
+ }
+ });
+ }
+
+ /**
+ * Permet de faire une action avant le parcours des fichiers, c-a-d que
+ * l'on fera l'action sur les fichiers contenu dans un r�pertoire
+ * apr�s l'action sur le r�pertoire lui m�me.
+ *
+ * @param f le fichier ou r�pertoire � partir duquel il faut commencer
+ * @param fileAction l'action � effectuer sur chaque fichier
+ * @return le r�sultat des fileAction execut� sur les fichiers, chaque
+ * r�sultat de FileAction sont assembl� par un ET logique pour donner
+ * le r�sultat final
+ */
+ public static boolean walkAfter(File f, FileAction fileAction) {
+ boolean result = fileAction.doAction(f);
+ if (f.isDirectory()) {
+ File list[] = f.listFiles();
+ for (int i = 0; i < list.length; i++) {
+ result = result && walkAfter(list[i], fileAction);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Permet de faire une action ap�s le parcours des fichiers, c-a-d que
+ * l'on fera l'action sur les fichiers contenu dans un r�pertoire
+ * avant l'action sur le r�pertoire lui m�me.
+ *
+ * @param f le fichier ou r�pertoire � partir duquel il faut commencer
+ * @param fileAction l'action � effectuer sur chaque fichier
+ * @return le r�sultat des fileAction execut� sur les fichiers, chaque
+ * r�sultat de FileAction sont assembl� par un ET logique pour donner
+ * le r�sultat final
+ */
+ public static boolean walkBefore(File f, FileAction fileAction) {
+ boolean result = true;
+ if (f.isDirectory()) {
+ File list[] = f.listFiles();
+ for (int i = 0; i < list.length; i++) {
+ result = result && walkBefore(list[i], fileAction);
+ }
+ }
+ return result && fileAction.doAction(f);
+ }
+
+ /**
+ * Permet de copier le fichier source vers le fichier cible.
+ *
+ * @param source le fichier source
+ * @param target le fichier cible
+ * @throws IOException Erreur de copie
+ */
+ public static void copy(File source, File target) throws IOException {
+ target.getParentFile().mkdirs();
+ FileChannel sourceChannel = new FileInputStream(source).getChannel();
+ FileChannel targetChannel = new FileOutputStream(target).getChannel();
+ sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
+ // or
+ // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
+ sourceChannel.close();
+ targetChannel.close();
+ }
+
+ /**
+ * Permet de copier le fichier source vers le fichier cible.
+ *
+ * @param source le fichier source
+ * @param target le fichier cible
+ * @throws IOException Erreur de copie
+ */
+ public static void copy(String source, String target) throws IOException {
+ copy(new File(source), new File(target));
+ }
+
+ /**
+ * Copie recursivement le repertoire source dans le repertoire destination
+ * <p/>
+ * copyRecursively("/truc/titi", "/var/tmp") donnera le repertoire
+ * "/var/tmp/titi"
+ *
+ * @param srcDir
+ * @param destDir
+ * @param includePatterns les patterns que doivent resperter les
+ * fichiers/repertoires pour etre copi�. Si vide alors tout est copi�
+ * @throws IOException
+ */
+ static public void copyRecursively(File srcDir, File destDir, String... includePatterns) throws IOException {
+ copyAndRenameRecursively(srcDir, destDir, null, null, includePatterns);
+ }
+
+ /**
+ * Copie recursivement le repertoire source dans le repertoire destination
+ * <p/>
+ * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire
+ * "/var/tmp/bidulle", 'bidulle' remplacant 'titi'
+ *
+ * @param srcDir
+ * @param destDir
+ * @param renameFrom pattern to permit rename file before uncompress it
+ * @param renameTo new name for file if renameFrom is applicable to it
+ * you can use $1, $2, ... if you have '(' ')' in renameFrom
+ * @param includePatterns les patterns que doivent resperter les
+ * fichiers/repertoires pour etre copi�. Si vide alors tout est copi�
+ * @throws IOException
+ */
+ static public void copyAndRenameRecursively(File srcDir, File destDir,
+ String renameFrom, String renameTo, String... includePatterns) throws IOException {
+ copyAndRenameRecursively(srcDir, destDir, true, renameFrom, renameTo, false, includePatterns);
+ }
+
+ /**
+ * Copie recursivement le repertoire source dans le repertoire destination
+ * <p/>
+ * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire
+ * "/var/tmp/bidulle", 'bidulle' remplacant 'titi'
+ *
+ * @param srcDir
+ * @param destDir
+ * @param includeSrcDir si vrai alors le repertoire source est copie dans le
+ * repertoire destination et non pas seulement les fichiers qu'il contient
+ * @param renameFrom pattern to permit rename file before uncompress it
+ * @param renameTo new name for file if renameFrom is applicable to it
+ * you can use $1, $2, ... if you have '(' ')' in renameFrom
+ * @param exclude inverse include pattern interpretation
+ * @param includePatterns les patterns que doivent resperter les
+ * fichiers/repertoires pour etre copi�. Si vide alors tout est copi�
+ * @throws IOException
+ */
+ static public void copyAndRenameRecursively(File srcDir, File destDir,
+ boolean includeSrcDir, String renameFrom, String renameTo, boolean exclude,
+ String... includePatterns) throws IOException {
+ String rootSrc;
+ if (includeSrcDir) {
+ rootSrc = srcDir.getParent();
+ } else {
+ rootSrc = srcDir.getPath();
+ }
+ List<File> files = getFilteredElements(srcDir, null, true);
+ log.debug("copyRecursively: " + files);
+ for (File file : files) {
+ boolean doCopy = copyRecursivelyAccept(file, includePatterns);
+ if (xor(exclude, doCopy)) {
+ String path = file.getPath().substring(rootSrc.length());
+ if (renameFrom != null && renameTo != null) {
+ String tmp = path.replaceAll(renameFrom, renameTo);
+ if (log.isDebugEnabled()) {
+ log.debug("rename " + path + " -> " + tmp);
+ }
+ path = tmp;
+ }
+
+ File destFile = new File(destDir, path);
+ if (file.isDirectory()) {
+ log.debug("create directory: " + destFile);
+ destFile.mkdirs();
+ } else {
+ log.debug("copy " + path + " to " + destFile);
+ copy(file, destFile);
+ }
+ }
+ }
+ }
+
+ static private boolean xor(boolean b, boolean c) {
+ if (b) return !c;
+ else return c;
+ }
+
+ /**
+ * @param file
+ * @param includePatterns
+ * @return
+ */
+ private static boolean copyRecursivelyAccept(File file, String[] includePatterns) {
+ boolean result = includePatterns.length == 0;
+ String filename = file.getAbsolutePath();
+ for (String pattern : includePatterns) {
+ result = filename.matches(pattern);
+ if (result) {
+ break;
+ }
+ }
+ return result;
+ }
+
+} // FileUtil
+
Property changes on: trunk/lutinutil/src/main/java/org/codelutin/util/FileUtil.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: trunk/lutinutil/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java (from rev 953, trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java)
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java (rev 0)
+++ trunk/lutinutil/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -0,0 +1,50 @@
+/*
+* ##% Copyright (C) 2008 Code Lutin, Gabriel Landais
+*
+* This program is free software; you can redistribute it and/or
+* modify it under the terms of the GNU General Public License
+* as published by the Free Software Foundation; either version 2
+* of the License, or (at your option) any later version.
+*
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+* ##% */
+package org.codelutin.util;
+
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+public class PropertiesDateRemoveFilterStream extends FilterOutputStream {
+
+ private boolean firstLineOver;
+ char endChar;
+
+ public PropertiesDateRemoveFilterStream(OutputStream out) {
+ super(out);
+ firstLineOver = false;
+ String lineSeparator = java.security.AccessController
+ .doPrivileged(new sun.security.action.GetPropertyAction(
+ "line.separator"));
+ endChar = lineSeparator.charAt(lineSeparator.length() - 1);
+ }
+
+ @Override
+ public void write(int b) throws IOException {
+ if (!firstLineOver) {
+ char c = (char) b;
+ if (c == endChar) {
+ firstLineOver = true;
+ }
+ } else {
+ out.write(b);
+ }
+ }
+
+}
\ No newline at end of file
Copied: trunk/lutinutil/src/main/java/org/codelutin/util/SortedProperties.java (from rev 953, trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/SortedProperties.java)
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/util/SortedProperties.java (rev 0)
+++ trunk/lutinutil/src/main/java/org/codelutin/util/SortedProperties.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -0,0 +1,62 @@
+/* *##%
+ * Copyright (C) 2007
+ * I18nPlugin, Code Lutin
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *##%*/
+
+package org.codelutin.util;
+
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Properties;
+import java.util.Vector;
+
+/**
+ * Permet d'avoir les fichiers de propri�t�s tri�s.
+ *
+ * @author julien
+ */
+public class SortedProperties extends Properties {
+
+ private static final long serialVersionUID = -1147150444452577558L;
+
+
+ public SortedProperties() {
+ super();
+ }
+
+ public SortedProperties(Properties defaults) {
+ super(defaults);
+ }
+
+ @Override
+ public synchronized Enumeration<Object> keys() {
+ List<Object> objects = Collections.list(super.keys());
+ Vector<Object> result;
+ try {
+ // Attention, si les clef ne sont pas des string, ca ne marchera pas
+ List<String> list = CollectionUtil.toGenericList(objects, String.class);
+ Collections.sort(list);
+ result = new Vector<Object>(list);
+ } catch (IllegalArgumentException e) {
+ // keys are not string !!!
+ // can not sort keys
+ result = new Vector<Object>(objects);
+ }
+ return result.elements();
+ }
+}
Property changes on: trunk/lutinutil/src/main/java/org/codelutin/util/SortedProperties.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: trunk/lutinutil/src/main/java/org/codelutin/util/StringUtil.java (from rev 953, trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtil.java)
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/util/StringUtil.java (rev 0)
+++ trunk/lutinutil/src/main/java/org/codelutin/util/StringUtil.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -0,0 +1,552 @@
+/* *##%%
+ * Copyright (C) 2002, 2003 Code Lutin
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
+ *##%%**/
+/* *
+ * StringUtil.java
+ *
+ * Created: Sun Apr 14 2002
+ *
+ * @author POUSSIN Benjamin <bpoussin(a)free.fr>
+ * Copyright Code Lutin
+ * @version $Revision$
+ *
+ * Mise a jour: $Date$
+ * par : $Author$
+ */
+package org.codelutin.util;
+
+import java.awt.Color;
+import java.lang.reflect.Field;
+import java.text.DateFormat;
+import java.text.MessageFormat;
+import java.text.ParseException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * Classe contenant un ensemle de methode static utiles pour la manipulation des
+ * chaine de caractere mais qui ne sont pas defini dans la classe String de
+ * Java.
+ *
+ * @author poussin
+ * @created 21 octobre 2003
+ */
+public class StringUtil { // StringUtil
+
+ /** Constructor for the StringUtil object */
+ protected StringUtil() {
+ }
+
+ /**
+ * Cette methode retire les accents. Quand le caractere est connu, elle le
+ * remplace par une version sans accent sinon, elle le supprime.
+ * Les caracteres non-alphanumeriques sont supprimes.
+ *
+ * @param s la chaine a unaccentuer
+ * @return la chaine sans accent
+ */
+ static public String unaccent(String s) {
+ String result = "";
+ for (char c : s.toCharArray()) {
+ if ("����".indexOf(c) != -1) {
+ result += "e";
+ } else if ("���".indexOf(c) != -1) {
+ result += "a";
+ } else if ("�".indexOf(c) != -1) {
+ result += "c";
+ } else if ("��".indexOf(c) != -1) {
+ result += "i";
+ } else if ("��".indexOf(c) != -1) {
+ result += "o";
+ } else if ("���".indexOf(c) != -1) {
+ result += "u";
+ } else if ("����".indexOf(c) != -1) {
+ result += "E";
+ } else if ("���".indexOf(c) != -1) {
+ result += "A";
+ } else if ("�".indexOf(c) != -1) {
+ result += "C";
+ } else if ("��".indexOf(c) != -1) {
+ result += "I";
+ } else if ("��".indexOf(c) != -1) {
+ result += "O";
+ } else if ("���".indexOf(c) != -1) {
+ result += "U";
+ } else if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')
+ || ('0' <= c && c <= '9') || ('.' == c) || ('-' == c)
+ || ('_' == c)) {
+ result += c;
+ } else {
+ // on ne l'ajoute pas a result donc on supprime le caractere
+ // result += encodeUTF(c);
+ }
+ }
+ return result;
+ }
+
+ static public String substring(String s, int begin) {
+ String result;
+ result = substring(s, begin, s.length());
+ return result;
+ }
+
+ static public String substring(String s, int begin, int end) {
+ if (begin < 0) {
+ begin = s.length() + begin;
+ }
+ if (end < 0) {
+ end = s.length() + end;
+ }
+ if (end < begin) {
+ end = begin;
+ }
+
+ String result;
+ result = s.substring(begin, end);
+ return result;
+ }
+
+ /**
+ * Met en majuscule le premier caractere de la chaine passee en parametre
+ *
+ * @param word La chaine a capitaliser
+ * @return La chaine capitalisee
+ * @deprecated you must use
+ * org.apache.commons.lang.StringUtils.capitalise(String)
+ */
+ public static String capitalize(String word) {
+ return word.substring(0, 1).toUpperCase() + word.substring(1);
+ }
+
+ /**
+ * Met en minuscule le premier caractere de la chaine passe en parametre
+ *
+ * @param word La chaine a decapitaliser
+ * @return La chaine decapitalisee
+ * @deprecated you must use
+ * org.apache.commons.lang.StringUtils.uncapitalise(String)
+ */
+ public static String uncapitalize(String word) {
+ return word.substring(0, 1).toLowerCase() + word.substring(1);
+ }
+
+ /**
+ * Concat�ne un tableau de chaine de caracteres en une seul chaine.
+ *
+ * @param s le tableau de chaines
+ * @param sep le separateur a utiliser pour separer chaque chaine.
+ * @return la chaine resultante de la concatenation. Si le tableau est null
+ * ou vide, la chaine resultante est une chaine vide.
+ * @deprecated you must use org.apache.commons.lang.StringUtils.join
+ */
+ public static String unsplit(String[] s, String sep) {
+ if (s == null || s.length <= 0) {
+ return "";
+ }
+
+ StringBuffer result = new StringBuffer(s[0]);
+ for (int i = 1; i < s.length; i++) {
+ result.append(sep).append(s[i]);
+ }
+ return result.toString();
+ }
+
+ private static final Character[] openingChars = {'(', '{', '['};
+
+ private static final Character[] closingChars = {')', '}', ']'};
+
+ /**
+ * Split string use 'separator' as separator. If String contains "'()[]{}
+ * this method count the number of open char end close char to split
+ * correctly argument
+ *
+ * @param args string to split
+ * @param separator separator use to split string
+ * @return array of string
+ */
+ static public String[] split(String args, String separator) {
+ return split(openingChars, closingChars, args, separator);
+ }
+
+
+ /**
+ * Use to split string array representation in array according with swixat
+ * seperator list
+ *
+ * @param stringList string that represent array
+ * @return array with length > 0 if listAsString != null or null
+ */
+ static public String[] split(String stringList) {
+ String[] result;
+ result = split(stringList, ",");
+ return result;
+ }
+
+ /**
+ * Split string use 'separator' as separator. If String contains "'
+ * and <code>openingChar</code> <code>closingChars</code>
+ * <p/>
+ * this method count the number of open char end close char to split correctly
+ * argument
+ *
+ * @param openingChars list of opening caracteres
+ * @param closingChars list of closing caracteres
+ * @param args string to split
+ * @param separator separator use to split string
+ * @return array of string
+ */
+ static public String[] split(Character[] openingChars,
+ Character[] closingChars,
+ String args, String separator) {
+ if (args == null) {
+ return new String[0];
+ }
+
+ List<String> result = new ArrayList<String>();
+
+ int start = 0;
+ int end;
+ StringBuffer op = new StringBuffer(); // stack of {([< currently open
+ char last = '\0'; // contains " or ' if string is openned
+
+ List<Character> opening = Arrays.asList(openingChars);
+
+ List<Character> closing = Arrays.asList(closingChars);
+
+ for (int i = 0; i < args.length(); i++) {
+ char c = args.charAt(i);
+ if (c == '\\') {
+ // pass next char
+ i++;
+ } else if (last != '"' && last != '\'') {
+ if (opening.contains(c)) {
+ op.append(c);
+ } else if (closing.contains(c)) {
+ op.deleteCharAt(op.length() - 1);
+ } else if (c == '"' || c == '\'') {
+ // open string " or '
+ last = c;
+ } else if (op.length() == 0 &&
+ args.regionMatches(i, separator, 0, separator.length())) {
+ // end of one arguement
+ end = i;
+ // pass separator
+ i += separator.length() - 1;
+
+ String a = args.substring(start, end);
+ result.add(a);
+ // start of next argument
+ start = end + separator.length();
+ }
+ } else if (c == last) {
+ // close string " or '
+ last = '\0';
+ }
+ }
+
+ if (start < args.length()) {
+ String a = args.substring(start, args.length());
+ result.add(a);
+ }
+
+ return result.toArray(new String[result.size()]);
+ }
+
+ public static boolean toBoolean(String s) {
+ return "true".equalsIgnoreCase(s);
+ }
+
+ public static byte toByte(String s) {
+ return Byte.parseByte(s);
+ }
+
+ public static double toDouble(String s) {
+ return Double.parseDouble(s);
+ }
+
+ public static float toFloat(String s) {
+ return Float.parseFloat(s);
+ }
+
+ public static long toLong(String s) {
+ return Long.parseLong(s);
+ }
+
+ public static short toShort(String s) {
+ return Short.parseShort(s);
+ }
+
+ public static int toInt(String s) {
+ return Integer.parseInt(s);
+ }
+
+ public static char toChar(String s) {
+ // fixme a revoir
+ return s.charAt(0);
+ }
+
+ public static boolean[] toArrayBoolean(String... s) {
+ boolean[] result = new boolean[s.length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = toBoolean(s[i]);
+ }
+ return result;
+ }
+
+ public static byte[] toArrayByte(String... s) {
+ byte[] result = new byte[s.length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = toByte(s[i]);
+ }
+ return result;
+ }
+
+ public static double[] toArrayDouble(String... s) {
+ double[] result = new double[s.length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = toDouble(s[i]);
+ }
+ return result;
+ }
+
+ public static float[] toArrayFloat(String... s) {
+ float[] result = new float[s.length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = toFloat(s[i]);
+ }
+ return result;
+ }
+
+ public static long[] toArrayLong(String... s) {
+ long[] result = new long[s.length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = toLong(s[i]);
+ }
+ return result;
+ }
+
+ public static short[] toArrayShort(String... s) {
+ short[] result = new short[s.length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = toShort(s[i]);
+ }
+ return result;
+ }
+
+ public static int[] toArrayInt(String... s) {
+ int[] result = new int[s.length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = toInt(s[i]);
+ }
+ return result;
+ }
+
+ public static char[] toArrayChar(String... s) {
+ char[] result = new char[s.length];
+ for (int i = 0; i < result.length; i++) {
+ result[i] = toChar(s[i]);
+ }
+ // fixme a revoir
+ return result;
+ }
+
+ /**
+ * Essai de convertir une chaine de caractere en une couleur si possible si
+ * ce n'est pas possible retourne null.
+ *
+ * @param s la couleur sous la forme de string, par exemple "red",
+ * "yellow" ou bien en RGB "#FFAA99", et avec un canal alpha
+ * "#FFAA3366"
+ * @return la couleur demand� si possible sinon null
+ * @throws IllegalArgumentException
+ * @throws StringUtilException if any problem while conversion
+ */
+ public static Color toColor(String s) throws StringUtilException {
+ try {
+ if (s.startsWith("#")) {
+ // r�cuperation des valeurs hexa
+ String hr = s.substring(1, 3);
+ String hg = s.substring(3, 5);
+ String hb = s.substring(5, 7);
+
+ // conversion en entier
+ int r = Integer.parseInt(hr, 16);
+ int g = Integer.parseInt(hg, 16);
+ int b = Integer.parseInt(hb, 16);
+
+ if (s.length() == 9) {
+ // s'il y a un canal alpha on l'utilise
+ String ha = s.substring(7, 9);
+ int a = Integer.parseInt(ha, 16);
+ return new Color(r, g, b, a);
+ } else {
+ return new Color(r, g, b);
+ }
+ } else {
+ Field f;
+ f = Color.class.getField(s);
+ return (Color) f.get(Color.class);
+ }
+ } catch (NumberFormatException e) {
+ throw new StringUtilException(
+ "Error during conversion from string to color", e);
+ } catch (SecurityException e) {
+ throw new StringUtilException(
+ "Error during conversion from string to color", e);
+ } catch (NoSuchFieldException e) {
+ throw new StringUtilException(
+ "Error during conversion from string to color", e);
+ } catch (IllegalArgumentException e) {
+ throw new StringUtilException(
+ "Error during conversion from string to color", e);
+ } catch (IllegalAccessException e) {
+ throw new StringUtilException(
+ "Error during conversion from string to color", e);
+ }
+ }
+
+ public static Date toDate(String s) throws ParseException {
+ return DateFormat.getDateInstance().parse(s);
+ }
+
+ static final protected double[] timeFactors = {1000000, 1000, 60, 60, 24};
+
+ static final protected String[] timeUnites = {"ns", "ms", "s", "m", "h",
+ "d"};
+
+ static public String convertTime(long value) {
+ return convert(value, timeFactors, timeUnites);
+ }
+
+ static public String convertTime(long value, long value2) {
+ return convertTime(value2 - value);
+ }
+
+ static final protected double[] memoryFactors = {1024, 1024, 1024, 1024};
+
+ static final protected String[] memoryUnites = {"o", "Ko", "Mo", "Go",
+ "To"};
+
+ static public String convertMemory(long value) {
+ return convert(value, memoryFactors, memoryUnites);
+ }
+
+ static public String convert(long value, double[] factors, String[] unites) {
+ long sign = value == 0 ? 1 : value / Math.abs(value);
+ int i = 0;
+ double tmp = Math.abs(value);
+ while (i < factors.length && i < unites.length && tmp > factors[i]) {
+ tmp = tmp / factors[i++];
+ }
+
+ tmp *= sign;
+ String result;
+ result = MessageFormat.format("{0,number,0.###}{1}", tmp,
+ unites[i]);
+ return result;
+ }
+
+ /**
+ * V�rifie q'une chaine de caract�re est valid pour les bloc openner closer, ie.
+ * <p/>
+ * que les blocs d�finit par les deux caract�res s'entrechevauchent pas.
+ * <p/>
+ * Exemple avec '(' ')' :
+ * <p/>
+ * (a(b)) est valide, par contre ((aaa))) n'est pas valide
+ *
+ * @param txt txte a verifier
+ * @param opener le caract�re ouvrant
+ * @param closer le caract�re fermant
+ * @return <code>true</code> is la chaine est valide
+ */
+ public static boolean checkEnclosure(String txt, final char opener, char closer) {
+ if (txt.indexOf(opener) == -1 && txt.indexOf(closer) == -1) {
+ // ok pas de block d�tect�s
+ return true;
+ }
+ List<Integer> opens = new ArrayList<Integer>();
+ for (int i = 0; i < txt.length(); i++) {
+ char c = txt.charAt(i);
+ if (c == opener) {
+ // add a open block
+ opens.add(i);
+ continue;
+ }
+ if (c == closer) {
+ if (opens.isEmpty()) {
+ // problem no block left
+ return false;
+ }
+ // on supprime le dernier bloc
+ opens.remove(opens.size() - 1);
+ }
+ }
+ return opens.isEmpty();
+ }
+
+ /**
+ * Convertir un nom en une constante Java
+ * <p/>
+ * Les seuls caract�res autoris�s sont les alpha num�riques, ains
+ * que l'underscore. tous les autres caract�res seront ignor�s.
+ *
+ * @param name le nom � convertir
+ * @return la constante g�n�r�e
+ */
+ public static String convertToConstantName(String name) {
+ StringBuilder sb = new StringBuilder();
+ char lastChar = 0;
+ for (int i = 0, j = name.length(); i < j; i++) {
+ char c = name.charAt(i);
+ if (Character.isDigit(c)) {
+ sb.append(c);
+ lastChar = c;
+ continue;
+ }
+ if (!Character.isLetter(c)) {
+ if (lastChar != '_') {
+ sb.append('_');
+ }
+ lastChar = '_';
+ continue;
+ }
+ if (Character.isUpperCase(c)) {
+ if (!Character.isUpperCase(lastChar) && lastChar != '_') {
+ sb.append('_');
+ }
+ sb.append(c);
+ } else {
+ sb.append(Character.toUpperCase(c));
+ }
+ lastChar = c;
+ }
+ String result = sb.toString();
+ // clean tail
+ while (!result.isEmpty() && result.endsWith("_")) {
+ result = result.substring(0, result.length() - 1);
+ }
+ // clean head
+ while (!result.isEmpty() && result.startsWith("_")) {
+ result = result.substring(1);
+ }
+ return result;
+ }
+
+}
Property changes on: trunk/lutinutil/src/main/java/org/codelutin/util/StringUtil.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: trunk/lutinutil/src/main/java/org/codelutin/util/StringUtilException.java (from rev 953, trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtilException.java)
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/util/StringUtilException.java (rev 0)
+++ trunk/lutinutil/src/main/java/org/codelutin/util/StringUtilException.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -0,0 +1,24 @@
+/*
+ * Created on Dec 7, 2004
+ *
+ * TODO To change the template for this generated file go to
+ * Window - Preferences - Java - Code Style - Code Templates
+ */
+package org.codelutin.util;
+
+/**
+ * @author pineau
+ * <p/>
+ * TODO To change the template for this generated type comment go to
+ * Window - Preferences - Java - Code Style - Code Templates
+ */
+public class StringUtilException extends RuntimeException {
+
+ /** */
+ private static final long serialVersionUID = 6148795384335489591L;
+
+ public StringUtilException(String message, Exception e) {
+ super(message, e);
+ }
+
+}
Property changes on: trunk/lutinutil/src/main/java/org/codelutin/util/StringUtilException.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Deleted: trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/CollectionUtil.java
===================================================================
--- trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/CollectionUtil.java 2008-08-04 13:30:38 UTC (rev 965)
+++ trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/CollectionUtil.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -1,156 +0,0 @@
-/* *##%
- * Copyright (C) 2006
- * Code Lutin, C�dric Pineau, Benjamin Poussin
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *##%*/
-
-/* *
- * CollectionUtil.java
- *
- * Created: 23 f�vr. 2006 09:03:39
- *
- * @author poussin
- * @version $Revision$
- *
- * Last update: $Date$
- * by : $Author$
- */
-
-package org.codelutin.util;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-
-/**
- * @author poussin
- *
- */
-
-public class CollectionUtil {
-
- /**
- * Ajoute a la collection tous les elements pass�s en parametre
- * @param col la collection
- * @param e les elements a ajouter
- * @return la collection pass� en parametre
- */
- static public <A, E extends Collection<A>> E addAll(E col, A ... e) {
- Collections.addAll(col, e);
- return col;
- }
-
- /**
- * Ajoute a la liste tous les elements pass�s en parametre
- * @param col la liste
- * @param pos le premier index o� ins�rer les donn�es
- * @param e les elements a ajouter
- * @return la liste pass� en parametre
- */
- static public <A, E extends List<A>> E addAll(E col, int pos, A ... e) {
- col.addAll(pos, Arrays.asList(e));
- return col;
- }
-
- /**
- * Permet de convertir une liste non typ�e, en une liste typ�e.
- *
- * La liste en entr�e en juste bien cast�e.
- *
- * On effectue une v�rification sur le typage des �lements de la liste.
- *
- * Note : <b>Aucune liste n'est cr�ee, ni recopi�e</b>
- *
- * @param list la liste � convertir
- * @param type le type des �l�ments de la liste
- * @return la liste typ�e
- * @throws IllegalArgumentException si un �l�ment de la liste en entr�e n'est
- * pas en ad�quation avec le type voulue.
- */
- @SuppressWarnings({"unchecked"})
- static public <O> List<O> toGenericList(List list,Class<O> type) throws IllegalArgumentException {
- if (list.isEmpty()) {
- return list;
- }
- for (Object o : list) {
- if (!(type.isAssignableFrom(o.getClass()))) {
- throw new IllegalArgumentException("can not cast List with object of type "+o.getClass()+" to "+type+" type!");
- }
- }
- return list;
- }
-
- /**
- * Permet de convertir une collection non typ�e, en une collection typ�e.
- *
- * La collection en entr�e en juste bien cast�e.
- *
- * On effectue une v�rification sur le typage des �lements de la collection.
- *
- * Note : <b>Aucune collection n'est cr�ee, ni recopi�e</b>
- *
- * @param list la collection � convertir
- * @param type le type des �l�ments de la collection
- * @return la collection typ�e
- * @throws IllegalArgumentException si un �l�ment de la collection en entr�e n'est
- * pas en ad�quation avec le type voulue.
- */
- @SuppressWarnings({"unchecked"})
- static public <O> Collection<O> toGenericCollection(Collection list,Class<O> type) throws IllegalArgumentException {
- if (list.isEmpty()) {
- return list;
- }
- for (Object o : list) {
- if (!(type.isAssignableFrom(o.getClass()))) {
- throw new IllegalArgumentException("can not cast Collection with object of type "+o.getClass()+" to "+type+" type!");
- }
- }
- return list;
- }
-
- /**
- * Permet de convertir un ensemble non typ�e, en un ensemble typ�e.
- *
- * L'ensemble en entr�e en juste bien cast�e.
- *
- * On effectue une v�rification sur le typage des �lements de la collection.
- *
- * Note : <b>Aucun ensemble n'est cr�ee, ni recopi�e</b>
- *
- * @param list l'ensemble � convertir
- * @param type le type des �l�ments de l'ensemble
- * @return l'ensemble typ�e
- * @throws IllegalArgumentException si un �l�ment de l'ensemble en entr�e n'est
- * pas en ad�quation avec le type voulue.
- */
- @SuppressWarnings({"unchecked"})
- static public <O> Set<O> toGenericSet(Set list,Class<O> type) throws IllegalArgumentException {
- if (list.isEmpty()) {
- return list;
- }
- for (Object o : list) {
- if (!(type.isAssignableFrom(o.getClass()))) {
- throw new IllegalArgumentException("can not cast Set with object of type "+o.getClass()+" to "+type+" type!");
- }
- }
- return list;
- }
-}
-
-
Deleted: trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/FileUtil.java
===================================================================
--- trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/FileUtil.java 2008-08-04 13:30:38 UTC (rev 965)
+++ trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/FileUtil.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -1,766 +0,0 @@
-/* *##%
- * Copyright (C) 2002, 2003, 2004 Code Lutin, C�dric Pineau,
- * Benjamin Poussin
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *##%*/
-
-/* *
- * FileUtil.java
- *
- * Created: 22 nov. 2004
- *
- * @author Benjamin Poussin <poussin(a)codelutin.com>
- * @version $Revision$
- *
- * Mise a jour: $Date$
- * par : $Author$
- */
-
-package org.codelutin.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.nio.channels.FileChannel;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.LinkedList;
-import java.util.List;
-
-import javax.swing.JFileChooser;
-
-import org.apache.commons.logging.LogFactory;
-
-public class FileUtil { // FileUtil
-
- /** to use log facility, just put in your code: log.info(\"...\"); */
- static private org.apache.commons.logging.Log log = LogFactory.getLog(FileUtil.class);
-
- /** Encoding par defaut utilis� si non sp�cifi� */
- static public String ENCODING = "ISO-8859-1";
- static protected File currentDirectory = new File(".");
-
- static public void setCurrentDirectory(File dir){
- currentDirectory = dir;
- }
-
- static public class PatternChooserFilter extends javax.swing.filechooser.FileFilter {
- protected String pattern = null;
- protected String description = null;
-
- public PatternChooserFilter(String pattern, String description) {
- this.pattern = pattern;
- this.description = description;
- }
-
- @Override
- public boolean accept(File f) {
- return f.isDirectory() || f.getAbsolutePath().matches(pattern);
- }
- @Override
- public String getDescription() {
- return description;
- }
-
- }
-
-
- /**
- * Retourne le nom du fichier entre dans la boite de dialogue.
- * Si le bouton annuler est utilis�, ou qu'il y a une erreur retourne null.
- *
- * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre donn�es
- * par deux, le pattern du filtre + la description du filtre
- * @return
- *
- * @see #getFile(javax.swing.filechooser.FileFilter[])
- */
- static public File getFile(String ... patternOrDescriptionFilters) {
- if (patternOrDescriptionFilters.length % 2 != 0) {
- throw new IllegalArgumentException("Arguments must be (pattern, description) couple");
- }
- javax.swing.filechooser.FileFilter [] filters = new javax.swing.filechooser.FileFilter[patternOrDescriptionFilters.length / 2];
- for (int i=0; i<filters.length; i++) {
- String pattern = patternOrDescriptionFilters[i*2];
- String description = patternOrDescriptionFilters[i*2 + 1];
- filters[i] = new PatternChooserFilter(pattern, description);
- }
- File result;
- result = getFile(filters);
- return result;
- }
-
- /**
- * Retourne le nom du fichier entre dans la boite de dialogue.
- * Si le bouton annuler est utilis�, ou qu'il y a une erreur retourne null.
- *
- * @param filters les filtres a ajouter
- * @return
- */
- static public File getFile(javax.swing.filechooser.FileFilter ... filters){
- try{
- JFileChooser chooser = new JFileChooser(currentDirectory);
-
- chooser.setDialogType(JFileChooser.CUSTOM_DIALOG);
- if (filters.length > 0) {
- if (filters.length == 1) {
- chooser.setFileFilter(filters[0]);
- } else {
- for (javax.swing.filechooser.FileFilter filter : filters) {
- chooser.addChoosableFileFilter(filter);
- }
- }
- }
- chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
- int returnVal = chooser.showDialog(null, "Ok");
- if(returnVal == JFileChooser.APPROVE_OPTION) {
- File theFile = chooser.getSelectedFile();
- if(theFile != null) {
- currentDirectory = theFile;
- return theFile.getAbsoluteFile();
- }
- }
- }
- catch(Exception eee){
- log.warn("Erreur:", eee);
- }
- return null;
- }
-
- /**
- * @param title le nom de la boite de dialogue
- * @param approvalText
- * @return le nom du repertoire entre dans la boite de dialogue.
- * Si le bouton annuler est utilis�, ou qu'il y a une erreur retourne
- * null.
- */
- static public String getDirectory(String title,String approvalText) {
- try{
- JFileChooser chooser = new JFileChooser(currentDirectory);
- chooser.setDialogType(JFileChooser.CUSTOM_DIALOG);
- chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
- chooser.setDialogTitle(title);
- int returnVal = chooser.showDialog(null,approvalText);
- if(returnVal == JFileChooser.APPROVE_OPTION) {
- File theFile = chooser.getSelectedFile();
- if(theFile != null) {
- currentDirectory = theFile;
- if(theFile.isDirectory()) {
- return theFile.getAbsolutePath();
- }
- }
- }
- else{
- return null;
- }
- } catch(Exception eee){
- log.warn("Erreur:", eee);
- }
- return null;
- }
-
- /**
- * @return le nom du repertoire entre dans la boite de dialogue.
- * Si le bouton annuler est utilis�, ou qu'il y a une erreur retourne
- * null.
- */
- static public String getDirectory() {
- return getDirectory("Ok","Ok");
- }
-
- /**
- * Permet de convertir un fichier en un tableau de byte
- *
- * @param file
- * @return
- * @throws IOException
- */
- static public byte[] fileToByte(File file) throws IOException {
- InputStream in = new BufferedInputStream(new FileInputStream(file));
- ByteArrayOutputStream result = new ByteArrayOutputStream();
- BufferedOutputStream tmp = new BufferedOutputStream(result);
- for (int b=in.read(); b != -1; b=in.read()) {
- tmp.write(b);
- }
- in.close();
- tmp.close();
-
- return result.toByteArray();
- }
-
- /**
- * Permet de convertir des bytes en fichier, le fichier sera automatiquement
- * supprim� a la fin de la JVM.
- *
- * @param bytes
- * @return le fichier temporaire contenant les bytes
- * @throws IOException
- */
- static public File byteToFile(byte[] bytes) throws IOException {
- File file = File.createTempFile("FileUtil-byteToFile", ".tmp");
- byteToFile(bytes, file);
- return file;
- }
-
- /**
- * Permet de convertir des bytes en fichier
- *
- * @param bytes
- * @param file le fichier dans lequel il faut ecrire les bytes
- * @return le fichier pass� en parametre
- * @throws IOException
- */
- static public File byteToFile(byte[] bytes, File file) throws IOException {
- OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
- out.write(bytes);
- out.close();
- return file;
- }
-
- /**
- * Retourne un Reader utilisant l'encoding par defaut {@link #ENCODING}
- *
- * @param file
- * @return
- * @throws IOException
- */
- static public BufferedReader getReader(File file) throws IOException {
- return getReader(file, ENCODING);
- }
-
- /**
- * Retourne un reader utilisant l'encoding choisi et plac� dans un
- * BufferedReader
- *
- * @param file
- * @param encoding (ISO-8859-1, UTF-8, ...)
- * @return
- * @throws IOException
- */
- static public BufferedReader getReader(File file, String encoding) throws IOException {
- FileInputStream inf = new FileInputStream(file);
- InputStreamReader in = new InputStreamReader(inf, encoding);
-// FileReader in = new FileReader(file);
- BufferedReader result = new BufferedReader(in);
- return result;
- }
-
- /**
- * Retourne un Writer utilisant l'encoding par defaut {@link #ENCODING}
- *
- * @param file
- * @return
- * @throws IOException
- */
- static public BufferedWriter getWriter(File file) throws IOException {
- return getWriter(file, ENCODING);
- }
-
- /**
- * Retourne un writer utilisant l'encoding choisi et plac� dans un
- * BufferedWriter
- *
- * @param file
- * @param encoding (ISO-8859-1, UTF-8, ...)
- * @return
- * @throws IOException
- */
- static public BufferedWriter getWriter(File file, String encoding) throws IOException {
- FileOutputStream outf = new FileOutputStream(file);
- OutputStreamWriter out = new OutputStreamWriter(outf, encoding);
-// FileWriter out = new FileWriter(file);
- BufferedWriter result = new BufferedWriter(out);
- return result;
- }
-
- public static void main(String[] args) {
-
- }
-
- /**
- * Permet de creer un nouveu repertoire temporaire, l'effacement du
- * r�pertoire est a la charge de l'appelant
- * @param prefix le prefix du fichier
- * @param suffix le suffix du fichier
- * @param tmpdir le r�pertoire temporaire ou il faut creer le repertoire
- * si null on utilise java.io.tmpdir
- * @return le fichier pointant sur le nouveau repertoire
- * @throws java.io.IOException
- */
- static public File createTempDirectory(String prefix, String suffix, File tmpdir) throws IOException {
- if (tmpdir == null) {
- tmpdir = new File(System.getProperty("java.io.tmpdir"));
- }
- File result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix);
- while (result.exists()) {
- result = new File(tmpdir, prefix + System.currentTimeMillis() + suffix);
- }
- if (!result.mkdirs()) {
- throw new IOException("Can't create temporary directory: " + result);
- }
- return result;
- }
- /**
- * Permet de creer un nouveu repertoire temporaire, l'effacement du
- * r�pertoire est a la charge de l'appelant
- * @param prefix
- * @param suffix
- * @return
- * @throws java.io.IOException
- */
- static public File createTempDirectory(String prefix, String suffix) throws IOException {
- return createTempDirectory(prefix, suffix, null);
- }
-
- /**
- * Regarde si le fichier f1 est plus recent que le fichier f2
- * @param f1
- * @param f2
- * @return vrai si f1 est plus recent que f2
- */
- static public boolean isNewer(File f1, File f2) {
- boolean result = f1.lastModified() > f2.lastModified();
- return result;
- }
-
- /**
- * Permet de lire un fichier et de retourner sont contenu sous forme d'une
- * chaine de carateres
- * @param file le fichier a lire
- * @throws IOException
- * @return
- */
- static public String readAsString(File file) throws IOException {
- StringBuffer result = new StringBuffer();
- char [] cbuf = new char[2000];
- BufferedReader in = getReader(file);
- int nb = in.read(cbuf);
- while (nb != -1) {
- result.append(cbuf, 0, nb);
- nb = in.read(cbuf);
- }
- in.close();
- return result.toString();
- }
-
- /**
- * Permet de sauver une chaine directement dans un fichier
- * @param file Le fichier dans lequel il faut ecrire la chaine
- * @param content Le texte a ecrire dans le fichier
- * @throws IOException if any pb while writing
- */
- static public void writeString(File file, String content) throws IOException {
- file.getParentFile().mkdirs();
- BufferedWriter out = getWriter(file);
- out.write(content);
- out.close();
- }
-
- /**
- * Permet de sauver une chaine directement dans un fichier
- * @param file Le fichier dans lequel il faut ecrire la chaine
- * @param content Le texte a ecrire dans le fichier
- * @param encoding encoding to use
- * @throws IOException if any pb while writing
- */
- static public void writeString(File file, String content,String encoding) throws IOException {
- file.getParentFile().mkdirs();
- BufferedWriter out = getWriter(file,encoding);
- out.write(content);
- out.close();
- }
-
- /**
- * Permet de donner une representation fichier pour une chaine de caractere.
- * Le fichier sera automatiquement effac� � la fin de la JVM.
- * @param content le contenu du fichier temporaire
- * @return le fichier qui contient content
- * @throws IOException
- */
- static public File getTempFile(String content) throws IOException {
- return getTempFile(content, "");
- }
-
- /**
- * Permet de donner une representation fichier pour une chaine de caractere.
- * Le fichier sera automatiquement effac� � la fin de la JVM.
- * @param content le contenu du fichier temporaire
- * @param fileSuffix l'extension du fichier cr��
- * @return le fichier qui contient content
- * @throws IOException
- */
- static public File getTempFile(String content, String fileSuffix) throws IOException {
- File result = File.createTempFile("tmp-" + FileUtil.class.getName(), fileSuffix);
- result.deleteOnExit();
- writeString(result, content);
- return result;
- }
-
- /**
- * Equivalent de la methode basename unix.
- * basename("/tmp/toto.xml", ".xml") -> "toto"
- *
- * @param file le fichier dont on souhaite le nom sans le chemin
- * @param suffixes si present represente le suffixe a eliminer du fichier
- * s'il est trouv�
- * @return le nom du fichier sans le suffixe si trouv�.
- */
- static public String basename(File file, String ... suffixes) {
- String result = file.getName();
- for(String suffixe : suffixes) {
- if (result.endsWith(suffixe)){
- result = result.substring(0, result.length() - suffixe.length());
- break;
- }
- }
- return result;
- }
-
- /**
- * Permet de r�cup�rer l'extension d'un fichier
- * @param file le fichier dont on souhaite l'extension
- * @param extchars la liste des caracteres pouvant former l'extension
- * dans l'ordre de preference. Si vide on utilise ".".
- * @return l'extension ou la chaine vide si le fichier n'a pas d'extension
- * l'extension ne contient pas le chaine de delimitation
- */
- static public String extension(File file, String ... extchars) {
- String result = "";
- String name = file.getName();
-
- if(extchars.length == 0) {
- extchars = new String[]{"."};
- }
- for (String extchar : extchars) {
- int pos = name.lastIndexOf(extchar);
- if (pos != -1) {
- result = name.substring(pos + extchar.length());
- break;
- }
- }
- return result;
- }
-
- static public interface FileAction {
- public boolean doAction(File f);
- }
-
- /**
- * Retourne tous les sous r�pertoires du r�pertoire pass� en argument.
- * @param directory un r�pertoire
- * @return une liste d'objet {@link java.io.File} de r�pertoires et ceci
- * recursivement � partir de directory, si directory
- * n'est pas un r�pertoire la liste est vide.
- */
- public static List<File> getSubDirectories(File directory) {
- class DirectoryFilter implements FileFilter {
- public boolean accept(File f) {
- return f.isDirectory();
- }
- }
- return getFilteredElements(directory, new DirectoryFilter(), true);
- }
-
- /**
- * Retourne tous les fichiers du r�pertoire pass� en argument.
- * @param directory un r�pertoire
- * @return une liste d'objet {@link java.io.File} des fichiers et ceci
- * recursivement � partir de directory, si directory n'est pas un
- * r�pertoire la liste est vide
- */
- public static List<File> getFiles(File directory) {
- class NormalFileFilter implements FileFilter {
- public boolean accept(File f) {
- return f.isFile();
- }
- }
- return getFilteredElements(directory, new NormalFileFilter(), true);
- }
-
- /**
- * Retourne les fichiers d'un r�pertoire qui s'attisfont un certain pattern.
- * La recherche est faite r�cursivement dans les sous r�pertoires
- * @param directory le r�pertoire � partir duquel il faut faire la recherche
- * @param pattern le pattern que doit respecter le fichier pour �tre dans la
- * liste r�sultante
- * @param recursively
- * @return une liste d'objet {@link java.io.File} qui ont s'attisfait le
- * pattern.
- */
- public static List<File> find(File directory, final String pattern, boolean recursively){
- final String root = directory.getAbsolutePath();
- final int rootLength = root.length();
-
- return getFilteredElements(directory, new FileFilter() {
- public boolean accept(File f) {
- String longFilename = f.getAbsolutePath();
- // + 1 to remove the first / or \
- String filename = longFilename.substring(rootLength + 1);
- return filename.matches(pattern);
- }
- }, recursively);
- }
-
- /**
- * Retourne la liste de toutes les fichiers ou r�pertoire qui s'attisfont
- * le filtre
- * @param directory repertoire � partir duquel il faut faire la recherche
- * @param ff le filtre � appliquer pour savoir si le fichier parcouru doit
- * �tre conserv� dans les r�sultats, ou null pour tous les fichiers
- * @param recursively
- * @return une liste d'objet {@link java.io.File}, qui s'attisfont le filtre
- */
- public static List<File> getFilteredElements(File directory, FileFilter ff, boolean recursively) {
- ArrayList<File> result = new ArrayList<File>();
- LinkedList<File> todo = new LinkedList<File>();
- if (directory.isDirectory()){
- todo.addAll(Arrays.asList(directory.listFiles()));
- }
- while(todo.size() > 0){
- File file = todo.removeFirst();
- if (recursively && file.isDirectory()){
- File [] childs = file.listFiles();
- if (childs != null) { // null if we don't have access to directory
- todo.addAll(Arrays.asList(childs));
- }
- }
- if(ff == null || ff.accept(file)){
- result.add(file);
- }
- }
- return result;
- }
-
- /**
- * Supprime recursivement tout le contenu d'un r�pertoire.
- * @param directory
- * @return vrai si tout se passe bien, false si la suppression d'un �lement
- * se passe mal
- */
- public static boolean deleteRecursively(String directory) {
- return deleteRecursively(new File(directory));
- }
-
- /**
- * Supprime recursivement tout le contenu d'un r�pertoire.
- * @param directory
- * @return vrai si tout se passe bien, false si la suppression d'un �lement
- * se passe mal
- */
- public static boolean deleteRecursively(File directory) {
- return walkBefore(directory, new FileAction(){
- public boolean doAction(File f) {
- return f.delete();
- }
- });
- }
-
- /**
- * Permet de faire une action avant le parcours des fichiers, c-a-d que
- * l'on fera l'action sur les fichiers contenu dans un r�pertoire
- * apr�s l'action sur le r�pertoire lui m�me.
- * @param f le fichier ou r�pertoire � partir duquel il faut commencer
- * @param fileAction l'action � effectuer sur chaque fichier
- * @return le r�sultat des fileAction execut� sur les fichiers, chaque
- * r�sultat de FileAction sont assembl� par un ET logique pour donner
- * le r�sultat final
- */
- public static boolean walkAfter(File f, FileAction fileAction) {
- boolean result=fileAction.doAction(f);
- if (f.isDirectory()) {
- File list[] = f.listFiles();
- for (int i = 0; i < list.length; i++) {
- result=result && walkAfter(list[i], fileAction);
- }
- }
- return result;
- }
-
- /**
- * Permet de faire une action ap�s le parcours des fichiers, c-a-d que
- * l'on fera l'action sur les fichiers contenu dans un r�pertoire
- * avant l'action sur le r�pertoire lui m�me.
- * @param f le fichier ou r�pertoire � partir duquel il faut commencer
- * @param fileAction l'action � effectuer sur chaque fichier
- * @return le r�sultat des fileAction execut� sur les fichiers, chaque
- * r�sultat de FileAction sont assembl� par un ET logique pour donner
- * le r�sultat final
- */
- public static boolean walkBefore(File f, FileAction fileAction) {
- boolean result=true;
- if (f.isDirectory()) {
- File list[] = f.listFiles();
- for (int i = 0; i < list.length; i++) {
- result=result && walkBefore(list[i], fileAction);
- }
- }
- return result && fileAction.doAction(f);
- }
-
- /**
- * Permet de copier le fichier source vers le fichier cible.
- * @param source le fichier source
- * @param target le fichier cible
- * @throws IOException Erreur de copie
- */
- public static void copy(File source, File target) throws IOException {
- target.getParentFile().mkdirs();
- FileChannel sourceChannel = new FileInputStream(source).getChannel();
- FileChannel targetChannel = new FileOutputStream(target).getChannel();
- sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
- // or
- // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
- sourceChannel.close();
- targetChannel.close();
- }
-
- /**
- * Permet de copier le fichier source vers le fichier cible.
- * @param source le fichier source
- * @param target le fichier cible
- * @throws IOException Erreur de copie
- */
- public static void copy(String source, String target) throws IOException {
- copy(new File(source), new File(target));
- }
-
- /**
- * Copie recursivement le repertoire source dans le repertoire destination
- *
- * copyRecursively("/truc/titi", "/var/tmp") donnera le repertoire
- * "/var/tmp/titi"
- *
- * @param srcDir
- * @param destDir
- * @param includePatterns les patterns que doivent resperter les
- * fichiers/repertoires pour etre copi�. Si vide alors tout est copi�
- *
- * @throws IOException
- */
- static public void copyRecursively(File srcDir, File destDir, String ... includePatterns) throws IOException {
- copyAndRenameRecursively(srcDir, destDir, null, null, includePatterns);
- }
-
- /**
- * Copie recursivement le repertoire source dans le repertoire destination
- *
- * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire
- * "/var/tmp/bidulle", 'bidulle' remplacant 'titi'
- *
- * @param srcDir
- * @param destDir
- * @param renameFrom pattern to permit rename file before uncompress it
- * @param renameTo new name for file if renameFrom is applicable to it
- * you can use $1, $2, ... if you have '(' ')' in renameFrom
- * @param includePatterns les patterns que doivent resperter les
- * fichiers/repertoires pour etre copi�. Si vide alors tout est copi�
- *
- * @throws IOException
- */
- static public void copyAndRenameRecursively(File srcDir, File destDir,
- String renameFrom, String renameTo, String ... includePatterns) throws IOException {
- copyAndRenameRecursively(srcDir, destDir, true, renameFrom, renameTo, false, includePatterns);
- }
-
- /**
- * Copie recursivement le repertoire source dans le repertoire destination
- *
- * copyRecursively("/truc/titi", "/var/tmp", "bidulle") donnera le repertoire
- * "/var/tmp/bidulle", 'bidulle' remplacant 'titi'
- *
- * @param srcDir
- * @param destDir
- * @param includeSrcDir si vrai alors le repertoire source est copie dans le
- * repertoire destination et non pas seulement les fichiers qu'il contient
- * @param renameFrom pattern to permit rename file before uncompress it
- * @param renameTo new name for file if renameFrom is applicable to it
- * you can use $1, $2, ... if you have '(' ')' in renameFrom
- * @param exclude inverse include pattern interpretation
- * @param includePatterns les patterns que doivent resperter les
- * fichiers/repertoires pour etre copi�. Si vide alors tout est copi�
- *
- * @throws IOException
- */
- static public void copyAndRenameRecursively(File srcDir, File destDir,
- boolean includeSrcDir, String renameFrom, String renameTo, boolean exclude,
- String ... includePatterns) throws IOException {
- String rootSrc;
- if (includeSrcDir) {
- rootSrc = srcDir.getParent();
- } else {
- rootSrc = srcDir.getPath();
- }
- List<File> files = getFilteredElements(srcDir, null, true);
- log.debug("copyRecursively: " + files);
- for (File file : files) {
- boolean doCopy = copyRecursivelyAccept(file, includePatterns);
- if (xor(exclude, doCopy)) {
- String path = file.getPath().substring(rootSrc.length());
- if (renameFrom != null && renameTo != null) {
- String tmp = path.replaceAll(renameFrom, renameTo);
- if (log.isDebugEnabled()) {
- log.debug("rename " + path + " -> " + tmp);
- }
- path = tmp;
- }
-
- File destFile = new File(destDir, path);
- if (file.isDirectory()) {
- log.debug("create directory: " + destFile);
- destFile.mkdirs();
- } else {
- log.debug("copy " + path + " to " + destFile);
- copy(file, destFile);
- }
- }
- }
- }
-
- static private boolean xor(boolean b, boolean c) {
- if (b) return !c;
- else return c;
- }
-
- /**
- * @param file
- * @param includePatterns
- * @return
- */
- private static boolean copyRecursivelyAccept(File file, String[] includePatterns) {
- boolean result = includePatterns.length == 0;
- String filename = file.getAbsolutePath();
- for (String pattern : includePatterns) {
- result = filename.matches(pattern);
- if (result) {
- break;
- }
- }
- return result;
- }
-
-} // FileUtil
-
Deleted: trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java
===================================================================
--- trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java 2008-08-04 13:30:38 UTC (rev 965)
+++ trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -1,50 +0,0 @@
-/*
-* ##% Copyright (C) 2008 Code Lutin, Gabriel Landais
-*
-* This program is free software; you can redistribute it and/or
-* modify it under the terms of the GNU General Public License
-* as published by the Free Software Foundation; either version 2
-* of the License, or (at your option) any later version.
-*
-* This program is distributed in the hope that it will be useful,
-* but WITHOUT ANY WARRANTY; without even the implied warranty of
-* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-* GNU General Public License for more details.
-*
-* You should have received a copy of the GNU General Public License
-* along with this program; if not, write to the Free Software
-* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
-* ##% */
-package org.codelutin.util;
-
-import java.io.FilterOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-public class PropertiesDateRemoveFilterStream extends FilterOutputStream {
-
- private boolean firstLineOver;
- char endChar;
-
- public PropertiesDateRemoveFilterStream(OutputStream out) {
- super(out);
- firstLineOver = false;
- String lineSeparator = java.security.AccessController
- .doPrivileged(new sun.security.action.GetPropertyAction(
- "line.separator"));
- endChar = lineSeparator.charAt(lineSeparator.length() - 1);
- }
-
- @Override
- public void write(int b) throws IOException {
- if (!firstLineOver) {
- char c = (char) b;
- if (c == endChar) {
- firstLineOver = true;
- }
- } else {
- out.write(b);
- }
- }
-
-}
\ No newline at end of file
Deleted: trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/SortedProperties.java
===================================================================
--- trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/SortedProperties.java 2008-08-04 13:30:38 UTC (rev 965)
+++ trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/SortedProperties.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -1,62 +0,0 @@
-/* *##%
- * Copyright (C) 2007
- * I18nPlugin, Code Lutin
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *##%*/
-
-package org.codelutin.util;
-
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Properties;
-import java.util.Vector;
-
-/**
- * Permet d'avoir les fichiers de propri�t�s tri�s.
- *
- * @author julien
- */
-public class SortedProperties extends Properties {
-
- private static final long serialVersionUID = -1147150444452577558L;
-
-
- public SortedProperties() {
- super();
- }
-
- public SortedProperties(Properties defaults) {
- super(defaults);
- }
-
- @Override
- public synchronized Enumeration<Object> keys() {
- List<Object> objects = Collections.list(super.keys());
- Vector<Object> result;
- try {
- // Attention, si les clef ne sont pas des string, ca ne marchera pas
- List<String> list = CollectionUtil.toGenericList(objects, String.class);
- Collections.sort(list);
- result = new Vector<Object>(list);
- } catch (IllegalArgumentException e) {
- // keys are not string !!!
- // can not sort keys
- result = new Vector<Object>(objects);
- }
- return result.elements();
- }
-}
Deleted: trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtil.java
===================================================================
--- trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtil.java 2008-08-04 13:30:38 UTC (rev 965)
+++ trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtil.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -1,552 +0,0 @@
-/* *##%%
- * Copyright (C) 2002, 2003 Code Lutin
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
- *##%%**/
-/* *
- * StringUtil.java
- *
- * Created: Sun Apr 14 2002
- *
- * @author POUSSIN Benjamin <bpoussin(a)free.fr>
- * Copyright Code Lutin
- * @version $Revision$
- *
- * Mise a jour: $Date$
- * par : $Author$
- */
-package org.codelutin.util;
-
-import java.awt.Color;
-import java.lang.reflect.Field;
-import java.text.DateFormat;
-import java.text.MessageFormat;
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-
-/**
- * Classe contenant un ensemle de methode static utiles pour la manipulation des
- * chaine de caractere mais qui ne sont pas defini dans la classe String de
- * Java.
- *
- * @author poussin
- * @created 21 octobre 2003
- */
-public class StringUtil { // StringUtil
-
- /** Constructor for the StringUtil object */
- protected StringUtil() {
- }
-
- /**
- * Cette methode retire les accents. Quand le caractere est connu, elle le
- * remplace par une version sans accent sinon, elle le supprime.
- * Les caracteres non-alphanumeriques sont supprimes.
- *
- * @param s la chaine a unaccentuer
- * @return la chaine sans accent
- */
- static public String unaccent(String s) {
- String result = "";
- for (char c : s.toCharArray()) {
- if ("����".indexOf(c) != -1) {
- result += "e";
- } else if ("���".indexOf(c) != -1) {
- result += "a";
- } else if ("�".indexOf(c) != -1) {
- result += "c";
- } else if ("��".indexOf(c) != -1) {
- result += "i";
- } else if ("��".indexOf(c) != -1) {
- result += "o";
- } else if ("���".indexOf(c) != -1) {
- result += "u";
- } else if ("����".indexOf(c) != -1) {
- result += "E";
- } else if ("���".indexOf(c) != -1) {
- result += "A";
- } else if ("�".indexOf(c) != -1) {
- result += "C";
- } else if ("��".indexOf(c) != -1) {
- result += "I";
- } else if ("��".indexOf(c) != -1) {
- result += "O";
- } else if ("���".indexOf(c) != -1) {
- result += "U";
- } else if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')
- || ('0' <= c && c <= '9') || ('.' == c) || ('-' == c)
- || ('_' == c)) {
- result += c;
- } else {
- // on ne l'ajoute pas a result donc on supprime le caractere
- // result += encodeUTF(c);
- }
- }
- return result;
- }
-
- static public String substring(String s, int begin) {
- String result;
- result = substring(s, begin, s.length());
- return result;
- }
-
- static public String substring(String s, int begin, int end) {
- if (begin < 0) {
- begin = s.length() + begin;
- }
- if (end < 0) {
- end = s.length() + end;
- }
- if (end < begin) {
- end = begin;
- }
-
- String result;
- result = s.substring(begin, end);
- return result;
- }
-
- /**
- * Met en majuscule le premier caractere de la chaine passee en parametre
- *
- * @param word La chaine a capitaliser
- * @return La chaine capitalisee
- * @deprecated you must use
- * org.apache.commons.lang.StringUtils.capitalise(String)
- */
- public static String capitalize(String word) {
- return word.substring(0, 1).toUpperCase() + word.substring(1);
- }
-
- /**
- * Met en minuscule le premier caractere de la chaine passe en parametre
- *
- * @param word La chaine a decapitaliser
- * @return La chaine decapitalisee
- * @deprecated you must use
- * org.apache.commons.lang.StringUtils.uncapitalise(String)
- */
- public static String uncapitalize(String word) {
- return word.substring(0, 1).toLowerCase() + word.substring(1);
- }
-
- /**
- * Concat�ne un tableau de chaine de caracteres en une seul chaine.
- *
- * @param s le tableau de chaines
- * @param sep le separateur a utiliser pour separer chaque chaine.
- * @return la chaine resultante de la concatenation. Si le tableau est null
- * ou vide, la chaine resultante est une chaine vide.
- * @deprecated you must use org.apache.commons.lang.StringUtils.join
- */
- public static String unsplit(String[] s, String sep) {
- if (s == null || s.length <= 0) {
- return "";
- }
-
- StringBuffer result = new StringBuffer(s[0]);
- for (int i = 1; i < s.length; i++) {
- result.append(sep).append(s[i]);
- }
- return result.toString();
- }
-
- private static final Character[] openingChars = {'(', '{', '['};
-
- private static final Character[] closingChars = {')', '}', ']'};
-
- /**
- * Split string use 'separator' as separator. If String contains "'()[]{}
- * this method count the number of open char end close char to split
- * correctly argument
- *
- * @param args string to split
- * @param separator separator use to split string
- * @return array of string
- */
- static public String[] split(String args, String separator) {
- return split(openingChars, closingChars, args, separator);
- }
-
-
- /**
- * Use to split string array representation in array according with swixat
- * seperator list
- *
- * @param stringList string that represent array
- * @return array with length > 0 if listAsString != null or null
- */
- static public String[] split(String stringList) {
- String[] result;
- result = split(stringList, ",");
- return result;
- }
-
- /**
- * Split string use 'separator' as separator. If String contains "'
- * and <code>openingChar</code> <code>closingChars</code>
- * <p/>
- * this method count the number of open char end close char to split correctly
- * argument
- *
- * @param openingChars list of opening caracteres
- * @param closingChars list of closing caracteres
- * @param args string to split
- * @param separator separator use to split string
- * @return array of string
- */
- static public String[] split(Character[] openingChars,
- Character[] closingChars,
- String args, String separator) {
- if (args == null) {
- return new String[0];
- }
-
- List<String> result = new ArrayList<String>();
-
- int start = 0;
- int end;
- StringBuffer op = new StringBuffer(); // stack of {([< currently open
- char last = '\0'; // contains " or ' if string is openned
-
- List<Character> opening = Arrays.asList(openingChars);
-
- List<Character> closing = Arrays.asList(closingChars);
-
- for (int i = 0; i < args.length(); i++) {
- char c = args.charAt(i);
- if (c == '\\') {
- // pass next char
- i++;
- } else if (last != '"' && last != '\'') {
- if (opening.contains(c)) {
- op.append(c);
- } else if (closing.contains(c)) {
- op.deleteCharAt(op.length() - 1);
- } else if (c == '"' || c == '\'') {
- // open string " or '
- last = c;
- } else if (op.length() == 0 &&
- args.regionMatches(i, separator, 0, separator.length())) {
- // end of one arguement
- end = i;
- // pass separator
- i += separator.length() - 1;
-
- String a = args.substring(start, end);
- result.add(a);
- // start of next argument
- start = end + separator.length();
- }
- } else if (c == last) {
- // close string " or '
- last = '\0';
- }
- }
-
- if (start < args.length()) {
- String a = args.substring(start, args.length());
- result.add(a);
- }
-
- return result.toArray(new String[result.size()]);
- }
-
- public static boolean toBoolean(String s) {
- return "true".equalsIgnoreCase(s);
- }
-
- public static byte toByte(String s) {
- return Byte.parseByte(s);
- }
-
- public static double toDouble(String s) {
- return Double.parseDouble(s);
- }
-
- public static float toFloat(String s) {
- return Float.parseFloat(s);
- }
-
- public static long toLong(String s) {
- return Long.parseLong(s);
- }
-
- public static short toShort(String s) {
- return Short.parseShort(s);
- }
-
- public static int toInt(String s) {
- return Integer.parseInt(s);
- }
-
- public static char toChar(String s) {
- // fixme a revoir
- return s.charAt(0);
- }
-
- public static boolean[] toArrayBoolean(String... s) {
- boolean[] result = new boolean[s.length];
- for (int i = 0; i < result.length; i++) {
- result[i] = toBoolean(s[i]);
- }
- return result;
- }
-
- public static byte[] toArrayByte(String... s) {
- byte[] result = new byte[s.length];
- for (int i = 0; i < result.length; i++) {
- result[i] = toByte(s[i]);
- }
- return result;
- }
-
- public static double[] toArrayDouble(String... s) {
- double[] result = new double[s.length];
- for (int i = 0; i < result.length; i++) {
- result[i] = toDouble(s[i]);
- }
- return result;
- }
-
- public static float[] toArrayFloat(String... s) {
- float[] result = new float[s.length];
- for (int i = 0; i < result.length; i++) {
- result[i] = toFloat(s[i]);
- }
- return result;
- }
-
- public static long[] toArrayLong(String... s) {
- long[] result = new long[s.length];
- for (int i = 0; i < result.length; i++) {
- result[i] = toLong(s[i]);
- }
- return result;
- }
-
- public static short[] toArrayShort(String... s) {
- short[] result = new short[s.length];
- for (int i = 0; i < result.length; i++) {
- result[i] = toShort(s[i]);
- }
- return result;
- }
-
- public static int[] toArrayInt(String... s) {
- int[] result = new int[s.length];
- for (int i = 0; i < result.length; i++) {
- result[i] = toInt(s[i]);
- }
- return result;
- }
-
- public static char[] toArrayChar(String... s) {
- char[] result = new char[s.length];
- for (int i = 0; i < result.length; i++) {
- result[i] = toChar(s[i]);
- }
- // fixme a revoir
- return result;
- }
-
- /**
- * Essai de convertir une chaine de caractere en une couleur si possible si
- * ce n'est pas possible retourne null.
- *
- * @param s la couleur sous la forme de string, par exemple "red",
- * "yellow" ou bien en RGB "#FFAA99", et avec un canal alpha
- * "#FFAA3366"
- * @return la couleur demand� si possible sinon null
- * @throws IllegalArgumentException
- * @throws StringUtilException if any problem while conversion
- */
- public static Color toColor(String s) throws StringUtilException {
- try {
- if (s.startsWith("#")) {
- // r�cuperation des valeurs hexa
- String hr = s.substring(1, 3);
- String hg = s.substring(3, 5);
- String hb = s.substring(5, 7);
-
- // conversion en entier
- int r = Integer.parseInt(hr, 16);
- int g = Integer.parseInt(hg, 16);
- int b = Integer.parseInt(hb, 16);
-
- if (s.length() == 9) {
- // s'il y a un canal alpha on l'utilise
- String ha = s.substring(7, 9);
- int a = Integer.parseInt(ha, 16);
- return new Color(r, g, b, a);
- } else {
- return new Color(r, g, b);
- }
- } else {
- Field f;
- f = Color.class.getField(s);
- return (Color) f.get(Color.class);
- }
- } catch (NumberFormatException e) {
- throw new StringUtilException(
- "Error during conversion from string to color", e);
- } catch (SecurityException e) {
- throw new StringUtilException(
- "Error during conversion from string to color", e);
- } catch (NoSuchFieldException e) {
- throw new StringUtilException(
- "Error during conversion from string to color", e);
- } catch (IllegalArgumentException e) {
- throw new StringUtilException(
- "Error during conversion from string to color", e);
- } catch (IllegalAccessException e) {
- throw new StringUtilException(
- "Error during conversion from string to color", e);
- }
- }
-
- public static Date toDate(String s) throws ParseException {
- return DateFormat.getDateInstance().parse(s);
- }
-
- static final protected double[] timeFactors = {1000000, 1000, 60, 60, 24};
-
- static final protected String[] timeUnites = {"ns", "ms", "s", "m", "h",
- "d"};
-
- static public String convertTime(long value) {
- return convert(value, timeFactors, timeUnites);
- }
-
- static public String convertTime(long value,long value2) {
- return convertTime(value2-value);
- }
-
- static final protected double[] memoryFactors = {1024, 1024, 1024, 1024};
-
- static final protected String[] memoryUnites = {"o", "Ko", "Mo", "Go",
- "To"};
-
- static public String convertMemory(long value) {
- return convert(value, memoryFactors, memoryUnites);
- }
-
- static public String convert(long value, double[] factors, String[] unites) {
- long sign = value == 0 ? 1 : value / Math.abs(value);
- int i = 0;
- double tmp = Math.abs(value);
- while (i < factors.length && i < unites.length && tmp > factors[i]) {
- tmp = tmp / factors[i++];
- }
-
- tmp *= sign;
- String result;
- result = MessageFormat.format("{0,number,0.###}{1}", tmp,
- unites[i]);
- return result;
- }
-
- /**
- * V�rifie q'une chaine de caract�re est valid pour les bloc openner closer, ie.
- * <p/>
- * que les blocs d�finit par les deux caract�res s'entrechevauchent pas.
- * <p/>
- * Exemple avec '(' ')' :
- * <p/>
- * (a(b)) est valide, par contre ((aaa))) n'est pas valide
- *
- * @param txt txte a verifier
- * @param opener le caract�re ouvrant
- * @param closer le caract�re fermant
- * @return <code>true</code> is la chaine est valide
- */
- public static boolean checkEnclosure(String txt, final char opener, char closer) {
- if (txt.indexOf(opener) == -1 && txt.indexOf(closer) == -1) {
- // ok pas de block d�tect�s
- return true;
- }
- List<Integer> opens = new ArrayList<Integer>();
- for (int i = 0; i < txt.length(); i++) {
- char c = txt.charAt(i);
- if (c == opener) {
- // add a open block
- opens.add(i);
- continue;
- }
- if (c == closer) {
- if (opens.isEmpty()) {
- // problem no block left
- return false;
- }
- // on supprime le dernier bloc
- opens.remove(opens.size() - 1);
- }
- }
- return opens.isEmpty();
- }
-
- /**
- * Convertir un nom en une constante Java
- *
- * Les seuls caract�res autoris�s sont les alpha num�riques, ains
- * que l'underscore. tous les autres caract�res seront ignor�s.
- *
- * @param name le nom � convertir
- * @return la constante g�n�r�e
- */
- public static String convertToConstantName(String name) {
- StringBuilder sb = new StringBuilder();
- char lastChar=0;
- for (int i = 0, j = name.length(); i < j; i++) {
- char c = name.charAt(i);
- if (Character.isDigit(c)) {
- sb.append(c);
- lastChar = c;
- continue;
- }
- if (!Character.isLetter(c)) {
- if (lastChar != '_') {
- sb.append('_');
- }
- lastChar='_';
- continue;
- }
- if (Character.isUpperCase(c)) {
- if (!Character.isUpperCase(lastChar)&&lastChar!='_') {
- sb.append('_');
- }
- sb.append(c);
- } else {
- sb.append(Character.toUpperCase(c));
- }
- lastChar=c;
- }
- String result = sb.toString();
- // clean tail
- while (!result.isEmpty() && result.endsWith("_")) {
- result = result.substring(0,result.length()-1);
- }
- // clean head
- while (!result.isEmpty() && result.startsWith("_")) {
- result = result.substring(1);
- }
- return result;
- }
-
-}
Deleted: trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtilException.java
===================================================================
--- trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtilException.java 2008-08-04 13:30:38 UTC (rev 965)
+++ trunk/lutinutil-no-i18n/src/main/java/org/codelutin/util/StringUtilException.java 2008-08-04 14:07:30 UTC (rev 966)
@@ -1,24 +0,0 @@
-/*
- * Created on Dec 7, 2004
- *
- * TODO To change the template for this generated file go to
- * Window - Preferences - Java - Code Style - Code Templates
- */
-package org.codelutin.util;
-
-/**
- * @author pineau
- *
- * TODO To change the template for this generated type comment go to
- * Window - Preferences - Java - Code Style - Code Templates
- */
-public class StringUtilException extends RuntimeException {
-
- /** */
- private static final long serialVersionUID = 6148795384335489591L;
-
- public StringUtilException(String message, Exception e) {
- super(message, e);
- }
-
-}
1
0
[Lutinutil-commits] r965 - in trunk/lutinutil/src/main/java/org/codelutin: i18n util
by bpoussin@users.labs.libre-entreprise.org 04 Aug '08
by bpoussin@users.labs.libre-entreprise.org 04 Aug '08
04 Aug '08
Author: bpoussin
Date: 2008-08-04 13:30:38 +0000 (Mon, 04 Aug 2008)
New Revision: 965
Modified:
trunk/lutinutil/src/main/java/org/codelutin/i18n/I18n.java
trunk/lutinutil/src/main/java/org/codelutin/util/ApplicationConfig.java
trunk/lutinutil/src/main/java/org/codelutin/util/HashMapMultiKey.java
trunk/lutinutil/src/main/java/org/codelutin/util/ObjectUtil.java
Log:
Version utilisable de ApplicationConfig
ajout de I18nf pour utiliser String.format
Modified: trunk/lutinutil/src/main/java/org/codelutin/i18n/I18n.java
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/i18n/I18n.java 2008-08-04 11:33:21 UTC (rev 964)
+++ trunk/lutinutil/src/main/java/org/codelutin/i18n/I18n.java 2008-08-04 13:30:38 UTC (rev 965)
@@ -164,8 +164,11 @@
* @param message message formate avec la m?me syntaxe que {@link MessageFormat}
* @param args les parametres pour le message.
* @return la traduction si possible ou la chaine passee en parametre
- * sinon.
+ * sinon.
+ * @deprecated use {@link I18nf#_} that used String.format. When all project are
+ * switched this method use String.format too.
*/
+ @Deprecated
public static String _(String message, Object... args) {
String result = message;
Language language = loader == null ? null : loader.getLanguage();
@@ -198,12 +201,15 @@
/**
* Retourne la chaine passée en argument.
*
- * @param message message formaté avec la même syntaxe que {@link
- * MessageFormat}
- * @param args les paramètres pour le message.
- * @return le message passé en argument mais formatté
- * avec les paramètres
+ * @param message message formate avec la meme syntaxe que {@link
+ * MessageFormat}Message
+ * @param args les parametres pour le message.
+ * @return le message passe en argument mais formatte
+ * avec les parametres
+ * @deprecated use {@link I18nf#n_} that used String.format. When all project are
+ * switched this method use String.format too.
*/
+ @Deprecated
public static String n_(String message, Object... args) {
try {
return MessageFormat.format(message, args);
Modified: trunk/lutinutil/src/main/java/org/codelutin/util/ApplicationConfig.java
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/util/ApplicationConfig.java 2008-08-04 11:33:21 UTC (rev 964)
+++ trunk/lutinutil/src/main/java/org/codelutin/util/ApplicationConfig.java 2008-08-04 13:30:38 UTC (rev 965)
@@ -19,8 +19,14 @@
package org.codelutin.util;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import static org.codelutin.i18n.I18nf._;
import java.io.File;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.Writer;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -29,6 +35,9 @@
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
@@ -37,14 +46,33 @@
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
+import org.apache.commons.beanutils.ConstructorUtils;
+import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
- * Usage:
+ * <h1>To do</h1>
+ *
+ * <ul>
+ * <li> ajout d'annotations sur les methodes
+ * pour precisser plus de chose pour les options (pattern, min/max, alias,
+ * description, ...)
+ * <li> trouver un moyen de document les options et actions pour automatiquement
+ * generer l'aide en ligne. Pour eviter de devoir maintenir une methode
+ * dans lequel est ecrit l'aide en plus des options.
+ * <li> prise en compte du flag {@link #useOnlyAliases}
+ * <li> vu qu'en java on ne peut pas pointer une methode mais seulement une classe
+ * il y a un bout des actions qui sont des chaines (nom de la methode). Il faudrait
+ * faire un plugin maven qui check que l'action existe bien durant la compilation.
+ * Il est simple de le faire a l'execution mais c trop tard :(
+ * </ul>
+ *
+ * <h1>Usage</h1>
* <li> create subclass of ApplicationConfig, where in constructor you call
* addAliases, setConfigFileName, setDefaultActionPackage, setDefaultActionClass, setDefaultActionMethod
* to have properly value.
+ *
* <li> conf = new MonAppConfig();
* <li> conf.parse(args);
* <li> here you can used conf.getOption(key);
@@ -52,30 +80,188 @@
* <li> ...
* <li> conf.doAction(n);
*
+ * <h1>Lecture des fichiers de configuration</h1>
+ *
+ * <p>
+ * La lecture des fichiers de configuration se fait durant l'appel de la methode
+ * {@link #parse} en utilisant la valeur de {@link #getConfigFileName} pour
+ * trouver les fichiers (voir Les options de configuration pour l'ordre de
+ * chargement des fichiers)
+ *
+ * <h1>La sauvegarde</h1>
+ *
+ * <p>
+ * La sauvegarde des options se fait via une des trois methodes disponible
+ *
+ * <ul>
+ * <li> {@link #save(File, boolean)} sauve les donn�es dans le fichier demand�
+ * <li> {@link #saveForSystem} sauvegarde les donnees dans /etc
+ * <li> {@link #saveForUser} sauvegarde les donnees dans $HOME
+ * </ul>
+ *
+ * Lors de l'utilisation de la methode {@link saveForSystem} ou
+ * {@link saveForUser} seul les options lu dans un fichier ou modifier par
+ * programmation ({@link #setOption} seront sauvegardees. Par exemple les
+ * options passees sur la ligne de commande ne seront pas sauvees.
+ *
+ * <h1>Les options de configuration</h1>
+ *
+ * <p>
+ * Cette classe permet de lire les fichiers de configuration, utiliser les
+ * variable d'environnement et de parser la ligne de commande. L'ordre de prise
+ * en compte des informations trouv�es est la suivante (le premier le plus
+ * important).
+ *
+ * <ul>
+ * <li>options ajoutees par programmation: {@link #setOption}(key, value)</li>
+ * <li>ligne de commande</li>
+ * <li>variable d'environnement de la JVM: java -Dkey=value</li>
+ * <li>variable d'environnement; export key=value</li>
+ * <li>fichier de configuration du repertoire courant: $user.dir/filename</li>
+ * <li>fichier de configuration du repertoire home de l'utilisateur: $user.home/.filename</li>
+ * <li>fichier de configuration du repertoire /etc: /etc/filename</li>
+ * <li>fichier de configuration trouve dans le classpath: $CLASSPATH/filename</li>
+ * <li>options ajoutees par programmation: {@link #defaults}.put(key, value)</li>
+ * </ul>
+ *
+ * <p>
+ * Les options sur la ligne de commande sont de la forme:
* <pre>
- * Librairie de parsing de ligne de commande
- o Chaque action est en faite une classe java. Les arguments de la methode (type et nom) donne l'information pour la ligne de commande.
- o MonAction{ maMethod(File file, Class clazz, String str, int i) {//implantation} } est appelable par MonAction.maMethod clazz=org.codelutin.util.Truc file= tmp/test i=10 str=coucou. Lors de la configuration du parseur on donne un package par defaut, une classe par defaut et une methode par defaut pour la recherche de la methode a appele.
- + package.Class.method: aucun element par defaut n'est utilise
- + Class.method: le package par defaut est utilise pour retrouver la classe
- + method: le package et la classe par defaut sont utilises pour retrouver la methode
- + Class: Le package et la methode par defaut sont utilises pour retourver la classe et la methode a appeler
- o On peut alors soit avoir une classe par action, une classe pour toute les actions, un mixte des deux. Si la methode n'est pas n'est pas static l'objet la contenant est instancier (IoC ? picocontainer ?)
- o Pour les Options de configuration de l'application, de la meme facon on configure une classe par defaut ou les options seront stockee. Cette classe heritera d'une classe generic qui elle meme etendra HashMap, pour implanter les get/set si on le souhaite, sinon les methodes put/get de la hashmap seront utilises. L'utilisateur aura les methodes getString, getInt, getFile, getClass, ... pour recuperer de facon type les options
- o l'ordre de recherche d'une option est: depuis les valeurs par defaut, le fichier /etc/prop, le fichier $home/prop, le fichier $CUR/prop, env, line. Pour cela stockage dans N hashmap chainee.
- + format du fichier key=value
- + format de env key=value
- + format de line. option key=value, ou si on a une methode set specifique key value (automatiquement la methode setKey est recherche grace au package par defaut et classe par defaut
- o ordre d'execution: Parametrage de la lib, utilisation de la lib avec les arguments du programme, lecture des options de la ligne de commande(ce qui peut modifier le nom du fichier d'option), lecture des options de env(ce qui peut modifier le nom du fichier d'option), lecture des options dans les fichiers. Execution des actions dans l'ordre ou on les trouve sur la ligne de commande.
- o Amelioration: Il sera possible de mettre des annotations sur les methodes pour precisser plus de chose pour les options (pattern, min/max, alias, description, ...)
- o Les arguments non parser se retrouve dans une liste de chaine
+ * --option key value
+ * --monOption key value1 value2
* </pre>
*
+ * <ul>
+ * <li>--option key value: est la syntaxe par defaut
+ * <li>--monOption key value1 value2: est la syntaxe si vous avez ajouter une
+ * methode setMonOption(key, value1, value2) sur votre classe de configuration
+ * qui herite de {@link ApplicationConfig}. Dans ce cas vous pouvez mettre les
+ * arguments que vous souhaitez du moment qu'ils soient convertibles de la
+ * representation String vers le type que vous avez mis.
+ * </ul>
+ *
+ * <h1>Les actions</h1>
+ *
+ * Les actions ne peuvent etre que sur la ligne de commande. Ils sont de la
+ * forme:
+ * <pre>
+ * --le.package.LaClass#laMethode arg1 arg2 arg3 ... argN
+ * </pre>
+ *
+ * <p>
+ * Une action est donc defini par le chemin complet vers la methode qui traitera
+ * l'action. Cette methode peut-etre une methode static ou non. Si la methode
+ * n'est pas static lors de l'instanciation de l'objet on essaie de passer en
+ * parametre du constructeur la classe de configuration utilisee pour permettre
+ * a l'action d'avoir a sa disposition les options de configuration. Si aucun
+ * constructeur avec comme seul parametre une classe heritant de
+ * {@link ApplicationConfig} n'existe alors le constructeur par defaut est
+ * utilise (il doit etre accessible). Toutes methodes d'actions faisant
+ * parties d'un meme objet utiliseront la meme instance de cette objet lors
+ * de leur execution.
+ *
+ * <p>
+ * Si la methode utilise les arguments variants alors tous les arguments
+ * jusqu'au prochain -- ou la fin de la ligne de commande sont utilises. Sinon
+ * Le nombre exact d'argument necessaire a la methode sont utilises.
+ *
+ * <p>
+ * Les arguments sont automatiquement converti dans le bon type reclame par la
+ * methode.
+ *
+ * <p>
+ * Si l'on veut des arguments optionnels le seul moyen actuellement est
+ * d'utiliser une methode avec des arguments variants
+ *
+ * <p> Les actions ne sont pas execute mais seulement parsees. Pour les executer
+ * il faut utiilser la methode {@link #doAction} qui prend en argument un numero
+ * de 'step'. Par defaut toutes les actions sont de niveau 0 et sont executee
+ * dans l'ordre d'apparition sur la ligne de commande. Si l'on souhaite
+ * distinguer les actions il est possible d'utiliser l'annotation
+ * {@link ApplicationConfig.Action.Step} sur la methode qui fera l'action en
+ * precisant une autre valeur que 0.
+ *
+ * <pre>
+ * doAction(0);
+ * ... do something ...
+ * doAction(1);
+ * </pre>
+ *
+ * <p>
+ * dans cette exemple on fait un traitement entre l'execution des actions
+ * de niveau 0 et les actions de niveau 1.
+ *
+ * <h1>Les arguments non parses</h1>
+ *
+ * <p>
+ * Tout ce qui n'est pas option ou action est considere comme non parse et peut
+ * etre recupere par la methode {@link #getUnparsed}. Si l'on souhaite forcer
+ * la fin du parsing de la ligne de commande il est possible de mettre --.
+ * Par exemple:
+ * <pre>
+ * monProg "mon arg" --option k1 v1 -- --option k2 v2 -- autre
+ * </pre>
+ *
+ * <p>
+ * Dans cet exemple seule la premiere option sera considere comme une option.
+ * On retrouvera dans unparsed: "mon arg", "--option", "k2", "v2", "--", "autre"
+ *
+ * <h1>Les alias</h1>
+ *
+ * On voit qu'aussi bien pour les actions que pour les options, le nom de la
+ * methode doit etre utilise. Pour eviter ceci il est possible de definir
+ * des alias ce qui permet de creer des options courtes par exemple. Pour cela,
+ * on utilise la methode {@link #addAlias}.
+ *
+ * <pre>
+ * addAlias("-v", "--option", "verbose", "true");
+ * addAlias("-o", "--option", "outputfile");
+ * addAlias("-i", "--mon.package.MaClass#MaMethode", "import");
+ * </pre>
+ *
+ * <p>
+ * En faite avant le parsing de la ligne de commande tous les alias trouves sont
+ * automatiquement remplacer par leur correspondance. Il est donc possible
+ * d'utiliser ce mecanisme pour autre chose par exemple:
+ *
+ * <pre>
+ * addAlias("cl", "Code Lutin");
+ * addAlias("bp", "Benjamin POUSSIN);
+ * </pre>
+ *
+ * <p>
+ * Dans le premier exemple on simplifie une option de flags l'option -v n'attend
+ * donc plus d'argument. Dans le second exemple on simplifie une option qui
+ * attend encore un argment de type File. Enfin dans le troisieme exemple
+ * on simplifie la syntaxe d'une action et on force le premier argument de
+ * l'action a etre "import".
+ *
+ * <h1>Conversion de type</h1>
+ * Pour la conversion de type nous utilisons common-beans. Les types supporte
+ * sont:
+
+ * <ul>
+ * <li> les primitif (byte, short, int, long, float, double, char, boolean)
+ * <li> String
+ * <li> File
+ * <li> URL
+ * <li> Class
+ * <li> SqlDate
+ * <li> SqlTime
+ * <li> SqlTimestamps
+ * <li> les tableaux d'un type primitif ou String. Chaque element doit etre
+ * separe par une virgule
+ * </ul>
+*
+ * Pour suporter d'autre type, il vous suffit d'enregistrer de nouveau
+ * converter dans commons-beans
+
* @author poussin
* @version $Revision$
- *
- * Last update: $Date$
- * by : $Author$
+ * @since 0.30
+ *
+ * Last update $Date$
+ * by $Author$
*/
public class ApplicationConfig {
@@ -91,6 +277,11 @@
protected boolean useOnlyAliases = false;
protected Map<String, List<String>> aliases = new HashMap<String, List<String>>();
+
+ /** file /etc/[filename] */
+ String systemPath = File.separator + "etc" + File.separator;
+ /** file $user.home/.[filename] */
+ String userPath = getUserHome() + File.separator + ".";
protected Properties defaults = new Properties();
protected Properties classpath = new Properties(defaults);
@@ -102,6 +293,10 @@
protected Properties line = new Properties(jvm);
protected Properties options = new Properties(line);
+ protected Map<String, CacheItem> cacheOption = new HashMap<String, ApplicationConfig.CacheItem>();
+ protected Map<Class, Object> cacheAction = new HashMap<Class, Object>();
+
+
protected List<String> unparsed = new ArrayList<String>();
protected Map<Integer, List<Action>> actions = new HashMap<Integer, List<Action>>();
@@ -126,16 +321,106 @@
this.params = params;
}
- public void doAction() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+ public void doAction() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
ObjectUtil.call(o, m, params);
}
}
+ /**
+ * Item used for cacheOption
+ * @param T
+ */
+ static protected class CacheItem<T> {
+ /** typed option value */
+ public T item;
+ /** hash of string representation */
+ public int hash;
+
+ public CacheItem(T item, int hash) {
+ this.item = item;
+ this.hash = hash;
+ }
+
+ }
+
public ApplicationConfig() {
- defaults.setProperty(CONFIG_FILE_NAME, this.getClass().getSimpleName());
+ setConfigFileName(this.getClass().getSimpleName());
}
-
+
+ static public String getUserHome() {
+ String result = System.getProperty("user.home");
+ return result;
+ }
+
+ public String getUsername() {
+ String result = getOption("user.name");
+ return result;
+ }
+
/**
+ * Used to put default configuration option in config option. Those options
+ * are used as fallback value.
+ * @param key
+ * @param value
+ */
+ protected void setDefaultOption(String key, String value) {
+ defaults.setProperty(key, value);
+ }
+
+ /**
+ * Save configuration, in specified file
+ * @param logOnError if true not throw exception but log error
+ * @param file file where config will be writen
+ * @param forceAll if true save all config option
+ * (with defaults, classpath, env, command line)
+ */
+ public void save(File file, boolean forceAll) throws IOException {
+ Properties prop = new Properties();
+ if (forceAll) {
+ prop.putAll(defaults);
+ prop.putAll(classpath);
+ }
+ prop.putAll(etcfile);
+ prop.putAll(homefile);
+ prop.putAll(curfile);
+ if (forceAll) {
+ prop.putAll(jvm);
+ prop.putAll(env);
+ prop.putAll(line);
+ }
+ prop.putAll(options);
+
+ Writer writer = new FileWriter(file);
+ prop.store(writer, "Last saved " + new java.util.Date());
+ }
+
+ /**
+ * Save configuration, in system directory (/etc/) using the
+ * {@link #getConfigFileName}. Default, env and commande line note saved
+ */
+ public void saveForSystem() {
+ File file = new File(systemPath + getConfigFileName());
+ try {
+ save(file, false);
+ } catch (IOException eee) {
+ log.warn(_("Can't save config in file %s", file), eee);
+ }
+ }
+
+ /**
+ * Save configuration, in user home directory using the
+ * {@link #getConfigFileName}. Default, env and commande line note saved
+ */
+ public void saveForUser() {
+ File file = new File(userPath + getConfigFileName());
+ try {
+ save(file, false);
+ } catch (IOException eee) {
+ log.warn(_("Can't save config in file %s", file), eee);
+ }
+ }
+
+ /**
* Return list of unparsed command line argument
* @return list of unparsed arguments
*/
@@ -159,7 +444,7 @@
}
}
- public void doAction(int step) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+ public void doAction(int step) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
List<Action> list = actions.get(step);
if (list != null) {
for (Action a : list) {
@@ -186,12 +471,23 @@
}
/**
+ * Add alias for action. This method put just -- front the actionMethod and
+ * call {@link addAlias}
+ * @param alias
+ * @param actionMethod must be fully qualified method path: package.Class.method
+ */
+ public void addActionAlias(String alias, String actionMethod) {
+ addAlias(alias, "--" + actionMethod);
+ }
+
+ /**
* Set name of file where options are read (in /etc, $HOME, $CURDIR)
+ * This set used {@link setDefaultOption}
* @param name file name
*/
public void setConfigFileName(String name) {
// put in defaults, this permit user to overwrite it on commande line
- defaults.setProperty(CONFIG_FILE_NAME, name);
+ setDefaultOption(CONFIG_FILE_NAME, name);
}
public String getConfigFileName() {
@@ -217,8 +513,126 @@
String value = options.getProperty(key);
return value;
}
+
+ /**
+ * get option value as typed value
+ * @param clazz type of object wanted as return type
+ * @param key
+ * @return typed value
+ */
+ public <T> T getOption(Class<T> clazz, String key) {
+ T result = null;
+ String cacheKey = key + "-" + clazz.getName();
+
+ String value = options.getProperty(key);
+ int hash = 0;
+ if (value != null) {
+ hash = value.hashCode();
+ }
+ CacheItem<T> cacheItem = cacheOption.get(cacheKey);
+ // compute value if value don't exist in cacheOption or
+ // if it's modified since last computation
+ if (cacheItem == null || cacheItem.hash != hash) {
+ result = (T) ConvertUtils.convert(value, clazz);
+ cacheItem = new CacheItem<T>(result, hash);
+ cacheOption.put(cacheKey, cacheItem);
+ }
+
+ return result;
+ }
+
+ /**
+ * get option value as typed value
+ * @param key
+ * @return typed value
+ */
+ public File getOptionAsFile(String key) {
+ File result = getOption(File.class, key);
+ result = result.getAbsoluteFile();
+ return result;
+ }
/**
+ * get option value as typed value
+ * @param key
+ * @return typed value
+ */
+ public URL getOptionAsURL(String key) {
+ URL result = getOption(URL.class, key);
+ return result;
+ }
+
+ /**
+ * get option value as typed value
+ * @param key
+ * @return typed value
+ */
+ public Class getOptionAsClass(String key) {
+ Class result = getOption(Class.class, key);
+ return result;
+ }
+
+ /**
+ * get option value as typed value
+ * @param key
+ * @return typed value
+ */
+ public Date getOptionAsDate(String key) {
+ Date result = getOption(Date.class, key);
+ return result;
+ }
+
+ /**
+ * get option value as typed value
+ * @param key
+ * @return typed value
+ */
+ public Time getOptionAsTime(String key) {
+ Time result = getOption(Time.class, key);
+ return result;
+ }
+
+ /**
+ * get option value as typed value
+ * @param key
+ * @return typed value
+ */
+ public Timestamp getOptionAsTimestamp(String key) {
+ Timestamp result = getOption(Timestamp.class, key);
+ return result;
+ }
+
+ /**
+ * get option value as typed value
+ * @param key
+ * @return typed value
+ */
+ public int getOptionAsInt(String key) {
+ Integer result = getOption(Integer.class, key);
+ return result;
+ }
+
+ /**
+ * get option value as typed value
+ * @param key
+ * @return typed value
+ */
+ public double getOptionAsDouble(String key) {
+ Double result = getOption(Double.class, key);
+ return result;
+ }
+
+ /**
+ * get option value as typed value
+ * @param key
+ * @return typed value
+ */
+ public boolean getOptionAsBoolean(String key) {
+ Boolean result = getOption(Boolean.class, key);
+ return result;
+ }
+
+ /**
* Get all set method on this object or super object
* @return map with method name without set and in lower case as key, and
* method as value
@@ -238,22 +652,35 @@
}
/**
- * Take required argument for method in args and call this method on target
- * object. Argument used is removed from args
- * @param target object where method is
+ * Take required argument for method in args. Argument used is removed from
+ * args. If method has varArgs, we take all argument to next '--'
* @param m the method to call
* @param args iterator with many argument (equals or more than necessary
* @throws java.lang.Exception if call failed
*/
protected String[] getParams(Method m, ListIterator<String> args) {
- int paramLenght = m.getParameterTypes().length;
- String[] result = new String[paramLenght];
- for (int i=0; i < paramLenght; i++) {
- String p = args.next();
- args.remove(); // remove this arg because is used now
- result[i] = p;
+ List<String> result = new ArrayList<String>();
+ if (m.isVarArgs()) {
+ while (args.hasNext()) {
+ String p = args.next();
+ if (p.startsWith("--")) {
+ // stop search
+ args.previous();
+ break;
+ } else {
+ result.add(p);
+ args.remove();
+ }
+ }
+ } else {
+ int paramLenght = m.getParameterTypes().length;
+ for (int i = 0; i < paramLenght; i++) {
+ String p = args.next();
+ args.remove(); // remove this arg because is used now
+ result.add(p);
+ }
}
- return result;
+ return result.toArray(new String[result.size()]);
}
/**
@@ -263,7 +690,7 @@
* @param params
* @return
*/
- protected Action createAction(String name, ListIterator<String> args) throws ArgumentsParserException, InstantiationException, IllegalAccessException {
+ protected Action createAction(String name, ListIterator<String> args) throws ArgumentsParserException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Action result = null;
Class clazz;
@@ -300,10 +727,22 @@
if (method != null) {
args.remove(); // remove option from command line, because is used now
- Object o = null;
- if (!Modifier.isStatic(method.getModifiers())) {
- o = clazz.newInstance();
+
+ // creation de l'object sur lequel on fera l'appel
+ Object o = cacheAction.get(clazz);
+ if (o == null && !Modifier.isStatic(method.getModifiers())) {
+ try {
+ o = ConstructorUtils.invokeConstructor(clazz, this);
+ } catch (NoSuchMethodException eee) {
+ log.debug(String.format(
+ "Use default constructor, because no constructor with Config parameter on class %s",
+ clazz.getName()));
+ o = clazz.newInstance();
+ }
+ cacheAction.put(clazz, o);
}
+
+ // recherche du step de l'action
int step = 0;
Action.Step annotation = method.getAnnotation(Action.Step.class);
if (annotation != null) {
@@ -339,6 +778,10 @@
// first parse option
for (ListIterator<String> i = arguments.listIterator(); i.hasNext();) {
String arg = i.next();
+ if (arg.equals("--")) {
+ // stop parsing
+ break;
+ }
if (arg.startsWith("--")) {
String optionName = arg.substring(2);
if (methods.containsKey(optionName)) {
@@ -369,23 +812,20 @@
log.info("Chargement du fichier de config: " + inClasspath);
classpath.load(inClasspath.openStream());
}
-
- // file /etc
- File etcConfig = new File(File.separator + "etc" + File.separator + filename);
+
+ File etcConfig = new File(systemPath + filename);
if (etcConfig.exists()) {
log.info("Chargement du fichier de config: " + etcConfig);
etcfile.load(etcConfig.toURI().toURL().openStream());
}
- // file /home
- String home = System.getProperty("user.home");
- File homeConfig = new File(home + File.separator + filename);
+ File homeConfig = new File(userPath + filename);
if (homeConfig.exists()) {
log.info("Chargement du fichier de config: " + homeConfig);
homefile.load(homeConfig.toURI().toURL().openStream());
}
- // file $CURDIR
+ // file $CURDIR/filename
File config = new File(filename);
if (config.exists()) {
log.info("Chargement du fichier de config: " + config);
@@ -397,6 +837,10 @@
//
for (ListIterator<String> i = arguments.listIterator(); i.hasNext();) {
String arg = i.next();
+ if (arg.equals("--")) {
+ // stop parsing
+ break;
+ }
if (arg.startsWith("--")) {
String optionName = arg.substring(2);
Action action = createAction(optionName, i);
@@ -407,6 +851,7 @@
//
// not used args added to unparsed
//
+ arguments.remove("--");
unparsed.addAll(arguments);
} catch (Exception eee) {
Modified: trunk/lutinutil/src/main/java/org/codelutin/util/HashMapMultiKey.java
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/util/HashMapMultiKey.java 2008-08-04 11:33:21 UTC (rev 964)
+++ trunk/lutinutil/src/main/java/org/codelutin/util/HashMapMultiKey.java 2008-08-04 13:30:38 UTC (rev 965)
@@ -51,7 +51,11 @@
* complet des References. iterator(), entrySet(), ... peuvent ne pas
* fonctionner comme il faut, c-a-d qu'il retourne les references et non
* les objets. Mais les methodes simples fonctionnent: put, remove, get, ...
+ *
+ * @deprecated Cette classe semble avoir des memory leaks. Mieux vaut ne pas
+ * l'utiliser ou alors il faudrait refaire l'implantation complete de facon propre
*/
+@Deprecated
public class HashMapMultiKey extends HashMap<Object, Object> { // HashMapMultiKey
/** */
@@ -246,6 +250,7 @@
* @throws IllegalArgumentException si le parametre key n'est pas
* une collection d'objet.
*/
+ @Override
public Object put(Object key, Object value){
if (key == null) {
if(log.isWarnEnabled()) {log.warn("key is null");}
@@ -272,11 +277,13 @@
}
+ @Override
public boolean containsValue(Object value) {
cleanQueue();
return valueToKey.containsKey(value);
}
+ @Override
public Object get(Object key) {
// a chaque fois que l'on prend, on nettoie un peu avant
cleanQueue();
@@ -305,6 +312,7 @@
* valeur associ�e a cette cle. Si un objet a ete passe, retourne la liste
* des cles qui contient cet objet et qui ont �t� supprim�es.
*/
+ @Override
public Object remove(Object key){
// on nettoie un peu avant
cleanQueue();
@@ -388,6 +396,7 @@
public Iterator<Object> iterator(){
return keys.iterator();
}
+ @Override
public boolean equals(Object o){
if (o != null && o instanceof Reference) {
// on inverse l'egalite pour que la Key soit egal a la ref
@@ -398,6 +407,7 @@
keys.equals(((Key)o).keys);
}
}
+ @Override
public int hashCode(){
int result = 0;
for(int i=0; i<keys.size(); i++){
@@ -408,6 +418,7 @@
}
return result;
}
+ @Override
public String toString(){
StringBuffer result = new StringBuffer("[");
String v ="";
Modified: trunk/lutinutil/src/main/java/org/codelutin/util/ObjectUtil.java
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/util/ObjectUtil.java 2008-08-04 11:33:21 UTC (rev 964)
+++ trunk/lutinutil/src/main/java/org/codelutin/util/ObjectUtil.java 2008-08-04 13:30:38 UTC (rev 965)
@@ -31,16 +31,26 @@
package org.codelutin.util;
+import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
+import static org.codelutin.i18n.I18nf._;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
public class ObjectUtil { // ObjectUtil
+ /** to use log facility, just put in your code: log.info(\"...\"); */
+ static private Log log = LogFactory.getLog(ObjectUtil.class);
+
/**
* ObjectUtil constructor
* private because of this class is a static class : nobody
@@ -95,6 +105,20 @@
return o;
}
+ static protected Object convert(String v, Class clazz) {
+ Object t = ConvertUtils.convert(v, clazz);
+
+ if (t != null &&
+ !String.class.getName().equals(clazz.getName()) &&
+ String.class.getName().equals(t.getClass().getName())) {
+ throw new IllegalArgumentException(String.format(
+ "Can convert argument to correct type. %s can't be" +
+ " converted from String to %s conversion is done to %s",
+ v, clazz.getName(), t.getClass().getName()));
+ }
+ return t;
+ }
+
/**
* Call method m with params as String. Each param is converted to required type for
* method with beanutils converter
@@ -104,27 +128,43 @@
* @return returned method's value
*/
public static Object call(Object o, Method m, String ... params)
- throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+ throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
Class[] types = m.getParameterTypes();
- if (params.length != types.length) {
+ if (!m.isVarArgs() && params.length != types.length) {
throw new IllegalArgumentException(String.format(
"Bad number params we have %1$s parameters and waiting %2$s.",
params.length, types.length));
}
+
+ int last = types.length;
+ if (m.isVarArgs()) {
+ // on traite le dernier differement
+ last--;
+ }
+
Object[] parameters = new Object[types.length];
- for (int i=0; i<types.length; i++) {
+ for (int i=0; i<last; i++) {
+ String v = params[i];
Class clazz = types[i];
- String v = params[i];
- parameters[i] = ConvertUtils.convert(v, clazz);
- if (parameters[i] != null &&
- !String.class.getName().equals(clazz.getName()) &&
- String.class.getName().equals(parameters[i].getClass().getName()) ) {
- throw new IllegalArgumentException(String.format(
- "Can convert argument to correct type. %s can't be" +
- " converted from String to %s conversion is done to %s",
- v, clazz.getName(), parameters[i].getClass().getName()));
+ Object t = convert(v, clazz);
+ parameters[i] = t;
+ }
+
+ if (m.isVarArgs()) {
+ Class clazz = types[last]; // get var args type
+ clazz = clazz.getComponentType(); // get array component type
+ List tmp = new ArrayList();
+ for (int i=last; i<params.length; i++) {
+ String v = params[i];
+ Object t = convert(v, clazz);
+ tmp.add(t);
}
+ parameters[last] = tmp.toArray((Object[])Array.newInstance(clazz, tmp.size()));
}
+
+ if (log.isDebugEnabled()) {
+ log.debug(_("Invoke %s with %s", m, Arrays.toString(parameters)));
+ }
Object result = m.invoke(o, parameters);
return result;
}
1
0
[Lutinutil-commits] r964 - trunk/maven-i18n-plugin/src/main/resources
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
04 Aug '08
Author: tchemit
Date: 2008-08-04 11:33:21 +0000 (Mon, 04 Aug 2008)
New Revision: 964
Modified:
trunk/maven-i18n-plugin/src/main/resources/jaxx.rules
trunk/maven-i18n-plugin/src/main/resources/swixat.rules
Log:
UTF8
Modified: trunk/maven-i18n-plugin/src/main/resources/jaxx.rules
===================================================================
--- trunk/maven-i18n-plugin/src/main/resources/jaxx.rules 2008-08-04 11:32:55 UTC (rev 963)
+++ trunk/maven-i18n-plugin/src/main/resources/jaxx.rules 2008-08-04 11:33:21 UTC (rev 964)
@@ -1,4 +1,4 @@
-# R�gles pour JAXX
+# Règles pour JAXX
//JDialog/@title
//JFrame/@title
Modified: trunk/maven-i18n-plugin/src/main/resources/swixat.rules
===================================================================
--- trunk/maven-i18n-plugin/src/main/resources/swixat.rules 2008-08-04 11:32:55 UTC (rev 963)
+++ trunk/maven-i18n-plugin/src/main/resources/swixat.rules 2008-08-04 11:33:21 UTC (rev 964)
@@ -1,4 +1,4 @@
-# R�gles pour swixat
+# Règles pour swixat
//Frame/@title
//frame/@title
1
0
[Lutinutil-commits] r963 - in trunk/maven-i18n-plugin: . src/main/java/org/codelutin/i18n/plugin src/main/java/org/codelutin/i18n/plugin/core src/main/java/org/codelutin/i18n/plugin/extension src/main/java/org/codelutin/i18n/plugin/ui
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
04 Aug '08
Author: tchemit
Date: 2008-08-04 11:32:55 +0000 (Mon, 04 Aug 2008)
New Revision: 963
Added:
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/PluginHelper.java
Modified:
trunk/maven-i18n-plugin/pom.xml
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nParser.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nPlugin.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Generate.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Getter.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Parser.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserEvent.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserException.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJava.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaActionConfig.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaTabConfig.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJaxx.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserSwixat.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserXml.java
trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/ui/KeysModifier.java
Log:
new version 0-4
project is now in UTF-8
refactor some code
now only modified files are parsed (to use old mode just add a -Di18n.scrictMode=true).
beware : this new mode forces them to always use the plugin before a compile phase
remove all code from lutinutil
Modified: trunk/maven-i18n-plugin/pom.xml
===================================================================
--- trunk/maven-i18n-plugin/pom.xml 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/pom.xml 2008-08-04 11:32:55 UTC (rev 963)
@@ -31,12 +31,12 @@
<scope>compile</scope>
</dependency>
- <dependency>
+ <!--dependency>
<groupId>org.codelutin</groupId>
<artifactId>lutinutil-no-i18n</artifactId>
<version>0.30-SNAPSHOT</version>
<scope>compile</scope>
- </dependency>
+ </dependency-->
<dependency>
<groupId>lutinlib</groupId>
@@ -64,7 +64,7 @@
<!-- *** Project Information ************************************* -->
<!-- ************************************************************* -->
<name>Plugin maven pour lutini18n</name>
- <version>0.3-SNAPSHOT</version>
+ <version>0.4</version>
<description>
Plugin pour maven 2 pour la génération des bundles pour l'internationnalisation des applications java fait par
lutinutil-i18n
@@ -142,7 +142,7 @@
<!-- compile with ? -->
<maven.compile.source>1.6</maven.compile.source>
<maven.compile.target>1.6</maven.compile.target>
- <maven.compile.encoding>ISO-8859-15</maven.compile.encoding>
+ <maven.compile.encoding>UTF-8</maven.compile.encoding>
<!-- Lists URL -->
<labs.lists>
Added: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/PluginHelper.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/PluginHelper.java (rev 0)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/PluginHelper.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -0,0 +1,275 @@
+/**
+ * # #% Copyright (C) 2008 Code Lutin, Tony Chemit
+ * This program is free software; you
+ * can redistribute it and/or modify it under the terms of the GNU General
+ * Public License as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. This program is
+ * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE. See the GNU General Public License for more details. You
+ * should have received a copy of the GNU General Public License along with this
+ * program; if not, write to the Free Software Foundation, Inc., 59 Temple Place
+ * - Suite 330, Boston, MA 02111-1307, USA.
+ * # #%
+ */
+package org.codelutin.i18n.plugin;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.nio.channels.FileChannel;
+import java.text.MessageFormat;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Properties;
+import java.util.Vector;
+
+/**
+ * Une classe pour mutualiser toutes les méthodes utiles dans ce plugin.
+ * <p/>
+ * Note : On a dupliqué ici du code de la librairie lutinutil, pour casser la dépendance ver ce projet qui utilise ce plugin
+ * et donc introduit un cycle dans le graphe des dépendances, ce qui n'est pas souhaitable.
+ *
+ * @author chemit
+ */
+public class PluginHelper {
+
+ /**
+ * @param root le repertoire ou sont stockes les fichiers i18n
+ * @param artifactId le nom de l'artifact
+ * @param bundle le nom du bundle
+ * @param create <code>true</code> pour creer le fichier si non present
+ * @return le fichier i18n
+ * @throws java.io.IOException si probleme lors de la creation du fichier
+ */
+ public static File getI18nFile(File root, String artifactId, String bundle, boolean create) throws IOException {
+ File file = new File(root.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ if (create && !file.exists()) {
+ if (!file.exists()) {
+ file.getParentFile().mkdirs();
+ }
+ file.createNewFile();
+ }
+ return file;
+ }
+
+ /**
+ * @param root le repertoire ou sont stockes les fichiers getter
+ * @param getter le nom du getter
+ * @param create <code>true</code> pour creer le fichier si non present
+ * @return le fichier i18n
+ * @throws java.io.IOException si probleme lors de la creation du fichier
+ */
+ public static File getGetterFile(File root, String getter, boolean create) throws IOException {
+ File file = new File(root.getAbsolutePath() + File.separatorChar + getter);
+ if (create && !file.exists()) {
+ if (!file.exists()) {
+ file.getParentFile().mkdirs();
+ }
+ file.createNewFile();
+ }
+ return file;
+ }
+
+ /**
+ * @param root le repertoire ou sont stockes les fichiers getter
+ * @param getter le nom du getter
+ * @return le fichier i18n
+ */
+ public static File getGetterFileBackup(File root, String getter) {
+ return new File(root.getAbsolutePath() + File.separatorChar + getter + '~');
+ }
+
+ /**
+ * @param root le reertoire ou sont stockes les fichiers i18n
+ * @param artifactId le nom de l'artifact
+ * @param bundle le nom du bundle
+ * @return le fichier i18n de backup
+ */
+ public static File getI18nFileBackup(File root, String artifactId, String bundle) {
+ return new File(root.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties~");
+ }
+
+ /**
+ * Permet de copier le fichier source vers le fichier cible.
+ *
+ * @param source le fichier source
+ * @param target le fichier cible
+ * @throws java.io.IOException Erreur de copie
+ */
+ public static void copy(File source, File target) throws IOException {
+ target.getParentFile().mkdirs();
+ FileChannel sourceChannel = new FileInputStream(source).getChannel();
+ FileChannel targetChannel = new FileOutputStream(target).getChannel();
+ sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
+ // or
+ // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
+ sourceChannel.close();
+ targetChannel.close();
+ }
+
+ /**
+ * Permet de lire un fichier et de retourner sont contenu sous forme d'une
+ * chaine de carateres
+ *
+ * @param file le fichier a lire
+ * @param encoding encoding to read file
+ * @return the content of the file
+ * @throws IOException if IO pb
+ */
+ static public String readAsString(File file, String encoding) throws IOException {
+ StringBuffer result = new StringBuffer();
+ char[] cbuf = new char[2000];
+ FileInputStream inf = new FileInputStream(file);
+ BufferedReader in = new BufferedReader(new InputStreamReader(inf, encoding));
+ int nb = in.read(cbuf);
+ while (nb != -1) {
+ result.append(cbuf, 0, nb);
+ nb = in.read(cbuf);
+ }
+ in.close();
+ return result.toString();
+ }
+
+ static public void writeString(File file, String content, String encoding) throws IOException {
+ file.getParentFile().mkdirs();
+ BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
+ out.write(content);
+ out.close();
+ }
+
+ /**
+ * Permet de convertir une liste non typee, en une liste typee.
+ * <p/>
+ * La liste en entree en juste bien castee.
+ * <p/>
+ * On effectue une verification sur le typage des elements de la liste.
+ * <p/>
+ * Note : <b>Aucune liste n'est creee, ni recopiee</b>
+ *
+ * @param list la liste a convertir
+ * @param type le type des elements de la liste
+ * @return la liste typee
+ * @throws IllegalArgumentException si un element de la liste en entree n'est
+ * pas en adequation avec le type voulue.
+ */
+ @SuppressWarnings({"unchecked"})
+ static public <O> List<O> toGenericList(List list, Class<O> type) throws IllegalArgumentException {
+ if (list.isEmpty()) {
+ return list;
+ }
+ for (Object o : list) {
+ if (!(type.isAssignableFrom(o.getClass()))) {
+ throw new IllegalArgumentException("can not cast List with object of type " + o.getClass() + " to " + type + " type!");
+ }
+ }
+ return list;
+ }
+
+
+ static final protected double[] timeFactors = {1000000, 1000, 60, 60, 24};
+
+ static final protected String[] timeUnites = {"ns", "ms", "s", "m", "h",
+ "d"};
+
+ static public String convertTime(long value) {
+ return convert(value, timeFactors, timeUnites);
+ }
+
+ static public String convertTime(long value, long value2) {
+ return convertTime(value2 - value);
+ }
+
+ static public String convert(long value, double[] factors, String[] unites) {
+ long sign = value == 0 ? 1 : value / Math.abs(value);
+ int i = 0;
+ double tmp = Math.abs(value);
+ while (i < factors.length && i < unites.length && tmp > factors[i]) {
+ tmp = tmp / factors[i++];
+ }
+
+ tmp *= sign;
+ String result;
+ result = MessageFormat.format("{0,number,0.###}{1}", tmp,
+ unites[i]);
+ return result;
+ }
+
+ /**
+ * Permet d'avoir les fichiers de proprietes tries.
+ *
+ * @author julien
+ */
+ public static class I18nProperties extends Properties {
+
+ private static final long serialVersionUID = -1147150444452577558L;
+
+
+ public I18nProperties() {
+ super();
+ }
+
+ public I18nProperties(Properties defaults) {
+ super(defaults);
+ }
+
+ @Override
+ public synchronized Enumeration<Object> keys() {
+ List<Object> objects = Collections.list(super.keys());
+ Vector<Object> result;
+ try {
+ // Attention, si les clef ne sont pas des string, ca ne marchera pas
+ List<String> list = toGenericList(objects, String.class);
+ Collections.sort(list);
+ result = new Vector<Object>(list);
+ } catch (IllegalArgumentException e) {
+ // keys are not string !!!
+ // can not sort keys
+ result = new Vector<Object>(objects);
+ }
+ return result.elements();
+ }
+
+ public void store(File bundleOut) throws IOException {
+ super.store(new PropertiesDateRemoveFilterStream(new FileOutputStream(bundleOut)), null);
+ }
+ }
+
+ public static class PropertiesDateRemoveFilterStream extends FilterOutputStream {
+
+ private boolean firstLineOver;
+ char endChar;
+
+ public PropertiesDateRemoveFilterStream(OutputStream out) {
+ super(out);
+ firstLineOver = false;
+ String lineSeparator = java.security.AccessController
+ .doPrivileged(new sun.security.action.GetPropertyAction(
+ "line.separator"));
+ endChar = lineSeparator.charAt(lineSeparator.length() - 1);
+ }
+
+ @Override
+ public void write(int b) throws IOException {
+ if (!firstLineOver) {
+ char c = (char) b;
+ if (c == endChar) {
+ firstLineOver = true;
+ }
+ } else {
+ out.write(b);
+ }
+ }
+
+ }
+
+
+}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nParser.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nParser.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nParser.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -20,11 +20,15 @@
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
+import org.codelutin.i18n.plugin.PluginHelper;
import org.codelutin.i18n.plugin.ui.KeysModifier;
-import org.codelutin.util.FileUtil;
+import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -36,6 +40,7 @@
* @author tony
*/
public abstract class AbstractI18nParser extends AbstractI18nPlugin implements Parser {
+
/** @return the outGetter to use for the instance (java.getter,...) */
protected abstract String getOutGetter();
@@ -82,13 +87,23 @@
oldParser = new Properties();
oldLanguage = new Properties();
out.mkdirs();
- // �v�nements
+ // �v�nements
if (keysModifier) {
- addParserEvent(KeysModifier.getInstance(getKeyModifierStart(), getKeyModifierEnd()));
+ addParserEvent(KeysModifier.getInstance(getKeyModifierStart(), getKeyModifierEnd(), encoding));
}
treadedFiles = new ArrayList<File>();
}
+ /**
+ * Test if a file is up to date and do not treate.
+ *
+ * @param basedir the basdir of sourceentry
+ * @param file1 the file path relative to basedir
+ * @param file the file to treate @return <code>true</code> if file is uptodate, says needs no treatment.
+ * @return <code>true</code> if file is up to date and do not need to be parsed
+ */
+ protected abstract boolean isFileUptodate(File basedir, File file1, String file);
+
/*
* (non-Javadoc)
* @see org.apache.maven.plugin.AbstractMojo#execute()
@@ -102,25 +117,27 @@
}
try {
// Reprise sur un ancien parsing
- File oldParserFile = new File(out.getAbsolutePath() + File.separatorChar + getOutGetter());
- File saveFile = new File(out.getAbsolutePath() + File.separatorChar + getOutGetter() + "~");
-
- if (!oldParserFile.exists()) {
+ File oldParserFile = PluginHelper.getGetterFile(out, getOutGetter(), true);
+ //File oldParserFile = new File(out.getAbsolutePath() + File.separatorChar + getOutGetter());
+ File saveFile = PluginHelper.getGetterFileBackup(out, getOutGetter());
+ //File saveFile = new File(out.getAbsolutePath() + File.separatorChar + getOutGetter() + "~");
+
+ /*if (!oldParserFile.exists()) {
oldParserFile.getParentFile().mkdirs();
}
- oldParserFile.createNewFile();
+ oldParserFile.createNewFile();*/
+
oldParser.load(new FileInputStream(oldParserFile));
+ PluginHelper.copy(oldParserFile, saveFile);
- FileUtil.copy(oldParserFile, saveFile);
-
-
- // Anciennes cl�s disponnibles
- File oldLanguageFile = new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundles[0] + ".properties");
- if (!oldLanguageFile.exists()) {
+ // Anciennes cl�s disponnibles
+ File oldLanguageFile = PluginHelper.getI18nFile(src, artifactId, bundles[0], true);
+ //File oldLanguageFile = new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundles[0] + ".properties");
+ /*if (!oldLanguageFile.exists()) {
oldLanguageFile.getParentFile().mkdirs();
}
- oldLanguageFile.createNewFile();
+ oldLanguageFile.createNewFile();*/
oldLanguage.load(new FileInputStream(oldLanguageFile));
// Parsing
@@ -139,7 +156,7 @@
}
- public void parse() {
+ public void parse() throws IOException {
if (treateDefaultEntry) {
addDefaultEntry();
}
@@ -158,7 +175,7 @@
if (verbose) {
getLog().debug(getLogEntry(" parse <" + entry + "> [incoming file(s) : " + foundFiles.length + "]", 0, 0, 0));
} else {
- getLog().info(getLogEntry(" parse <" + entry .getBasedir()+ "> [incoming file(s) : " + foundFiles.length + "]", 0, 0, 0));
+ getLog().info(getLogEntry(" parse <" + entry.getBasedir() + "> [incoming file(s) : " + foundFiles.length + "]", 0, 0, 0));
}
// launch parser for found files
parseEntry(entry.getBasedir(), foundFiles);
@@ -186,7 +203,7 @@
entries = list.toArray(new SourceEntry[list.size()]);
}
- protected void parseEntry(File basedir, String[] files) {
+ protected void parseEntry(File basedir, String[] files) throws IOException {
long t00 = System.nanoTime();
for (int i = 0; i < files.length; i++) {
String file1 = files[i];
@@ -197,8 +214,21 @@
event.eventChangeFile(file);
}
touchFile = false;
- parseFile(file);
+ int size = result.size();
+ if (strictMode || !isFileUptodate(basedir, file, file1)) {
+ // on parse toujours en mode strict ou que le fichier n'est pas à jour
+ getLog().info("parseFile " + file);
+ parseFile(file);
+ }
+
+ // D�tection de nouvelles cl�s, sauvegarde du fichier pour pouvoir le restaurer en cas de plantage
+ if (size != result.size()) {
+ saveProperties0();
+ }
if (touchFile) {
+ if (verbose) {
+ getLog().info("touched file " + file);
+ }
treadedFiles.add(file);
if (verbose) {
getLog().debug(getLogEntry(fileName, i, t000, t00));
@@ -209,4 +239,17 @@
}
}
}
+
+ protected void saveProperties0() throws IOException {
+ OutputStream outputStream = null;
+ try {
+ outputStream = new BufferedOutputStream(new FileOutputStream(PluginHelper.getGetterFile(out, getOutGetter(), false)));
+ //outputStream = new BufferedOutputStream(new FileOutputStream(out.getAbsolutePath() + File.separatorChar + getOutGetter()));
+ result.store(outputStream, null);
+ } finally {
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ }
+ }
}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nPlugin.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nPlugin.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nPlugin.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -19,66 +19,65 @@
package org.codelutin.i18n.plugin.core;
+import org.apache.maven.plugin.AbstractMojo;
+import org.codelutin.i18n.plugin.PluginHelper;
+import org.codelutin.i18n.plugin.PluginHelper.I18nProperties;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
-import org.apache.maven.plugin.AbstractMojo;
-import org.codelutin.util.SortedProperties;
-import org.codelutin.util.StringUtil;
-
/**
- * Classe permettant d'obenir les param�tres pendant les diff�rentes phases
+ * Classe permettant d'obenir les parametres pendant les différentes phases
* du plugin.
- *
+ *
* @author julien
*/
public abstract class AbstractI18nPlugin extends AbstractMojo {
/**
- * @description Langues des bundles g�n�r�s.
+ * @description Langues des bundles generes.
* @parameter expression="${i18n.bundles}" default-value=""
* @required
*/
protected String[] bundles;
/**
- * @description R�pertoire sources des fichiers i18n.
+ * @description Repertoire sources des fichiers i18n.
* @parameter expression="${i18n.src}" default-value="${basedir}/src/resources/i18n"
* @required
*/
protected File src;
/**
- * @description Met les fichiers g�n�r�s dans le r�pertoire des sources i18n.
+ * @description Met les fichiers generes dans le repertoire des sources i18n.
* @parameter expression="${i18n.genSrc}" default-value="true"
*/
protected boolean genSrc;
-
+
/**
- * @description R�pertoire des fichiers g�n�r�s i18n.
+ * @description Répertoire des fichiers generes i18n.
* @parameter expression="${i18n.out}" default-value="${basedir}/target/gen/i18n"
* @required
*/
protected File out;
/**
- * @description Active la modification de cl�
+ * @description Active la modification de cle
* @parameter expression="${i18n.keysModifier}" default-value="false"
*/
protected boolean keysModifier;
/**
* @description verbose
- * @parameter expression="${i18n.verbose}" default-value="${maven.verbose}"
+ * @parameter expression="${i18n.verbose}" default-value="false"
*/
protected boolean verbose;
-
+
/**
* @description Nom du projet.
* @parameter expression="${i18n.artifactId}" default-value="${project.artifactId}"
@@ -91,79 +90,93 @@
* @parameter expression="${i18n.keepBackup}" default-value="true"
*/
protected boolean keepBackup;
-
+
/**
+ * @description ne conserve que les clef scannees (et donc traite tous les fichiers)
+ * @parameter expression="${i18n.strictMode}" default-value="false"
+ */
+ protected boolean strictMode;
+
+ /**
+ * @description ne conserve que les clef scannees (et donc traite tous les fichiers)
+ * @parameter expression="${i18n.encoding}" default-value="${maven.compile.encoding}"
+ * @required
+ */
+ protected String encoding;
+
+ /**
* Log
* Do not use a instance of, use a lazy instancier
*/
//protected Log log = getLog();
-
+
/**
- * R�pertoire de stockage des fichiers i18n pour la r�cup�ration des fichiers
+ * Répertoire de stockage des fichiers i18n pour la recuperation des fichiers
* de traduction entre librairie
*/
protected static String DIRECTORY_INSTALL = "i18n" + File.separatorChar;
-
- /**
- * Liste des �v�nements
- */
+
+ /** Liste des évènements */
protected List<ParserEvent> events = new ArrayList<ParserEvent>();
/**
- * Ajoute un �v�nement
- * @param parserEvent l'�v�nement d'ajout
+ * Ajoute un évènement
+ *
+ * @param parserEvent l'évènement d'ajout
*/
protected void addParserEvent(ParserEvent parserEvent) {
this.events.add(parserEvent);
}
-
+
/**
- * Supprime un �v�nement
- * @param parserEvent l'�v�nement de suppression
+ * Supprime un évènement
+ *
+ * @param parserEvent l'évènement de suppression
*/
protected void removeParserEvent(ParserEvent parserEvent) {
this.events.remove(parserEvent);
}
-
- /**
- * Concat�ne deux fichiers de propri�t�s
- * @param in le fichier entrant
+
+ /**
+ * Concatène deux fichiers de proprietes
+ *
+ * @param in le fichier entrant
* @param out le fichier sortant
- * @throws FileNotFoundException si fichier non trouv�
- * @throws IOException si probl�me pendant la sauvegarde
+ * @throws FileNotFoundException si fichier non trouvé
+ * @throws IOException si problème pendant la sauvegarde
*/
protected void concactProperties(File in, File out) throws IOException {
- Properties propertiesIn = new SortedProperties();
+ Properties propertiesIn = new I18nProperties();
propertiesIn.load(new FileInputStream(in));
-
- Properties propertiesOut = new SortedProperties();
+
+ I18nProperties propertiesOut = new I18nProperties();
propertiesOut.load(new FileInputStream(out));
propertiesOut.putAll(propertiesIn);
- propertiesOut.store(new FileOutputStream(out), null);
+ propertiesOut.store(out);
}
/**
- * Construit une chaine de log format�e.
+ * Construit une chaine de log formatée.
*
* @param msg le prefix du message
- * @param nbFiles le nombre de fichiers actuellement trait�s
+ * @param nbFiles le nombre de fichiers actuellement traités
* @param time le time de traitement de ce fichier
* @param all le temps de traitement de tous les fichiers
- * @return la chaine de log format�e
+ * @return la chaine de log formatée
*/
protected String getLogEntry(String msg, int nbFiles, long time, long all) {
long now = System.nanoTime();
long delta = now - time;
- String s = "["+artifactId+"] i18n."+getClass().getSimpleName() + " : " + msg;
+ String s = "[" + artifactId + "] i18n." + getClass().getSimpleName() + " : " + msg;
if (time > 0) {
- s += " (" + StringUtil.convertTime(delta) + ")";
+ s += " (" + PluginHelper.convertTime(delta) + ")";
}
if (all > 0 && nbFiles > -1) {
- s += "(total time:" + StringUtil.convertTime(now - all) + ") ( ~ " + StringUtil.convertTime(((now - all) / (nbFiles + 1))) + " / file)";
+ s += "(total time:" + PluginHelper.convertTime(now - all) + ") ( ~ " + PluginHelper.convertTime(((now - all) / (nbFiles + 1))) + " / file)";
}
return s;
}
- /** Taille du buffer pour les lectures/�critures */
+ /** Taille du buffer pour les lectures/écritures */
protected static final int BUFFER_SIZE = 8 * 1024;
}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Generate.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Generate.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Generate.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -21,18 +21,16 @@
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
-import org.codelutin.util.FileUtil;
-import org.codelutin.util.PropertiesDateRemoveFilterStream;
-import org.codelutin.util.SortedProperties;
+import org.codelutin.i18n.plugin.PluginHelper;
+import org.codelutin.i18n.plugin.PluginHelper.I18nProperties;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
- * Merge des fichiers de propri�t�s avec les anciens.
+ * Merge des fichiers de propriétés avec les anciens.
*
* @author julien
* @goal gen
@@ -49,40 +47,49 @@
for (String bundle : bundles) {
try {
// Merge
- File bundleSrc = new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
- File bundleOut = new File(out.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ //File bundleSrc = new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ //File bundleOut = new File(out.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ File bundleSrc = PluginHelper.getI18nFile(src, artifactId, bundle, false);
+ File bundleOut = PluginHelper.getI18nFile(out, artifactId, bundle, false);
if (bundleSrc.exists()) {
+
Properties propertiesSrc = new Properties();
propertiesSrc.load(new FileInputStream(bundleSrc));
- Properties propertiesBundle = new SortedProperties();
- propertiesBundle.load(new FileInputStream(bundleOut));
+ I18nProperties propertiesOut = new I18nProperties();
- // Parcours des cl�s
- for (Object key : propertiesBundle.keySet()) {
- Object oldKey = propertiesBundle.get(key);
+ if (!strictMode) {
+ // push back in bundle out, all the bundle src keys
+ propertiesOut.putAll(propertiesSrc);
+ }
+ propertiesOut.load(new FileInputStream(bundleOut));
+
+ // Parcours des clés
+ for (Object key : propertiesOut.keySet()) {
+ Object oldKey = propertiesOut.get(key);
Object value = propertiesSrc.get(oldKey);
- // R�cup�ration de la cl� si elle a �t� renomm�
+ // Récupération de la clé si elle a été renommée
if (!key.equals(oldKey) && value == null) {
value = propertiesSrc.get(key);
}
if (value != null) {
- propertiesBundle.put(key, value);
+ propertiesOut.put(key, value);
} else {
- propertiesBundle.put(key, "");
+ propertiesOut.put(key, "");
}
}
- FileOutputStream fileOutputStream = new FileOutputStream(bundleOut);
- PropertiesDateRemoveFilterStream filter = new PropertiesDateRemoveFilterStream(fileOutputStream);
- propertiesBundle.store(filter, null);
+ //saveBundle(bundleOut, propertiesOut);
+ propertiesOut.store(bundleOut);
+
// Sauvegarde avant copie
if (genSrc && keepBackup) {
- FileUtil.copy(bundleSrc, new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties" + "~"));
+ PluginHelper.copy(bundleSrc, PluginHelper.getI18nFileBackup(src, artifactId, bundle));
+ //FileUtil.copy(bundleSrc, new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties" + "~"));
}
getLog().info("Merge bundle " + bundleSrc.getAbsolutePath());
@@ -90,7 +97,7 @@
if (genSrc) {
// Copie des fichiers dans les sources
- FileUtil.copy(bundleOut, bundleSrc);
+ PluginHelper.copy(bundleOut, bundleSrc);
getLog().info("Copy bundle " + bundleSrc.getAbsolutePath());
}
@@ -100,4 +107,10 @@
}
}
}
+
+ /*void saveBundle(File bundleOut, Properties propertiesBundle) throws IOException {
+ FileOutputStream fileOutputStream = new FileOutputStream(bundleOut);
+ PropertiesDateRemoveFilterStream filter = new PropertiesDateRemoveFilterStream(fileOutputStream);
+ propertiesBundle.store(filter, null);
+ }*/
}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Getter.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Getter.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Getter.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -19,19 +19,18 @@
package org.codelutin.i18n.plugin.core;
-import java.io.File;
-import java.io.IOException;
-
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.DirectoryScanner;
-import org.codelutin.util.FileUtil;
+import org.codelutin.i18n.plugin.PluginHelper;
+import java.io.File;
+import java.io.IOException;
+
/**
- * R�cup�re les diff�rents fichiers des parsers en un fichier de propri�t�s.
- *
+ * Récupère les différents fichiers des parsers en un fichier de propriétés.
+ *
* @author julien
- *
* @goal get
* @phase generate-resources
*/
@@ -45,16 +44,17 @@
try {
File bundleGetters = new File(out.getAbsolutePath() + File.separatorChar + artifactId + ".properties");
bundleGetters.createNewFile();
-
+
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(out);
- ds.setIncludes(new String[] {"*.getter"});
+ ds.setIncludes(new String[]{"*.getter"});
ds.scan();
String[] files = ds.getIncludedFiles();
- // Fusion des fichiers propri�t�s des diff�rents parsers
+ // Fusion des fichiers propriétés des différents parsers
for (String file : files) {
- File bundleGetter = new File(out.getAbsolutePath() + File.separatorChar + file);
+ File bundleGetter = PluginHelper.getGetterFile(out, file, false);
+ //File bundleGetter = new File(out.getAbsolutePath() + File.separatorChar + file);
concactProperties(bundleGetter, bundleGetters);
if (genSrc) {
bundleGetter.delete();
@@ -62,13 +62,14 @@
getLog().info("Create bundle with " + bundleGetter.getAbsolutePath());
}
- // Cr�ation des bundles
+ // Création des bundles
for (String bundle : bundles) {
- File bundleOut = new File(out.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
- FileUtil.copy(bundleGetters, bundleOut);
+ //File bundleOut = new File(out.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ File bundleOut = PluginHelper.getI18nFile(out, artifactId, bundle, false);
+ PluginHelper.copy(bundleGetters, bundleOut);
getLog().info("Generate bundle " + bundleOut.getAbsolutePath());
}
-
+
bundleGetters.delete();
} catch (IOException e) {
getLog().error("File Error I/O ", e);
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Parser.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Parser.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Parser.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -20,30 +20,31 @@
package org.codelutin.i18n.plugin.core;
import java.io.File;
+import java.io.IOException;
/**
- * Interface type pour la d�finition d'un nouveau parser.
+ * Interface type pour la définition d'un nouveau parser.
* <p/>
- * Une implantation abstraite est propos�e : {@link AbstractI18nParser}.
+ * Une implantation abstraite est proposée : {@link AbstractI18nParser}.
*
* @author julien
*/
public interface Parser {
/** Lancement du parser */
- public void parse();
+ public void parse() throws IOException;
/**
* Parse sur un fichier
*
- * @param file le fichier � parser
+ * @param file le fichier à parser
*/
public void parseFile(File file);
/**
* Parse une partie du fichier
*
- * @param file le fichier � parser
+ * @param file le fichier à parser
* @param args ? TODO
*/
public void parseLine(File file, String args);
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserEvent.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserEvent.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserEvent.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -22,36 +22,39 @@
import java.io.File;
/**
- * Permet d'ajouter des �v�nements sur les parsers
- *
+ * Permet d'ajouter des évènements sur les parsers
+ *
* @author julien
- *
*/
public interface ParserEvent {
-
+
/**
- * M�thode appel�e quand on change de fichier pars�
+ * M�thode appelée quand on change de fichier parsé
+ *
* @param file
*/
public void eventChangeFile(File file);
-
+
/**
- * M�thode appel�e apr�s le parsing du fichier
+ * Méthode appelée après le parsing du fichier
+ *
* @param file
*/
public void eventNextFile(File file);
/**
- * M�thode appel�e quand on change de cl�
+ * M�thode appelée quand on change de clé
+ *
* @param keyI18n
* @param newKey
*/
public void eventChangeKey(String keyI18n, boolean newKey);
-
+
/**
- * M�thode appel�e pour r�cup�rer la nouvelle valeur de cl�
+ * M�thode appelée pour récupérer la nouvelle valeur de clé
+ *
* @return
*/
public String eventGetRealKey();
-
+
}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserException.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserException.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserException.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -20,10 +20,9 @@
package org.codelutin.i18n.plugin.core;
/**
- * Permet la gestion des exceptions dans les parsers et dans les �v�nements
- *
- * @author julien
+ * Permet la gestion des exceptions dans les parsers et dans les évènements
*
+ * @author julien
*/
public class ParserException extends RuntimeException {
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJava.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJava.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJava.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -19,36 +19,19 @@
package org.codelutin.i18n.plugin.extension;
-import org.apache.maven.artifact.Artifact;
import org.apache.maven.project.MavenProject;
import org.codelutin.i18n.plugin.core.AbstractI18nParser;
import org.codelutin.i18n.plugin.core.ParserEvent;
import org.codelutin.i18n.plugin.core.ParserException;
-import org.codelutin.i18n.plugin.core.SourceEntry;
import org.codelutin.processor.filters.I18nFilter;
-import org.codelutin.util.FileUtil;
-import java.io.BufferedOutputStream;
-import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
-import java.io.OutputStream;
-import java.lang.annotation.Annotation;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.regex.Pattern;
/**
- * R�cup�ration des cha�ne � traduire depuis les fichiers java.
+ * Récupération des chaine a traduire depuis les fichiers java.
*
* @author julien
* @goal parserJava
@@ -69,33 +52,21 @@
protected File defaultBasedir;
/**
- * @description D�pendance du projet.
+ * @description Dependance du projet.
* @parameter default-value="${project}"
* @readonly
*/
protected MavenProject project;
/**
- * @description R�pertoire sources des fichiers i18n.
+ * @description Repertoire sources des fichiers i18n.
* @parameter expression="${i18n.cp}" default-value="${basedir}/target/classes"
* @required
*/
protected File cp;
- /**
- * @description pour utiliser l'annotation I18nable pour traiter les fichiers
- * @parameter expression="${i18n.ea}" default-value="false"
- */
- protected boolean ea;
+ //protected List<String> annotationClass;
- /**
- * @description pour d�couvrir les fichiers I18nable.
- * @parameter expression="${i18n.detectea}" default-value="false"
- */
- protected boolean detectea;
-
- protected List<String> annotationClass;
-
protected String[] getDefaultIncludes() {
return new String[]{defaultIncludes};
}
@@ -119,33 +90,40 @@
protected I18nFilter filter;
- protected URLClassLoader loader;
- protected Annotation annotation;
+ //protected URLClassLoader loader;
+ //protected Annotation annotation;
@Override
public void init() {
super.init();
filter = new I18nFilter();
- if (detectea) {
+ /*if (detectea) {
// in detect mode, we do not filter by ea, try all files
ea = false;
}
if (ea) {
// in ea mode, we do not detect anything
detectea = false;
- }
+ }*/
- if (ea || detectea) {
+ /*if (ea || detectea) {
loader = initClassLoader();
annotationClass = initAnnotations();
- }
+ }*/
}
- protected List<String> initAnnotations() {
- return Collections.singletonList("org.codelutin.i18n.I18nable");
+ protected boolean isFileUptodate(File basedir, File file1, String file) {
+ String clazzFile = file.substring(0, file.length() - 4) + "class";
+ File clazz = new File(cp + File.separator + clazzFile);
+
+ return clazz.exists() && file1.lastModified() < clazz.lastModified();
}
- @Override
+ /*protected List<String> initAnnotations() {
+ return Collections.singletonList("org.codelutin.i18n.I18nable");
+ }*/
+
+ /*@Override
protected String[] getFilesForEntry(SourceEntry entry) {
if (detectea || !ea) {
@@ -155,29 +133,28 @@
// filter by annotation
return entry.getIncludedFiles(getDefaultBasedir(), getDefaultIncludes(), loader, annotationClass, getLog());
- }
+ }*/
/*
* (non-Javadoc)
* @see org.codelutin.i18n.plugin.core.Parser#parseFile(java.io.File)
*/
+
public void parseFile(File srcFile) {
try {
- int size = result.size();
- parseFile0(srcFile);
-
- // D�tection de nouvelles cl�s, sauvegarde du fichier pour pouvoir le restaurer en cas de plantage
- if (size != result.size()) {
- saveProperties0();
+ LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(srcFile)));
+ while (lnr.ready()) {
+ String line = lnr.readLine();
+ parseLine(srcFile, line);
}
- if (touchFile && detectea) {
+ /*if (touchFile && detectea) {
Annotation annotation = currentEntry.getAnnotation(srcFile, loader, annotationClass, getLog());
if (annotation == null) {
addAnnotation(srcFile);
}
- }
+ }*/
} catch (Exception e) {
throw new ParserException(e);
}
@@ -209,7 +186,7 @@
}
}
- private void addAnnotation(File srcFile) throws IOException {
+ /*private void addAnnotation(File srcFile) throws IOException {
String classname = srcFile.getName();
@@ -249,30 +226,18 @@
outputStream.close();
}
}
- }
+ }*/
- protected void saveProperties0() throws IOException {
- OutputStream outputStream = null;
- try {
- outputStream = new BufferedOutputStream(new FileOutputStream(out.getAbsolutePath() + File.separatorChar + getOutGetter()));
- result.store(outputStream, null);
- } finally {
- if (outputStream != null) {
- outputStream.close();
- }
- }
- }
-
- protected void parseFile0(File srcFile) throws IOException {
+ /*protected void parseFile0(File srcFile) throws IOException {
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(srcFile)));
while (lnr.ready()) {
String line = lnr.readLine();
parseLine(srcFile, line);
}
- }
+ }*/
- @SuppressWarnings({"unchecked"})
- protected URLClassLoader initClassLoader() {
+ /*@SuppressWarnings({"unchecked"})
+ private URLClassLoader initClassLoader() {
URLClassLoader loader = null;
if (project != null) {
URLClassLoader result;
@@ -309,5 +274,5 @@
}
}
return loader;
- }
+ }*/
}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaActionConfig.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaActionConfig.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaActionConfig.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -21,8 +21,6 @@
import org.codelutin.i18n.plugin.core.ParserEvent;
import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -52,20 +50,21 @@
return "java-action-config.getter";
}
- @Override
+ /*@Override
protected List<String> initAnnotations() {
- List<String> result = new ArrayList<String>(1);
- result.add("jaxx.runtime.builder.ActionConfig");
- result.add("jaxx.runtime.builder.SelectActionConfig");
- result.add("jaxx.runtime.builder.TabContentConfig");
- result.add("jaxx.runtime.builder.ToggleActionConfig");
+ List<String> result = new ArrayList<String>(4);
+ result.add("org.codelutin.jaxx.action.ActionConfig");
+ result.add("org.codelutin.jaxx.action.SelectActionConfig");
+ result.add("org.codelutin.jaxx.action.TabContentConfig");
+ result.add("org.codelutin.jaxx.action.ToggleActionConfig");
return result;
- }
+ }*/
/*
* (non-Javadoc)
* @see org.codelutin.i18n.plugin.extension.XmlParser#extract(java.lang.String)
*/
+
public String extract(String i18nString) {
Matcher matcher = MATCH_PATTERN.matcher(i18nString.trim());
if (matcher.matches()) {
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaTabConfig.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaTabConfig.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaTabConfig.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -14,8 +14,6 @@
*/
package org.codelutin.i18n.plugin.extension;
-import java.util.Collections;
-
/**
* Un paseur java pour scanner les annotations TabContentConfig.
*
@@ -30,9 +28,9 @@
return "java-tab-config.getter";
}
- @Override
+ /*@Override
protected java.util.List<String> initAnnotations() {
return Collections.singletonList("org.codelutin.i18n.I18nable");
- }
+ }*/
}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJaxx.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJaxx.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJaxx.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -19,8 +19,10 @@
package org.codelutin.i18n.plugin.extension;
+import java.io.File;
+
/**
- * R�cup�ration des cha�ne � traduire depuis les fichiers xml Jaxx.
+ * Récupération des chaine à traduire depuis les fichiers xml Jaxx.
*
* @author julien
* @goal parserJaxx
@@ -33,9 +35,9 @@
* @parameter expression="${i18n.defaultIncludes}" default-value="**\\/*.jaxx"
*/
protected String defaultIncludes;
-
+
/**
- * @description R�gles xml.
+ * @description Règles xml.
* @parameter expression="${i18n.rulesJaxx}" default-value="jaxx.rules"
*/
protected String rulesJaxx;
@@ -44,6 +46,10 @@
return new String[]{defaultIncludes};
}
+ protected boolean isFileUptodate(File basedir, File file1, String file) {
+ return false;
+ }
+
protected String getOutGetter() {
return "jaxx.getter";
}
@@ -73,7 +79,7 @@
* @see org.codelutin.i18n.plugin.extension.XmlParser#extract(java.lang.String)
*/
public String extract(String i18nString) {
- return i18nString.length()==0?null:i18nString;
+ return i18nString.length() == 0 ? null : i18nString;
}
}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserSwixat.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserSwixat.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserSwixat.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -19,8 +19,10 @@
package org.codelutin.i18n.plugin.extension;
+import java.io.File;
+
/**
- * R�cup�ration des cha�ne � traduire depuis les fichiers xml Swixat.
+ * Récupération des chaines à traduire depuis les fichiers xml Swixat.
*
* @author julien
* @goal parserSwixat
@@ -35,7 +37,7 @@
protected String defaultIncludes;
/**
- * @description R�gles xml.
+ * @description R�gles xml.
* @parameter expression="${i18n.rulesSwixat}" default-value="swixat.rules"
*/
protected String rulesSwixat;
@@ -44,7 +46,11 @@
return new String[]{defaultIncludes};
}
+ protected boolean isFileUptodate(File basedir, File file1, String file) {
+ return false;
+ }
+
protected String getKeyModifierStart() {
return "=\\s*[\"\']";
}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserXml.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserXml.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserXml.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -34,19 +34,17 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
/**
- * R�cup�ration des cha�ne � traduire depuis les fichiers xml.
+ * Récupération des chaines à traduire depuis les fichiers xml.
*
* @author julien
*/
public abstract class ParserXml extends AbstractI18nParser {
- /** Taille du buffer pour les lectures/�critures */
+ /** Taille du buffer pour les lectures/écritures */
protected static final int BUFFER_SIZE = 8 * 1024;
/**
@@ -71,7 +69,7 @@
/** @return le fichier des rules */
protected abstract String getFileRules();
- /** @return le fichier des rules de base � toujours charger */
+ /** @return le fichier des rules de base à toujours charger */
protected abstract String getCoreFileRules();
@Override
@@ -88,12 +86,12 @@
*/
public void parseFile(File file) {
NodeList list;
- InputSource inputSource = new InputSource(file.getAbsolutePath()); // TODO: A d�placer pour les performances
+ InputSource inputSource = new InputSource(file.getAbsolutePath()); // TODO: A d�placer pour les performances
try {
int size = result.size();
- // Recherche des cl�s � partir d'un xpath
+ // Recherche des clés à partir d'un xpath
XPathExpression expression = xpath.compile(rules);
list = (NodeList) expression.evaluate(inputSource, XPathConstants.NODESET);
@@ -102,10 +100,11 @@
parseLine(file, node.getTextContent());
}
- // D�tection de nouvelles cl�s, sauvegarde du fichier pour pouvoir le restaurer en cas de plantage
+ // Détection de nouvelles clés, sauvegarde du fichier pour pouvoir le restaurer en cas de plantage
if (size != result.size()) {
- OutputStream xmlparserOut = new FileOutputStream(out.getAbsolutePath() + File.separatorChar + getOutGetter());
- result.store(xmlparserOut, null);
+ saveProperties0();
+ //OutputStream xmlparserOut = new FileOutputStream(out.getAbsolutePath() + File.separatorChar + getOutGetter());
+ //result.store(xmlparserOut, null);
}
} catch (Exception e) {
throw new ParserException(e);
@@ -139,10 +138,10 @@
}
/**
- * R�cup�re le xpath � partir d'un fichier
+ * Récupère le xpath à partir d'un fichier
*
- * @param fileRules le nom du fichier contant les r�gles
- * @return le xpath � partir d'un fichier
+ * @param fileRules le nom du fichier contant les règles
+ * @return le xpath à partir d'un fichier
*/
private String getRules(String fileRules) {
StringBuilder result = new StringBuilder();
@@ -211,7 +210,7 @@
*
* @param in le flux entrant
* @return le contenu du flux
- * @throws IOException si probl�me de lecture dans flux entrant
+ * @throws IOException si problème de lecture dans flux entrant
*/
private String readInputStream(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
@@ -225,7 +224,7 @@
String result = sb.toString().trim();
result = result.replaceAll("#.*\n", ""); // suppression des commentaires
result = result.replaceAll("\\s+", " | "); // contruction du xpath avec des ou
- result = result.replaceAll("(^ \\| )|( \\| $)", ""); // suppression des ou de d�but ee fin
+ result = result.replaceAll("(^ \\| )|( \\| $)", ""); // suppression des ou de début ee fin
return result;
}
}
Modified: trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/ui/KeysModifier.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/ui/KeysModifier.java 2008-08-04 11:30:42 UTC (rev 962)
+++ trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/ui/KeysModifier.java 2008-08-04 11:32:55 UTC (rev 963)
@@ -19,6 +19,15 @@
package org.codelutin.i18n.plugin.ui;
+import org.codelutin.i18n.plugin.PluginHelper;
+import org.codelutin.i18n.plugin.core.ParserEvent;
+import org.codelutin.i18n.plugin.core.ParserException;
+
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JTextField;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
@@ -33,32 +42,22 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JTextField;
-
-import org.codelutin.i18n.plugin.core.ParserEvent;
-import org.codelutin.i18n.plugin.core.ParserException;
-import org.codelutin.util.FileUtil;
-
/**
- * IHM permettant de modifier les cl�s de traduction en direct dans les fichiers
- * pars�s et les fichiers de propri�t�s.
- *
+ * IHM permettant de modifier les clés de traduction en direct dans les fichiers
+ * parsés et les fichiers de propriétés.
+ *
* @author julien
- *
*/
public class KeysModifier extends JFrame implements ParserEvent {
private static final long serialVersionUID = 1L;
-
- // Modification des cl�s dans le fichier
+
+ // Modification des clés dans le fichier
protected List<String> newKeys;
protected boolean needModifiedFile;
protected String patternLeft;
protected String patternRight;
+ protected String encoding;
// Interface
protected JLabel name = new JLabel();
@@ -66,33 +65,33 @@
protected JTextField key = new JTextField();
protected JTextField pattern = new JTextField(".*");
protected JCheckBox onlyNewKey = new JCheckBox();
+
+
protected JButton next = new JButton("Next >>");
+ private static KeysModifier keysModifier;
-
- private static KeysModifier keysModifier;
-
/**
- * Rc�cup�ration d'une instance de l'interface
- * @param patternLeft
- * @param patternRight
- * @return
+ * Récupération d'une instance de l'interface
+ *
+ * @param patternLeft left pattern
+ * @param patternRight right pattern
+ * @param encoding encoding
+ * @return the shared instance with new config
*/
- public static KeysModifier getInstance(String patternLeft, String patternRight) {
- if(keysModifier == null) {
+ public static KeysModifier getInstance(String patternLeft, String patternRight, String encoding) {
+ if (keysModifier == null) {
keysModifier = new KeysModifier();
}
-
+
+
+ keysModifier.encoding = encoding;
keysModifier.patternLeft = patternLeft;
keysModifier.patternRight = patternRight;
-
+
return keysModifier;
}
-
- /**
- * Contructeur de l'interface
- * @param patternLeft
- * @param patternRight
- */
+
+ /** Contructeur de l'interface */
private KeysModifier() {
setLayout(new GridLayout(9, 2, 10, 10));
@@ -142,7 +141,7 @@
path.setText(file.getPath());
key.setText("");
repaint();
-
+
newKeys = new ArrayList<String>();
needModifiedFile = false;
}
@@ -152,12 +151,12 @@
* @see org.codelutin.i18n.plugin.core.ParserEvent#eventNextFile(java.io.File)
*/
public void eventNextFile(File file) {
- if(needModifiedFile) {
+ if (needModifiedFile) {
String content = "";
int region = 0;
try {
- content = FileUtil.readAsString(file);
+ content = PluginHelper.readAsString(file, encoding);
} catch (IOException e) {
throw new ParserException(e);
}
@@ -174,22 +173,22 @@
}
try {
- FileUtil.writeString(file, content);
+ PluginHelper.writeString(file, content, encoding);
} catch (IOException e) {
throw new ParserException(e);
}
}
}
-
+
/*
- * (non-Javadoc)
- * @see org.codelutin.i18n.plugin.core.ParserEvent#eventChangeKey(java.lang.String)
- */
+ * (non-Javadoc)
+ * @see org.codelutin.i18n.plugin.core.ParserEvent#eventChangeKey(java.lang.String)
+ */
public synchronized void eventChangeKey(String keyI18n, boolean newKey) {
key.setText(keyI18n);
newKeys.add(key.getText());
repaint();
- if(isVisible() && keyI18n.matches(pattern.getText()) && (!onlyNewKey.isSelected() || newKey)) {
+ if (isVisible() && keyI18n.matches(pattern.getText()) && (!onlyNewKey.isSelected() || newKey)) {
try {
wait();
} catch (InterruptedException e) {
@@ -208,36 +207,42 @@
return key.getText();
}
- /**
- * Action sur le boutton pour passer � la cl� suivante
- */
+ /** Action sur le boutton pour passer � la cl� suivante */
class EventNextKey implements ActionListener {
public void actionPerformed(ActionEvent e) {
eventNextKey();
}
}
- /**
- * Action sur la fermeture de la frame
- */
+ /** Action sur la fermeture de la frame */
class EventWindows implements WindowListener {
- public void windowClosed(WindowEvent e) {}
- public void windowActivated(WindowEvent e) {}
+ public void windowClosed(WindowEvent e) {
+ }
+
+ public void windowActivated(WindowEvent e) {
+ }
+
public void windowClosing(WindowEvent e) {
setVisible(false);
eventNextKey();
}
- public void windowDeactivated(WindowEvent e) {}
- public void windowDeiconified(WindowEvent e) {}
- public void windowIconified(WindowEvent e) {}
- public void windowOpened(WindowEvent e) {}
+ public void windowDeactivated(WindowEvent e) {
+ }
+
+ public void windowDeiconified(WindowEvent e) {
+ }
+
+ public void windowIconified(WindowEvent e) {
+ }
+
+ public void windowOpened(WindowEvent e) {
+ }
+
}
- /**
- * Permet de passer � la cl� suivante
- */
+ /** Permet de passer à la clé suivante */
public synchronized void eventNextKey() {
notifyAll();
}
1
0
[Lutinutil-commits] r962 - in tags/04082008_beforeUTF8: . maven-i18n-plugin maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/ui
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
04 Aug '08
Author: tchemit
Date: 2008-08-04 11:30:42 +0000 (Mon, 04 Aug 2008)
New Revision: 962
Added:
tags/04082008_beforeUTF8/maven-i18n-plugin/
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/PluginHelper.java
Modified:
tags/04082008_beforeUTF8/maven-i18n-plugin/pom.xml
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nParser.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nPlugin.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Generate.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Getter.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Parser.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserEvent.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserException.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJava.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaActionConfig.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaTabConfig.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJaxx.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserSwixat.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserXml.java
tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/ui/KeysModifier.java
Log:
before UTF8
Copied: tags/04082008_beforeUTF8/maven-i18n-plugin (from rev 955, trunk/maven-i18n-plugin)
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/pom.xml
===================================================================
--- trunk/maven-i18n-plugin/pom.xml 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/pom.xml 2008-08-04 11:30:42 UTC (rev 962)
@@ -31,12 +31,12 @@
<scope>compile</scope>
</dependency>
- <dependency>
+ <!--dependency>
<groupId>org.codelutin</groupId>
<artifactId>lutinutil-no-i18n</artifactId>
<version>0.30-SNAPSHOT</version>
<scope>compile</scope>
- </dependency>
+ </dependency-->
<dependency>
<groupId>lutinlib</groupId>
@@ -64,7 +64,7 @@
<!-- *** Project Information ************************************* -->
<!-- ************************************************************* -->
<name>Plugin maven pour lutini18n</name>
- <version>0.3-SNAPSHOT</version>
+ <version>0.4</version>
<description>
Plugin pour maven 2 pour la génération des bundles pour l'internationnalisation des applications java fait par
lutinutil-i18n
@@ -142,7 +142,7 @@
<!-- compile with ? -->
<maven.compile.source>1.6</maven.compile.source>
<maven.compile.target>1.6</maven.compile.target>
- <maven.compile.encoding>ISO-8859-15</maven.compile.encoding>
+ <maven.compile.encoding>UTF-8</maven.compile.encoding>
<!-- Lists URL -->
<labs.lists>
Added: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/PluginHelper.java
===================================================================
--- tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/PluginHelper.java (rev 0)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/PluginHelper.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -0,0 +1,275 @@
+/**
+ * # #% Copyright (C) 2008 Code Lutin, Tony Chemit
+ * This program is free software; you
+ * can redistribute it and/or modify it under the terms of the GNU General
+ * Public License as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version. This program is
+ * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+ * PARTICULAR PURPOSE. See the GNU General Public License for more details. You
+ * should have received a copy of the GNU General Public License along with this
+ * program; if not, write to the Free Software Foundation, Inc., 59 Temple Place
+ * - Suite 330, Boston, MA 02111-1307, USA.
+ * # #%
+ */
+package org.codelutin.i18n.plugin;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.nio.channels.FileChannel;
+import java.text.MessageFormat;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Properties;
+import java.util.Vector;
+
+/**
+ * Une classe pour mutualiser toutes les méthodes utiles dans ce plugin.
+ * <p/>
+ * Note : On a dupliqué ici du code de la librairie lutinutil, pour casser la dépendance ver ce projet qui utilise ce plugin
+ * et donc introduit un cycle dans le graphe des dépendances, ce qui n'est pas souhaitable.
+ *
+ * @author chemit
+ */
+public class PluginHelper {
+
+ /**
+ * @param root le repertoire ou sont stockes les fichiers i18n
+ * @param artifactId le nom de l'artifact
+ * @param bundle le nom du bundle
+ * @param create <code>true</code> pour creer le fichier si non present
+ * @return le fichier i18n
+ * @throws java.io.IOException si probleme lors de la creation du fichier
+ */
+ public static File getI18nFile(File root, String artifactId, String bundle, boolean create) throws IOException {
+ File file = new File(root.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ if (create && !file.exists()) {
+ if (!file.exists()) {
+ file.getParentFile().mkdirs();
+ }
+ file.createNewFile();
+ }
+ return file;
+ }
+
+ /**
+ * @param root le repertoire ou sont stockes les fichiers getter
+ * @param getter le nom du getter
+ * @param create <code>true</code> pour creer le fichier si non present
+ * @return le fichier i18n
+ * @throws java.io.IOException si probleme lors de la creation du fichier
+ */
+ public static File getGetterFile(File root, String getter, boolean create) throws IOException {
+ File file = new File(root.getAbsolutePath() + File.separatorChar + getter);
+ if (create && !file.exists()) {
+ if (!file.exists()) {
+ file.getParentFile().mkdirs();
+ }
+ file.createNewFile();
+ }
+ return file;
+ }
+
+ /**
+ * @param root le repertoire ou sont stockes les fichiers getter
+ * @param getter le nom du getter
+ * @return le fichier i18n
+ */
+ public static File getGetterFileBackup(File root, String getter) {
+ return new File(root.getAbsolutePath() + File.separatorChar + getter + '~');
+ }
+
+ /**
+ * @param root le reertoire ou sont stockes les fichiers i18n
+ * @param artifactId le nom de l'artifact
+ * @param bundle le nom du bundle
+ * @return le fichier i18n de backup
+ */
+ public static File getI18nFileBackup(File root, String artifactId, String bundle) {
+ return new File(root.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties~");
+ }
+
+ /**
+ * Permet de copier le fichier source vers le fichier cible.
+ *
+ * @param source le fichier source
+ * @param target le fichier cible
+ * @throws java.io.IOException Erreur de copie
+ */
+ public static void copy(File source, File target) throws IOException {
+ target.getParentFile().mkdirs();
+ FileChannel sourceChannel = new FileInputStream(source).getChannel();
+ FileChannel targetChannel = new FileOutputStream(target).getChannel();
+ sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
+ // or
+ // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
+ sourceChannel.close();
+ targetChannel.close();
+ }
+
+ /**
+ * Permet de lire un fichier et de retourner sont contenu sous forme d'une
+ * chaine de carateres
+ *
+ * @param file le fichier a lire
+ * @param encoding encoding to read file
+ * @return the content of the file
+ * @throws IOException if IO pb
+ */
+ static public String readAsString(File file, String encoding) throws IOException {
+ StringBuffer result = new StringBuffer();
+ char[] cbuf = new char[2000];
+ FileInputStream inf = new FileInputStream(file);
+ BufferedReader in = new BufferedReader(new InputStreamReader(inf, encoding));
+ int nb = in.read(cbuf);
+ while (nb != -1) {
+ result.append(cbuf, 0, nb);
+ nb = in.read(cbuf);
+ }
+ in.close();
+ return result.toString();
+ }
+
+ static public void writeString(File file, String content, String encoding) throws IOException {
+ file.getParentFile().mkdirs();
+ BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding));
+ out.write(content);
+ out.close();
+ }
+
+ /**
+ * Permet de convertir une liste non typee, en une liste typee.
+ * <p/>
+ * La liste en entree en juste bien castee.
+ * <p/>
+ * On effectue une verification sur le typage des elements de la liste.
+ * <p/>
+ * Note : <b>Aucune liste n'est creee, ni recopiee</b>
+ *
+ * @param list la liste a convertir
+ * @param type le type des elements de la liste
+ * @return la liste typee
+ * @throws IllegalArgumentException si un element de la liste en entree n'est
+ * pas en adequation avec le type voulue.
+ */
+ @SuppressWarnings({"unchecked"})
+ static public <O> List<O> toGenericList(List list, Class<O> type) throws IllegalArgumentException {
+ if (list.isEmpty()) {
+ return list;
+ }
+ for (Object o : list) {
+ if (!(type.isAssignableFrom(o.getClass()))) {
+ throw new IllegalArgumentException("can not cast List with object of type " + o.getClass() + " to " + type + " type!");
+ }
+ }
+ return list;
+ }
+
+
+ static final protected double[] timeFactors = {1000000, 1000, 60, 60, 24};
+
+ static final protected String[] timeUnites = {"ns", "ms", "s", "m", "h",
+ "d"};
+
+ static public String convertTime(long value) {
+ return convert(value, timeFactors, timeUnites);
+ }
+
+ static public String convertTime(long value, long value2) {
+ return convertTime(value2 - value);
+ }
+
+ static public String convert(long value, double[] factors, String[] unites) {
+ long sign = value == 0 ? 1 : value / Math.abs(value);
+ int i = 0;
+ double tmp = Math.abs(value);
+ while (i < factors.length && i < unites.length && tmp > factors[i]) {
+ tmp = tmp / factors[i++];
+ }
+
+ tmp *= sign;
+ String result;
+ result = MessageFormat.format("{0,number,0.###}{1}", tmp,
+ unites[i]);
+ return result;
+ }
+
+ /**
+ * Permet d'avoir les fichiers de proprietes tries.
+ *
+ * @author julien
+ */
+ public static class I18nProperties extends Properties {
+
+ private static final long serialVersionUID = -1147150444452577558L;
+
+
+ public I18nProperties() {
+ super();
+ }
+
+ public I18nProperties(Properties defaults) {
+ super(defaults);
+ }
+
+ @Override
+ public synchronized Enumeration<Object> keys() {
+ List<Object> objects = Collections.list(super.keys());
+ Vector<Object> result;
+ try {
+ // Attention, si les clef ne sont pas des string, ca ne marchera pas
+ List<String> list = toGenericList(objects, String.class);
+ Collections.sort(list);
+ result = new Vector<Object>(list);
+ } catch (IllegalArgumentException e) {
+ // keys are not string !!!
+ // can not sort keys
+ result = new Vector<Object>(objects);
+ }
+ return result.elements();
+ }
+
+ public void store(File bundleOut) throws IOException {
+ super.store(new PropertiesDateRemoveFilterStream(new FileOutputStream(bundleOut)), null);
+ }
+ }
+
+ public static class PropertiesDateRemoveFilterStream extends FilterOutputStream {
+
+ private boolean firstLineOver;
+ char endChar;
+
+ public PropertiesDateRemoveFilterStream(OutputStream out) {
+ super(out);
+ firstLineOver = false;
+ String lineSeparator = java.security.AccessController
+ .doPrivileged(new sun.security.action.GetPropertyAction(
+ "line.separator"));
+ endChar = lineSeparator.charAt(lineSeparator.length() - 1);
+ }
+
+ @Override
+ public void write(int b) throws IOException {
+ if (!firstLineOver) {
+ char c = (char) b;
+ if (c == endChar) {
+ firstLineOver = true;
+ }
+ } else {
+ out.write(b);
+ }
+ }
+
+ }
+
+
+}
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nParser.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nParser.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nParser.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -20,11 +20,15 @@
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
+import org.codelutin.i18n.plugin.PluginHelper;
import org.codelutin.i18n.plugin.ui.KeysModifier;
-import org.codelutin.util.FileUtil;
+import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -36,6 +40,7 @@
* @author tony
*/
public abstract class AbstractI18nParser extends AbstractI18nPlugin implements Parser {
+
/** @return the outGetter to use for the instance (java.getter,...) */
protected abstract String getOutGetter();
@@ -82,13 +87,23 @@
oldParser = new Properties();
oldLanguage = new Properties();
out.mkdirs();
- // �v�nements
+ // �v�nements
if (keysModifier) {
- addParserEvent(KeysModifier.getInstance(getKeyModifierStart(), getKeyModifierEnd()));
+ addParserEvent(KeysModifier.getInstance(getKeyModifierStart(), getKeyModifierEnd(), encoding));
}
treadedFiles = new ArrayList<File>();
}
+ /**
+ * Test if a file is up to date and do not treate.
+ *
+ * @param basedir the basdir of sourceentry
+ * @param file1 the file path relative to basedir
+ * @param file the file to treate @return <code>true</code> if file is uptodate, says needs no treatment.
+ * @return <code>true</code> if file is up to date and do not need to be parsed
+ */
+ protected abstract boolean isFileUptodate(File basedir, File file1, String file);
+
/*
* (non-Javadoc)
* @see org.apache.maven.plugin.AbstractMojo#execute()
@@ -102,25 +117,27 @@
}
try {
// Reprise sur un ancien parsing
- File oldParserFile = new File(out.getAbsolutePath() + File.separatorChar + getOutGetter());
- File saveFile = new File(out.getAbsolutePath() + File.separatorChar + getOutGetter() + "~");
-
- if (!oldParserFile.exists()) {
+ File oldParserFile = PluginHelper.getGetterFile(out, getOutGetter(), true);
+ //File oldParserFile = new File(out.getAbsolutePath() + File.separatorChar + getOutGetter());
+ File saveFile = PluginHelper.getGetterFileBackup(out, getOutGetter());
+ //File saveFile = new File(out.getAbsolutePath() + File.separatorChar + getOutGetter() + "~");
+
+ /*if (!oldParserFile.exists()) {
oldParserFile.getParentFile().mkdirs();
}
- oldParserFile.createNewFile();
+ oldParserFile.createNewFile();*/
+
oldParser.load(new FileInputStream(oldParserFile));
+ PluginHelper.copy(oldParserFile, saveFile);
- FileUtil.copy(oldParserFile, saveFile);
-
-
- // Anciennes cl�s disponnibles
- File oldLanguageFile = new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundles[0] + ".properties");
- if (!oldLanguageFile.exists()) {
+ // Anciennes cl�s disponnibles
+ File oldLanguageFile = PluginHelper.getI18nFile(src, artifactId, bundles[0], true);
+ //File oldLanguageFile = new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundles[0] + ".properties");
+ /*if (!oldLanguageFile.exists()) {
oldLanguageFile.getParentFile().mkdirs();
}
- oldLanguageFile.createNewFile();
+ oldLanguageFile.createNewFile();*/
oldLanguage.load(new FileInputStream(oldLanguageFile));
// Parsing
@@ -139,7 +156,7 @@
}
- public void parse() {
+ public void parse() throws IOException {
if (treateDefaultEntry) {
addDefaultEntry();
}
@@ -158,7 +175,7 @@
if (verbose) {
getLog().debug(getLogEntry(" parse <" + entry + "> [incoming file(s) : " + foundFiles.length + "]", 0, 0, 0));
} else {
- getLog().info(getLogEntry(" parse <" + entry .getBasedir()+ "> [incoming file(s) : " + foundFiles.length + "]", 0, 0, 0));
+ getLog().info(getLogEntry(" parse <" + entry.getBasedir() + "> [incoming file(s) : " + foundFiles.length + "]", 0, 0, 0));
}
// launch parser for found files
parseEntry(entry.getBasedir(), foundFiles);
@@ -186,7 +203,7 @@
entries = list.toArray(new SourceEntry[list.size()]);
}
- protected void parseEntry(File basedir, String[] files) {
+ protected void parseEntry(File basedir, String[] files) throws IOException {
long t00 = System.nanoTime();
for (int i = 0; i < files.length; i++) {
String file1 = files[i];
@@ -197,8 +214,21 @@
event.eventChangeFile(file);
}
touchFile = false;
- parseFile(file);
+ int size = result.size();
+ if (strictMode || !isFileUptodate(basedir, file, file1)) {
+ // on parse toujours en mode strict ou que le fichier n'est pas à jour
+ getLog().info("parseFile " + file);
+ parseFile(file);
+ }
+
+ // D�tection de nouvelles cl�s, sauvegarde du fichier pour pouvoir le restaurer en cas de plantage
+ if (size != result.size()) {
+ saveProperties0();
+ }
if (touchFile) {
+ if (verbose) {
+ getLog().info("touched file " + file);
+ }
treadedFiles.add(file);
if (verbose) {
getLog().debug(getLogEntry(fileName, i, t000, t00));
@@ -209,4 +239,17 @@
}
}
}
+
+ protected void saveProperties0() throws IOException {
+ OutputStream outputStream = null;
+ try {
+ outputStream = new BufferedOutputStream(new FileOutputStream(PluginHelper.getGetterFile(out, getOutGetter(), false)));
+ //outputStream = new BufferedOutputStream(new FileOutputStream(out.getAbsolutePath() + File.separatorChar + getOutGetter()));
+ result.store(outputStream, null);
+ } finally {
+ if (outputStream != null) {
+ outputStream.close();
+ }
+ }
+ }
}
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nPlugin.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nPlugin.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/AbstractI18nPlugin.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -19,66 +19,65 @@
package org.codelutin.i18n.plugin.core;
+import org.apache.maven.plugin.AbstractMojo;
+import org.codelutin.i18n.plugin.PluginHelper;
+import org.codelutin.i18n.plugin.PluginHelper.I18nProperties;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
-import org.apache.maven.plugin.AbstractMojo;
-import org.codelutin.util.SortedProperties;
-import org.codelutin.util.StringUtil;
-
/**
- * Classe permettant d'obenir les param�tres pendant les diff�rentes phases
+ * Classe permettant d'obenir les parametres pendant les différentes phases
* du plugin.
- *
+ *
* @author julien
*/
public abstract class AbstractI18nPlugin extends AbstractMojo {
/**
- * @description Langues des bundles g�n�r�s.
+ * @description Langues des bundles generes.
* @parameter expression="${i18n.bundles}" default-value=""
* @required
*/
protected String[] bundles;
/**
- * @description R�pertoire sources des fichiers i18n.
+ * @description Repertoire sources des fichiers i18n.
* @parameter expression="${i18n.src}" default-value="${basedir}/src/resources/i18n"
* @required
*/
protected File src;
/**
- * @description Met les fichiers g�n�r�s dans le r�pertoire des sources i18n.
+ * @description Met les fichiers generes dans le repertoire des sources i18n.
* @parameter expression="${i18n.genSrc}" default-value="true"
*/
protected boolean genSrc;
-
+
/**
- * @description R�pertoire des fichiers g�n�r�s i18n.
+ * @description Répertoire des fichiers generes i18n.
* @parameter expression="${i18n.out}" default-value="${basedir}/target/gen/i18n"
* @required
*/
protected File out;
/**
- * @description Active la modification de cl�
+ * @description Active la modification de cle
* @parameter expression="${i18n.keysModifier}" default-value="false"
*/
protected boolean keysModifier;
/**
* @description verbose
- * @parameter expression="${i18n.verbose}" default-value="${maven.verbose}"
+ * @parameter expression="${i18n.verbose}" default-value="false"
*/
protected boolean verbose;
-
+
/**
* @description Nom du projet.
* @parameter expression="${i18n.artifactId}" default-value="${project.artifactId}"
@@ -91,79 +90,93 @@
* @parameter expression="${i18n.keepBackup}" default-value="true"
*/
protected boolean keepBackup;
-
+
/**
+ * @description ne conserve que les clef scannees (et donc traite tous les fichiers)
+ * @parameter expression="${i18n.strictMode}" default-value="false"
+ */
+ protected boolean strictMode;
+
+ /**
+ * @description ne conserve que les clef scannees (et donc traite tous les fichiers)
+ * @parameter expression="${i18n.encoding}" default-value="${maven.compile.encoding}"
+ * @required
+ */
+ protected String encoding;
+
+ /**
* Log
* Do not use a instance of, use a lazy instancier
*/
//protected Log log = getLog();
-
+
/**
- * R�pertoire de stockage des fichiers i18n pour la r�cup�ration des fichiers
+ * Répertoire de stockage des fichiers i18n pour la recuperation des fichiers
* de traduction entre librairie
*/
protected static String DIRECTORY_INSTALL = "i18n" + File.separatorChar;
-
- /**
- * Liste des �v�nements
- */
+
+ /** Liste des évènements */
protected List<ParserEvent> events = new ArrayList<ParserEvent>();
/**
- * Ajoute un �v�nement
- * @param parserEvent l'�v�nement d'ajout
+ * Ajoute un évènement
+ *
+ * @param parserEvent l'évènement d'ajout
*/
protected void addParserEvent(ParserEvent parserEvent) {
this.events.add(parserEvent);
}
-
+
/**
- * Supprime un �v�nement
- * @param parserEvent l'�v�nement de suppression
+ * Supprime un évènement
+ *
+ * @param parserEvent l'évènement de suppression
*/
protected void removeParserEvent(ParserEvent parserEvent) {
this.events.remove(parserEvent);
}
-
- /**
- * Concat�ne deux fichiers de propri�t�s
- * @param in le fichier entrant
+
+ /**
+ * Concatène deux fichiers de proprietes
+ *
+ * @param in le fichier entrant
* @param out le fichier sortant
- * @throws FileNotFoundException si fichier non trouv�
- * @throws IOException si probl�me pendant la sauvegarde
+ * @throws FileNotFoundException si fichier non trouvé
+ * @throws IOException si problème pendant la sauvegarde
*/
protected void concactProperties(File in, File out) throws IOException {
- Properties propertiesIn = new SortedProperties();
+ Properties propertiesIn = new I18nProperties();
propertiesIn.load(new FileInputStream(in));
-
- Properties propertiesOut = new SortedProperties();
+
+ I18nProperties propertiesOut = new I18nProperties();
propertiesOut.load(new FileInputStream(out));
propertiesOut.putAll(propertiesIn);
- propertiesOut.store(new FileOutputStream(out), null);
+ propertiesOut.store(out);
}
/**
- * Construit une chaine de log format�e.
+ * Construit une chaine de log formatée.
*
* @param msg le prefix du message
- * @param nbFiles le nombre de fichiers actuellement trait�s
+ * @param nbFiles le nombre de fichiers actuellement traités
* @param time le time de traitement de ce fichier
* @param all le temps de traitement de tous les fichiers
- * @return la chaine de log format�e
+ * @return la chaine de log formatée
*/
protected String getLogEntry(String msg, int nbFiles, long time, long all) {
long now = System.nanoTime();
long delta = now - time;
- String s = "["+artifactId+"] i18n."+getClass().getSimpleName() + " : " + msg;
+ String s = "[" + artifactId + "] i18n." + getClass().getSimpleName() + " : " + msg;
if (time > 0) {
- s += " (" + StringUtil.convertTime(delta) + ")";
+ s += " (" + PluginHelper.convertTime(delta) + ")";
}
if (all > 0 && nbFiles > -1) {
- s += "(total time:" + StringUtil.convertTime(now - all) + ") ( ~ " + StringUtil.convertTime(((now - all) / (nbFiles + 1))) + " / file)";
+ s += "(total time:" + PluginHelper.convertTime(now - all) + ") ( ~ " + PluginHelper.convertTime(((now - all) / (nbFiles + 1))) + " / file)";
}
return s;
}
- /** Taille du buffer pour les lectures/�critures */
+ /** Taille du buffer pour les lectures/écritures */
protected static final int BUFFER_SIZE = 8 * 1024;
}
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Generate.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Generate.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Generate.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -21,18 +21,16 @@
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
-import org.codelutin.util.FileUtil;
-import org.codelutin.util.PropertiesDateRemoveFilterStream;
-import org.codelutin.util.SortedProperties;
+import org.codelutin.i18n.plugin.PluginHelper;
+import org.codelutin.i18n.plugin.PluginHelper.I18nProperties;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/**
- * Merge des fichiers de propri�t�s avec les anciens.
+ * Merge des fichiers de propriétés avec les anciens.
*
* @author julien
* @goal gen
@@ -49,40 +47,49 @@
for (String bundle : bundles) {
try {
// Merge
- File bundleSrc = new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
- File bundleOut = new File(out.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ //File bundleSrc = new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ //File bundleOut = new File(out.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ File bundleSrc = PluginHelper.getI18nFile(src, artifactId, bundle, false);
+ File bundleOut = PluginHelper.getI18nFile(out, artifactId, bundle, false);
if (bundleSrc.exists()) {
+
Properties propertiesSrc = new Properties();
propertiesSrc.load(new FileInputStream(bundleSrc));
- Properties propertiesBundle = new SortedProperties();
- propertiesBundle.load(new FileInputStream(bundleOut));
+ I18nProperties propertiesOut = new I18nProperties();
- // Parcours des cl�s
- for (Object key : propertiesBundle.keySet()) {
- Object oldKey = propertiesBundle.get(key);
+ if (!strictMode) {
+ // push back in bundle out, all the bundle src keys
+ propertiesOut.putAll(propertiesSrc);
+ }
+ propertiesOut.load(new FileInputStream(bundleOut));
+
+ // Parcours des clés
+ for (Object key : propertiesOut.keySet()) {
+ Object oldKey = propertiesOut.get(key);
Object value = propertiesSrc.get(oldKey);
- // R�cup�ration de la cl� si elle a �t� renomm�
+ // Récupération de la clé si elle a été renommée
if (!key.equals(oldKey) && value == null) {
value = propertiesSrc.get(key);
}
if (value != null) {
- propertiesBundle.put(key, value);
+ propertiesOut.put(key, value);
} else {
- propertiesBundle.put(key, "");
+ propertiesOut.put(key, "");
}
}
- FileOutputStream fileOutputStream = new FileOutputStream(bundleOut);
- PropertiesDateRemoveFilterStream filter = new PropertiesDateRemoveFilterStream(fileOutputStream);
- propertiesBundle.store(filter, null);
+ //saveBundle(bundleOut, propertiesOut);
+ propertiesOut.store(bundleOut);
+
// Sauvegarde avant copie
if (genSrc && keepBackup) {
- FileUtil.copy(bundleSrc, new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties" + "~"));
+ PluginHelper.copy(bundleSrc, PluginHelper.getI18nFileBackup(src, artifactId, bundle));
+ //FileUtil.copy(bundleSrc, new File(src.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties" + "~"));
}
getLog().info("Merge bundle " + bundleSrc.getAbsolutePath());
@@ -90,7 +97,7 @@
if (genSrc) {
// Copie des fichiers dans les sources
- FileUtil.copy(bundleOut, bundleSrc);
+ PluginHelper.copy(bundleOut, bundleSrc);
getLog().info("Copy bundle " + bundleSrc.getAbsolutePath());
}
@@ -100,4 +107,10 @@
}
}
}
+
+ /*void saveBundle(File bundleOut, Properties propertiesBundle) throws IOException {
+ FileOutputStream fileOutputStream = new FileOutputStream(bundleOut);
+ PropertiesDateRemoveFilterStream filter = new PropertiesDateRemoveFilterStream(fileOutputStream);
+ propertiesBundle.store(filter, null);
+ }*/
}
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Getter.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Getter.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Getter.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -19,19 +19,18 @@
package org.codelutin.i18n.plugin.core;
-import java.io.File;
-import java.io.IOException;
-
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.util.DirectoryScanner;
-import org.codelutin.util.FileUtil;
+import org.codelutin.i18n.plugin.PluginHelper;
+import java.io.File;
+import java.io.IOException;
+
/**
- * R�cup�re les diff�rents fichiers des parsers en un fichier de propri�t�s.
- *
+ * Récupère les différents fichiers des parsers en un fichier de propriétés.
+ *
* @author julien
- *
* @goal get
* @phase generate-resources
*/
@@ -45,16 +44,17 @@
try {
File bundleGetters = new File(out.getAbsolutePath() + File.separatorChar + artifactId + ".properties");
bundleGetters.createNewFile();
-
+
DirectoryScanner ds = new DirectoryScanner();
ds.setBasedir(out);
- ds.setIncludes(new String[] {"*.getter"});
+ ds.setIncludes(new String[]{"*.getter"});
ds.scan();
String[] files = ds.getIncludedFiles();
- // Fusion des fichiers propri�t�s des diff�rents parsers
+ // Fusion des fichiers propriétés des différents parsers
for (String file : files) {
- File bundleGetter = new File(out.getAbsolutePath() + File.separatorChar + file);
+ File bundleGetter = PluginHelper.getGetterFile(out, file, false);
+ //File bundleGetter = new File(out.getAbsolutePath() + File.separatorChar + file);
concactProperties(bundleGetter, bundleGetters);
if (genSrc) {
bundleGetter.delete();
@@ -62,13 +62,14 @@
getLog().info("Create bundle with " + bundleGetter.getAbsolutePath());
}
- // Cr�ation des bundles
+ // Création des bundles
for (String bundle : bundles) {
- File bundleOut = new File(out.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
- FileUtil.copy(bundleGetters, bundleOut);
+ //File bundleOut = new File(out.getAbsolutePath() + File.separatorChar + artifactId + "-" + bundle + ".properties");
+ File bundleOut = PluginHelper.getI18nFile(out, artifactId, bundle, false);
+ PluginHelper.copy(bundleGetters, bundleOut);
getLog().info("Generate bundle " + bundleOut.getAbsolutePath());
}
-
+
bundleGetters.delete();
} catch (IOException e) {
getLog().error("File Error I/O ", e);
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Parser.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Parser.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/Parser.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -20,30 +20,31 @@
package org.codelutin.i18n.plugin.core;
import java.io.File;
+import java.io.IOException;
/**
- * Interface type pour la d�finition d'un nouveau parser.
+ * Interface type pour la définition d'un nouveau parser.
* <p/>
- * Une implantation abstraite est propos�e : {@link AbstractI18nParser}.
+ * Une implantation abstraite est proposée : {@link AbstractI18nParser}.
*
* @author julien
*/
public interface Parser {
/** Lancement du parser */
- public void parse();
+ public void parse() throws IOException;
/**
* Parse sur un fichier
*
- * @param file le fichier � parser
+ * @param file le fichier à parser
*/
public void parseFile(File file);
/**
* Parse une partie du fichier
*
- * @param file le fichier � parser
+ * @param file le fichier à parser
* @param args ? TODO
*/
public void parseLine(File file, String args);
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserEvent.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserEvent.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserEvent.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -22,7 +22,7 @@
import java.io.File;
/**
- * Permet d'ajouter des �v�nements sur les parsers
+ * Permet d'ajouter des évènements sur les parsers
*
* @author julien
*
@@ -30,26 +30,26 @@
public interface ParserEvent {
/**
- * M�thode appel�e quand on change de fichier pars�
+ * M�thode appelée quand on change de fichier parsé
* @param file
*/
public void eventChangeFile(File file);
/**
- * M�thode appel�e apr�s le parsing du fichier
+ * Méthode appelée après le parsing du fichier
* @param file
*/
public void eventNextFile(File file);
/**
- * M�thode appel�e quand on change de cl�
+ * M�thode appelée quand on change de clé
* @param keyI18n
* @param newKey
*/
public void eventChangeKey(String keyI18n, boolean newKey);
/**
- * M�thode appel�e pour r�cup�rer la nouvelle valeur de cl�
+ * M�thode appelée pour récupérer la nouvelle valeur de clé
* @return
*/
public String eventGetRealKey();
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserException.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserException.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/core/ParserException.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -20,7 +20,7 @@
package org.codelutin.i18n.plugin.core;
/**
- * Permet la gestion des exceptions dans les parsers et dans les �v�nements
+ * Permet la gestion des exceptions dans les parsers et dans les évènements
*
* @author julien
*
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJava.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJava.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJava.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -19,36 +19,19 @@
package org.codelutin.i18n.plugin.extension;
-import org.apache.maven.artifact.Artifact;
import org.apache.maven.project.MavenProject;
import org.codelutin.i18n.plugin.core.AbstractI18nParser;
import org.codelutin.i18n.plugin.core.ParserEvent;
import org.codelutin.i18n.plugin.core.ParserException;
-import org.codelutin.i18n.plugin.core.SourceEntry;
import org.codelutin.processor.filters.I18nFilter;
-import org.codelutin.util.FileUtil;
-import java.io.BufferedOutputStream;
-import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
-import java.io.OutputStream;
-import java.lang.annotation.Annotation;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.regex.Pattern;
/**
- * R�cup�ration des cha�ne � traduire depuis les fichiers java.
+ * Récupération des chaine a traduire depuis les fichiers java.
*
* @author julien
* @goal parserJava
@@ -69,33 +52,21 @@
protected File defaultBasedir;
/**
- * @description D�pendance du projet.
+ * @description Dependance du projet.
* @parameter default-value="${project}"
* @readonly
*/
protected MavenProject project;
/**
- * @description R�pertoire sources des fichiers i18n.
+ * @description Repertoire sources des fichiers i18n.
* @parameter expression="${i18n.cp}" default-value="${basedir}/target/classes"
* @required
*/
protected File cp;
- /**
- * @description pour utiliser l'annotation I18nable pour traiter les fichiers
- * @parameter expression="${i18n.ea}" default-value="false"
- */
- protected boolean ea;
+ //protected List<String> annotationClass;
- /**
- * @description pour d�couvrir les fichiers I18nable.
- * @parameter expression="${i18n.detectea}" default-value="false"
- */
- protected boolean detectea;
-
- protected List<String> annotationClass;
-
protected String[] getDefaultIncludes() {
return new String[]{defaultIncludes};
}
@@ -119,33 +90,40 @@
protected I18nFilter filter;
- protected URLClassLoader loader;
- protected Annotation annotation;
+ //protected URLClassLoader loader;
+ //protected Annotation annotation;
@Override
public void init() {
super.init();
filter = new I18nFilter();
- if (detectea) {
+ /*if (detectea) {
// in detect mode, we do not filter by ea, try all files
ea = false;
}
if (ea) {
// in ea mode, we do not detect anything
detectea = false;
- }
+ }*/
- if (ea || detectea) {
+ /*if (ea || detectea) {
loader = initClassLoader();
annotationClass = initAnnotations();
- }
+ }*/
}
- protected List<String> initAnnotations() {
- return Collections.singletonList("org.codelutin.i18n.I18nable");
+ protected boolean isFileUptodate(File basedir, File file1, String file) {
+ String clazzFile = file.substring(0, file.length() - 4) + "class";
+ File clazz = new File(cp + File.separator + clazzFile);
+
+ return clazz.exists() && file1.lastModified() < clazz.lastModified();
}
- @Override
+ /*protected List<String> initAnnotations() {
+ return Collections.singletonList("org.codelutin.i18n.I18nable");
+ }*/
+
+ /*@Override
protected String[] getFilesForEntry(SourceEntry entry) {
if (detectea || !ea) {
@@ -155,29 +133,28 @@
// filter by annotation
return entry.getIncludedFiles(getDefaultBasedir(), getDefaultIncludes(), loader, annotationClass, getLog());
- }
+ }*/
/*
* (non-Javadoc)
* @see org.codelutin.i18n.plugin.core.Parser#parseFile(java.io.File)
*/
+
public void parseFile(File srcFile) {
try {
- int size = result.size();
- parseFile0(srcFile);
-
- // D�tection de nouvelles cl�s, sauvegarde du fichier pour pouvoir le restaurer en cas de plantage
- if (size != result.size()) {
- saveProperties0();
+ LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(srcFile)));
+ while (lnr.ready()) {
+ String line = lnr.readLine();
+ parseLine(srcFile, line);
}
- if (touchFile && detectea) {
+ /*if (touchFile && detectea) {
Annotation annotation = currentEntry.getAnnotation(srcFile, loader, annotationClass, getLog());
if (annotation == null) {
addAnnotation(srcFile);
}
- }
+ }*/
} catch (Exception e) {
throw new ParserException(e);
}
@@ -209,7 +186,7 @@
}
}
- private void addAnnotation(File srcFile) throws IOException {
+ /*private void addAnnotation(File srcFile) throws IOException {
String classname = srcFile.getName();
@@ -249,30 +226,18 @@
outputStream.close();
}
}
- }
+ }*/
- protected void saveProperties0() throws IOException {
- OutputStream outputStream = null;
- try {
- outputStream = new BufferedOutputStream(new FileOutputStream(out.getAbsolutePath() + File.separatorChar + getOutGetter()));
- result.store(outputStream, null);
- } finally {
- if (outputStream != null) {
- outputStream.close();
- }
- }
- }
-
- protected void parseFile0(File srcFile) throws IOException {
+ /*protected void parseFile0(File srcFile) throws IOException {
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(new FileInputStream(srcFile)));
while (lnr.ready()) {
String line = lnr.readLine();
parseLine(srcFile, line);
}
- }
+ }*/
- @SuppressWarnings({"unchecked"})
- protected URLClassLoader initClassLoader() {
+ /*@SuppressWarnings({"unchecked"})
+ private URLClassLoader initClassLoader() {
URLClassLoader loader = null;
if (project != null) {
URLClassLoader result;
@@ -309,5 +274,5 @@
}
}
return loader;
- }
+ }*/
}
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaActionConfig.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaActionConfig.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaActionConfig.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -21,8 +21,6 @@
import org.codelutin.i18n.plugin.core.ParserEvent;
import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -52,20 +50,21 @@
return "java-action-config.getter";
}
- @Override
+ /*@Override
protected List<String> initAnnotations() {
- List<String> result = new ArrayList<String>(1);
- result.add("jaxx.runtime.builder.ActionConfig");
- result.add("jaxx.runtime.builder.SelectActionConfig");
- result.add("jaxx.runtime.builder.TabContentConfig");
- result.add("jaxx.runtime.builder.ToggleActionConfig");
+ List<String> result = new ArrayList<String>(4);
+ result.add("org.codelutin.jaxx.action.ActionConfig");
+ result.add("org.codelutin.jaxx.action.SelectActionConfig");
+ result.add("org.codelutin.jaxx.action.TabContentConfig");
+ result.add("org.codelutin.jaxx.action.ToggleActionConfig");
return result;
- }
+ }*/
/*
* (non-Javadoc)
* @see org.codelutin.i18n.plugin.extension.XmlParser#extract(java.lang.String)
*/
+
public String extract(String i18nString) {
Matcher matcher = MATCH_PATTERN.matcher(i18nString.trim());
if (matcher.matches()) {
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaTabConfig.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaTabConfig.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJavaTabConfig.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -14,8 +14,6 @@
*/
package org.codelutin.i18n.plugin.extension;
-import java.util.Collections;
-
/**
* Un paseur java pour scanner les annotations TabContentConfig.
*
@@ -30,9 +28,9 @@
return "java-tab-config.getter";
}
- @Override
+ /*@Override
protected java.util.List<String> initAnnotations() {
return Collections.singletonList("org.codelutin.i18n.I18nable");
- }
+ }*/
}
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJaxx.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJaxx.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserJaxx.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -19,8 +19,10 @@
package org.codelutin.i18n.plugin.extension;
+import java.io.File;
+
/**
- * R�cup�ration des cha�ne � traduire depuis les fichiers xml Jaxx.
+ * Récupération des chaine à traduire depuis les fichiers xml Jaxx.
*
* @author julien
* @goal parserJaxx
@@ -35,7 +37,7 @@
protected String defaultIncludes;
/**
- * @description R�gles xml.
+ * @description Règles xml.
* @parameter expression="${i18n.rulesJaxx}" default-value="jaxx.rules"
*/
protected String rulesJaxx;
@@ -44,6 +46,10 @@
return new String[]{defaultIncludes};
}
+ protected boolean isFileUptodate(File basedir, File file1, String file) {
+ return false;
+ }
+
protected String getOutGetter() {
return "jaxx.getter";
}
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserSwixat.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserSwixat.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserSwixat.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -19,8 +19,10 @@
package org.codelutin.i18n.plugin.extension;
+import java.io.File;
+
/**
- * R�cup�ration des cha�ne � traduire depuis les fichiers xml Swixat.
+ * Récupération des chaines à traduire depuis les fichiers xml Swixat.
*
* @author julien
* @goal parserSwixat
@@ -35,7 +37,7 @@
protected String defaultIncludes;
/**
- * @description R�gles xml.
+ * @description R�gles xml.
* @parameter expression="${i18n.rulesSwixat}" default-value="swixat.rules"
*/
protected String rulesSwixat;
@@ -44,7 +46,11 @@
return new String[]{defaultIncludes};
}
+ protected boolean isFileUptodate(File basedir, File file1, String file) {
+ return false;
+ }
+
protected String getKeyModifierStart() {
return "=\\s*[\"\']";
}
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserXml.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserXml.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/extension/ParserXml.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -34,19 +34,17 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.OutputStream;
/**
- * R�cup�ration des cha�ne � traduire depuis les fichiers xml.
+ * Récupération des chaines à traduire depuis les fichiers xml.
*
* @author julien
*/
public abstract class ParserXml extends AbstractI18nParser {
- /** Taille du buffer pour les lectures/�critures */
+ /** Taille du buffer pour les lectures/écritures */
protected static final int BUFFER_SIZE = 8 * 1024;
/**
@@ -71,7 +69,7 @@
/** @return le fichier des rules */
protected abstract String getFileRules();
- /** @return le fichier des rules de base � toujours charger */
+ /** @return le fichier des rules de base à toujours charger */
protected abstract String getCoreFileRules();
@Override
@@ -88,12 +86,12 @@
*/
public void parseFile(File file) {
NodeList list;
- InputSource inputSource = new InputSource(file.getAbsolutePath()); // TODO: A d�placer pour les performances
+ InputSource inputSource = new InputSource(file.getAbsolutePath()); // TODO: A d�placer pour les performances
try {
int size = result.size();
- // Recherche des cl�s � partir d'un xpath
+ // Recherche des clés à partir d'un xpath
XPathExpression expression = xpath.compile(rules);
list = (NodeList) expression.evaluate(inputSource, XPathConstants.NODESET);
@@ -102,10 +100,11 @@
parseLine(file, node.getTextContent());
}
- // D�tection de nouvelles cl�s, sauvegarde du fichier pour pouvoir le restaurer en cas de plantage
+ // Détection de nouvelles clés, sauvegarde du fichier pour pouvoir le restaurer en cas de plantage
if (size != result.size()) {
- OutputStream xmlparserOut = new FileOutputStream(out.getAbsolutePath() + File.separatorChar + getOutGetter());
- result.store(xmlparserOut, null);
+ saveProperties0();
+ //OutputStream xmlparserOut = new FileOutputStream(out.getAbsolutePath() + File.separatorChar + getOutGetter());
+ //result.store(xmlparserOut, null);
}
} catch (Exception e) {
throw new ParserException(e);
@@ -139,10 +138,10 @@
}
/**
- * R�cup�re le xpath � partir d'un fichier
+ * Récupère le xpath à partir d'un fichier
*
- * @param fileRules le nom du fichier contant les r�gles
- * @return le xpath � partir d'un fichier
+ * @param fileRules le nom du fichier contant les règles
+ * @return le xpath à partir d'un fichier
*/
private String getRules(String fileRules) {
StringBuilder result = new StringBuilder();
@@ -211,7 +210,7 @@
*
* @param in le flux entrant
* @return le contenu du flux
- * @throws IOException si probl�me de lecture dans flux entrant
+ * @throws IOException si problème de lecture dans flux entrant
*/
private String readInputStream(InputStream in) throws IOException {
StringBuilder sb = new StringBuilder();
@@ -225,7 +224,7 @@
String result = sb.toString().trim();
result = result.replaceAll("#.*\n", ""); // suppression des commentaires
result = result.replaceAll("\\s+", " | "); // contruction du xpath avec des ou
- result = result.replaceAll("(^ \\| )|( \\| $)", ""); // suppression des ou de d�but ee fin
+ result = result.replaceAll("(^ \\| )|( \\| $)", ""); // suppression des ou de début ee fin
return result;
}
}
Modified: tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/ui/KeysModifier.java
===================================================================
--- trunk/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/ui/KeysModifier.java 2008-07-31 21:07:05 UTC (rev 955)
+++ tags/04082008_beforeUTF8/maven-i18n-plugin/src/main/java/org/codelutin/i18n/plugin/ui/KeysModifier.java 2008-08-04 11:30:42 UTC (rev 962)
@@ -19,6 +19,15 @@
package org.codelutin.i18n.plugin.ui;
+import org.codelutin.i18n.plugin.PluginHelper;
+import org.codelutin.i18n.plugin.core.ParserEvent;
+import org.codelutin.i18n.plugin.core.ParserException;
+
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JTextField;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
@@ -33,32 +42,22 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JTextField;
-
-import org.codelutin.i18n.plugin.core.ParserEvent;
-import org.codelutin.i18n.plugin.core.ParserException;
-import org.codelutin.util.FileUtil;
-
/**
- * IHM permettant de modifier les cl�s de traduction en direct dans les fichiers
- * pars�s et les fichiers de propri�t�s.
- *
+ * IHM permettant de modifier les clés de traduction en direct dans les fichiers
+ * parsés et les fichiers de propriétés.
+ *
* @author julien
- *
*/
public class KeysModifier extends JFrame implements ParserEvent {
private static final long serialVersionUID = 1L;
-
- // Modification des cl�s dans le fichier
+
+ // Modification des clés dans le fichier
protected List<String> newKeys;
protected boolean needModifiedFile;
protected String patternLeft;
protected String patternRight;
+ protected String encoding;
// Interface
protected JLabel name = new JLabel();
@@ -66,33 +65,33 @@
protected JTextField key = new JTextField();
protected JTextField pattern = new JTextField(".*");
protected JCheckBox onlyNewKey = new JCheckBox();
+
+
protected JButton next = new JButton("Next >>");
+ private static KeysModifier keysModifier;
-
- private static KeysModifier keysModifier;
-
/**
- * Rc�cup�ration d'une instance de l'interface
- * @param patternLeft
- * @param patternRight
- * @return
+ * Récupération d'une instance de l'interface
+ *
+ * @param patternLeft left pattern
+ * @param patternRight right pattern
+ * @param encoding encoding
+ * @return the shared instance with new config
*/
- public static KeysModifier getInstance(String patternLeft, String patternRight) {
- if(keysModifier == null) {
+ public static KeysModifier getInstance(String patternLeft, String patternRight, String encoding) {
+ if (keysModifier == null) {
keysModifier = new KeysModifier();
}
-
+
+
+ keysModifier.encoding = encoding;
keysModifier.patternLeft = patternLeft;
keysModifier.patternRight = patternRight;
-
+
return keysModifier;
}
-
- /**
- * Contructeur de l'interface
- * @param patternLeft
- * @param patternRight
- */
+
+ /** Contructeur de l'interface */
private KeysModifier() {
setLayout(new GridLayout(9, 2, 10, 10));
@@ -142,7 +141,7 @@
path.setText(file.getPath());
key.setText("");
repaint();
-
+
newKeys = new ArrayList<String>();
needModifiedFile = false;
}
@@ -152,12 +151,12 @@
* @see org.codelutin.i18n.plugin.core.ParserEvent#eventNextFile(java.io.File)
*/
public void eventNextFile(File file) {
- if(needModifiedFile) {
+ if (needModifiedFile) {
String content = "";
int region = 0;
try {
- content = FileUtil.readAsString(file);
+ content = PluginHelper.readAsString(file, encoding);
} catch (IOException e) {
throw new ParserException(e);
}
@@ -174,22 +173,22 @@
}
try {
- FileUtil.writeString(file, content);
+ PluginHelper.writeString(file, content, encoding);
} catch (IOException e) {
throw new ParserException(e);
}
}
}
-
+
/*
- * (non-Javadoc)
- * @see org.codelutin.i18n.plugin.core.ParserEvent#eventChangeKey(java.lang.String)
- */
+ * (non-Javadoc)
+ * @see org.codelutin.i18n.plugin.core.ParserEvent#eventChangeKey(java.lang.String)
+ */
public synchronized void eventChangeKey(String keyI18n, boolean newKey) {
key.setText(keyI18n);
newKeys.add(key.getText());
repaint();
- if(isVisible() && keyI18n.matches(pattern.getText()) && (!onlyNewKey.isSelected() || newKey)) {
+ if (isVisible() && keyI18n.matches(pattern.getText()) && (!onlyNewKey.isSelected() || newKey)) {
try {
wait();
} catch (InterruptedException e) {
@@ -208,36 +207,42 @@
return key.getText();
}
- /**
- * Action sur le boutton pour passer � la cl� suivante
- */
+ /** Action sur le boutton pour passer � la cl� suivante */
class EventNextKey implements ActionListener {
public void actionPerformed(ActionEvent e) {
eventNextKey();
}
}
- /**
- * Action sur la fermeture de la frame
- */
+ /** Action sur la fermeture de la frame */
class EventWindows implements WindowListener {
- public void windowClosed(WindowEvent e) {}
- public void windowActivated(WindowEvent e) {}
+ public void windowClosed(WindowEvent e) {
+ }
+
+ public void windowActivated(WindowEvent e) {
+ }
+
public void windowClosing(WindowEvent e) {
setVisible(false);
eventNextKey();
}
- public void windowDeactivated(WindowEvent e) {}
- public void windowDeiconified(WindowEvent e) {}
- public void windowIconified(WindowEvent e) {}
- public void windowOpened(WindowEvent e) {}
+ public void windowDeactivated(WindowEvent e) {
+ }
+
+ public void windowDeiconified(WindowEvent e) {
+ }
+
+ public void windowIconified(WindowEvent e) {
+ }
+
+ public void windowOpened(WindowEvent e) {
+ }
+
}
- /**
- * Permet de passer � la cl� suivante
- */
+ /** Permet de passer à la clé suivante */
public synchronized void eventNextKey() {
notifyAll();
}
1
0
Author: tchemit
Date: 2008-08-04 11:30:40 +0000 (Mon, 04 Aug 2008)
New Revision: 961
Added:
tags/04082008_beforeUTF8/
Log:
before UTF8
1
0
Author: tchemit
Date: 2008-08-04 11:29:49 +0000 (Mon, 04 Aug 2008)
New Revision: 960
Removed:
tags/before_0-4_and_UTF8/
Log:
1
0
[Lutinutil-commits] r959 - tags/before_0-4_and_UTF8
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
by tchemit@users.labs.libre-entreprise.org 04 Aug '08
04 Aug '08
Author: tchemit
Date: 2008-08-04 11:29:21 +0000 (Mon, 04 Aug 2008)
New Revision: 959
Added:
tags/before_0-4_and_UTF8/maven-i18n-plugin/
Log:
tag before version 0-4 and project in UTF-8
Copied: tags/before_0-4_and_UTF8/maven-i18n-plugin (from rev 958, trunk/maven-i18n-plugin)
1
0
Author: tchemit
Date: 2008-08-04 11:29:18 +0000 (Mon, 04 Aug 2008)
New Revision: 958
Added:
tags/before_0-4_and_UTF8/
Log:
tag before version 0-4 and project in UTF-8
1
0
[Lutinutil-commits] r957 - trunk/lutinutil/src/main/java/org/codelutin/i18n
by bpoussin@users.labs.libre-entreprise.org 01 Aug '08
by bpoussin@users.labs.libre-entreprise.org 01 Aug '08
01 Aug '08
Author: bpoussin
Date: 2008-08-01 14:22:01 +0000 (Fri, 01 Aug 2008)
New Revision: 957
Added:
trunk/lutinutil/src/main/java/org/codelutin/i18n/I18nf.java
Log:
ajout d'une nouvelle classe qui utilise String.format au lieu
de MessageFormat
Added: trunk/lutinutil/src/main/java/org/codelutin/i18n/I18nf.java
===================================================================
--- trunk/lutinutil/src/main/java/org/codelutin/i18n/I18nf.java (rev 0)
+++ trunk/lutinutil/src/main/java/org/codelutin/i18n/I18nf.java 2008-08-01 14:22:01 UTC (rev 957)
@@ -0,0 +1,84 @@
+/* *##%
+ * Copyright (C) 2002-2008 Code Lutin, Benjamin Poussin
+ *
+ * This program is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU General Public License
+ * as published by the Free Software Foundation; either version 2
+ * of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+ * USA.
+ *##%*/
+
+package org.codelutin.i18n;
+
+
+import java.util.Arrays;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Transition class during project switch between MessageFormat.format syntax
+ * to String.format syntax.
+ *
+ * @author poussin
+ * @version $Revision$
+ *
+ * Last update: $Date$
+ * by : $Author$
+ */
+public class I18nf extends I18n {
+
+ /** to use log facility, just put in your code: log.info(\"...\"); */
+ static private Log log = LogFactory.getLog(I18nf.class);
+ /**
+ * Retourne la chaine traduite si possible.
+ *
+ * @param message message formate avec la meme syntaxe que {@link String#format}
+ * @param args les parametres pour le message.
+ * @return la traduction si possible ou la chaine passee en parametre
+ * sinon.
+ */
+ public static String _(String message, Object... args) {
+ String result = message;
+ Language language = loader == null ? null : loader.getLanguage();
+ if (language != null) {
+ result = language.translate(message);
+ }
+ try {
+ return applyFilter(String.format(result, args));
+ } catch (Exception eee) {
+ try {
+ return applyFilter(String.format(message, args));
+ } catch (Exception zzz) {
+ log.warn(I18n._("lutinutil.error.i18n.untranslated.message", message));
+ return applyFilter(message);
+ }
+ }
+ }
+
+ /**
+ * Retourne la chaine passée en argument.
+ *
+ * @param message message formate avec la meme syntaxe que {@link
+ * MessageFormat}
+ * @param args les parametres pour le message.
+ * @return le message passe en argument mais formatte
+ * avec les parametres
+ */
+ public static String n_(String message, Object... args) {
+ try {
+ return String.format(message, args);
+ } catch (Exception eee) {
+ log.warn(I18n._("lutinutil.error.i18n.unformated.message", message, Arrays.toString(args)));
+ return message;
+ }
+ }
+}
1
0