[Lutinutil-commits] r1548 - in nuitonutil/trunk/src: main/java/org/nuiton main/java/org/nuiton/i18n main/java/org/nuiton/log main/java/org/nuiton/util main/java/org/nuiton/util/config main/resources/META-INF/services test/java/org/nuiton test/java/org/nuiton/i18n test/java/org/nuiton/i18n/bundle test/java/org/nuiton/log test/java/org/nuiton/util test/resources/compress/simulation/exports test/resources/compress/simulation/scripts test/resources/compress/simulation/simulators
Author: tchemit Date: 2009-05-14 05:40:24 +0000 (Thu, 14 May 2009) New Revision: 1548 Added: nuitonutil/trunk/src/main/java/org/nuiton/i18n/ nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18n.java nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nBundleBridge.java nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nLoader.java nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nf.java nuitonutil/trunk/src/main/java/org/nuiton/i18n/Language.java nuitonutil/trunk/src/main/java/org/nuiton/i18n/LocaleEditor.java nuitonutil/trunk/src/main/java/org/nuiton/log/ nuitonutil/trunk/src/main/java/org/nuiton/log/Log4JWrapper.java nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLog.java nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogEvent.java nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogFactory.java nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogListener.java nuitonutil/trunk/src/main/java/org/nuiton/log/LutinProgressEvent.java nuitonutil/trunk/src/main/java/org/nuiton/log/MonitorMapper.java nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressMonitorFrame.java nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressState.java nuitonutil/trunk/src/main/java/org/nuiton/log/UserLog.java nuitonutil/trunk/src/main/java/org/nuiton/log/package.html nuitonutil/trunk/src/main/java/org/nuiton/util/ nuitonutil/trunk/src/main/java/org/nuiton/util/ApplicationConfig.java nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParser.java nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserDefaultOption.java nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserException.java nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserOption.java nuitonutil/trunk/src/main/java/org/nuiton/util/ArrayUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedList.java nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedListOutOfBoundsException.java nuitonutil/trunk/src/main/java/org/nuiton/util/CallAnalyse.java nuitonutil/trunk/src/main/java/org/nuiton/util/CardinalityHelper.java nuitonutil/trunk/src/main/java/org/nuiton/util/CategorisedListenerSet.java nuitonutil/trunk/src/main/java/org/nuiton/util/ClassLoaderUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/CollectionUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/ConverterUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/DigestGenerator.java nuitonutil/trunk/src/main/java/org/nuiton/util/EnumConverter.java nuitonutil/trunk/src/main/java/org/nuiton/util/EnumEditor.java nuitonutil/trunk/src/main/java/org/nuiton/util/ExceptionUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/FileCompletion.java nuitonutil/trunk/src/main/java/org/nuiton/util/FileUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverter.java nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverterFactory.java nuitonutil/trunk/src/main/java/org/nuiton/util/FormatMap.java nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtilException.java nuitonutil/trunk/src/main/java/org/nuiton/util/H2TypeEnum.java nuitonutil/trunk/src/main/java/org/nuiton/util/HashList.java nuitonutil/trunk/src/main/java/org/nuiton/util/IOUtils.java nuitonutil/trunk/src/main/java/org/nuiton/util/LRUMapMultiKey.java nuitonutil/trunk/src/main/java/org/nuiton/util/ListenerSet.java nuitonutil/trunk/src/main/java/org/nuiton/util/Log.java nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingException.java nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingPatternFormatter.java nuitonutil/trunk/src/main/java/org/nuiton/util/MD5.java nuitonutil/trunk/src/main/java/org/nuiton/util/MD5InputStream.java nuitonutil/trunk/src/main/java/org/nuiton/util/MD5OutputStream.java nuitonutil/trunk/src/main/java/org/nuiton/util/MD5State.java nuitonutil/trunk/src/main/java/org/nuiton/util/MonthEnum.java nuitonutil/trunk/src/main/java/org/nuiton/util/ObjectUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java nuitonutil/trunk/src/main/java/org/nuiton/util/RecursiveProperties.java nuitonutil/trunk/src/main/java/org/nuiton/util/ReflectUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/Resource.java nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceException.java nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceNotFoundException.java nuitonutil/trunk/src/main/java/org/nuiton/util/SimplePaginationEnum.java nuitonutil/trunk/src/main/java/org/nuiton/util/SortedProperties.java nuitonutil/trunk/src/main/java/org/nuiton/util/StreamKeywordTokenizer.java nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtilException.java nuitonutil/trunk/src/main/java/org/nuiton/util/Tbz2Util.java nuitonutil/trunk/src/main/java/org/nuiton/util/TransformedList.java nuitonutil/trunk/src/main/java/org/nuiton/util/Transformer.java nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteSoftReference.java nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteWeakReference.java nuitonutil/trunk/src/main/java/org/nuiton/util/URIConverter.java nuitonutil/trunk/src/main/java/org/nuiton/util/URLConverter.java nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumber.java nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberConverter.java nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/ZipStreamEncoder.java nuitonutil/trunk/src/main/java/org/nuiton/util/ZipUtil.java nuitonutil/trunk/src/main/java/org/nuiton/util/config/ nuitonutil/trunk/src/main/java/org/nuiton/util/config/Config.java nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfig.java nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfigProperty.java nuitonutil/trunk/src/main/java/org/nuiton/util/config/Property.java nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleConfig.java nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleIdentityConfig.java nuitonutil/trunk/src/main/java/org/nuiton/util/package.html nuitonutil/trunk/src/test/java/org/nuiton/i18n/ nuitonutil/trunk/src/test/java/org/nuiton/i18n/I18nLoaderTest.java nuitonutil/trunk/src/test/java/org/nuiton/i18n/bundle/ nuitonutil/trunk/src/test/java/org/nuiton/i18n/bundle/I18nBundleManagerTest.java nuitonutil/trunk/src/test/java/org/nuiton/log/ nuitonutil/trunk/src/test/java/org/nuiton/log/LutinLogTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/ nuitonutil/trunk/src/test/java/org/nuiton/util/ApplicationConfigTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/CallAnalyseTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/CardinalityHelperTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/CategorisedListenerSetTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/CollectionUtilTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/ConverterUtilTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/FileCompletionTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/FileUtilTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/LRUMapMultiKeyTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/ListenerSetTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/LogTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/ObjectUtilTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/RecursivePropertiesTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/ResourceTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/StreamKeywordTokenizerTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/StringUtilTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/Tbz2UtilTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/TransparenteReferenceTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/VersionNumberUtilTest.java nuitonutil/trunk/src/test/java/org/nuiton/util/ZipUtilTest.java Modified: nuitonutil/trunk/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory nuitonutil/trunk/src/test/resources/compress/simulation/exports/Abundances.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/Biomasses.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/CapturesNombre.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/CapturesPoids.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/CellsDefinition.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/EffortsMetier.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/MetierZone.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/NonActivite.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/OwnerMargin.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/RegionDefinition.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/RejetsNombre.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/RejetsPoids.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/VesselMargin.java nuitonutil/trunk/src/test/resources/compress/simulation/exports/ZonesDefinition.java nuitonutil/trunk/src/test/resources/compress/simulation/scripts/GravityModel.java nuitonutil/trunk/src/test/resources/compress/simulation/scripts/ResultName.java nuitonutil/trunk/src/test/resources/compress/simulation/scripts/SiMatrix.java nuitonutil/trunk/src/test/resources/compress/simulation/simulators/DefaultSimulator.java Log: migrate to nuiton Copied: nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18n.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/i18n/I18n.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18n.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18n.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,353 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * I18n.java + * + * Created: 2 d?c. 2003 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +package org.nuiton.i18n; + +import org.nuiton.i18n.I18nFilter; +import java.net.URL; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.logging.Logger; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.ConverterUtil; + +/** + * This class is a facility for internationalization. To use it in your soft, + * you can either : + * <ul> + * <li> import the org.codelutin.i18n.I18n class, + * <li> init the translation support with the init(String language) or + * init(String language, String country), init(Localelocale) static methods in your main, ( eg: + * I18n.init("fr","FR") ) + * <li> call the translate static method for each sentence, ( eg: + * I18n._("hello you !") ) + * <li> create a resource file for each language following the naming + * convention given in the java.util.ResourceBundle javadoc and translate all + * the sentence. + * </ul> + * + * @author poussin + * @author chemit + * created 2 decembre 2003 + */ +public class I18n { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static Log log = LogFactory.getLog(I18n.class); + public static final String ISO_8859_1_ENCONDING = "ISO-8859-1"; + public static final String UTF_8_ENCONDING = "UTF-8"; + public static final String DEFAULT_ENCODING = ISO_8859_1_ENCONDING; + public static final Locale DEFAULT_LOCALE = Locale.UK; + /** la classe responsable du chargement des ressources */ + static I18nLoader loader; + /** la gestionnaire de bundle */ +// static I18nBundleManager bundleManager; + /** Filtre a appliquer avant de retourner les chaines */ + protected static I18nFilter filter; + /** Indique le chemin du fichier dans lequel ecrire les entrees non trouvees */ + protected static String recordFilePath; + /** + * some extra urls to given to bundle manager. + * <p/> + * Note: use this before call <code>init(...)</code> methods + */ + static URL[] extraURL; + /** + * le nom d'un unique bundle à utiliser. + * + * Si l'on positionne cette propriété, on n'utilisera pas la recherche + * classique des bunldes à charger mais on se contentera de rechercher + * le bundle (et ses entrées) à cet emplacement + * <code>META-INF/uniqueBundleName-XXX.properties</code>. + * + * Cela permet de chargement I18n en une seule fois et de ne scruter qu'un + * seul jar (ou repertoire)... + * + * Un goal dans le plugin i18n (i18n:bundle) permet de construire le bundle + * englobant toutes les autres traductions avec gestion des dépendances. + * + * @since 1.0.6 + */ + protected static String uniqueBundleName; + + /** Initialise la librairie avec encoding par defaut et locale par defaut */ + public static void init() { + init(null); + } + + /** + * Initialize the library for given <code>locale</code with {@link #DEFAULT_ENCODING}. + * + * @param locale language to use + */ + public static void init(Locale locale) { + if (locale == null) { + locale = newLocale(null, null); + } + getLoader().setLanguage(locale); + } + + /** + * Initialise la librairie + * + * @param language une chaine representant la langue à utiliser fr, en, ... + * @param country une chaine representant le pays à utiliser FR, GB, ... + */ + public static void init(String language, String country) { + init(newLocale(language, country)); + } + + /** + * Retourne la chaine traduite si possible. + * + * @param message la chaine a traduire + * @return la traduction si possible ou la chaine passee en parametre + * sinon. + */ + public static String _(String message) { + if (loader == null || loader.getLanguage() == null) { + return applyFilter(message); + } + return applyFilter(loader.getLanguage().translate(message)); + } + + /** + * 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), zzz); + return applyFilter(message); + } + } + } + + /** + * Retourne la chaine passée en argument. + * + * @param message message formate avec la meme syntaxe que {@link + * java.text.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)), eee); + return message; + } + } + + /** + * Retourne la chaine passé en argument + * + * @param message la chaine à traduire + * @return la chaine passée en argument + * sinon. + */ + public static String n_(String message) { + return message; + } + + public static String getRecordFilePath() { + return recordFilePath; + } + + /** @return the array of extra url to include in bundle search */ + public static URL[] getExtraURL() { + return extraURL == null ? new URL[0] : extraURL; + } + + /** + *@return the unique bundle name to use for loading of system + * + * @since 1.0.6 + */ + public static String getUniqueBundleName() { + return uniqueBundleName; + } + + /** + * Change le filtre des chaines traduites + * + * @param filter l'objet filtre a utiliser + */ + public static void setFilter(I18nFilter filter) { + I18n.filter = filter; + } + + public static void setRecordFilePath(String recordFilePath) { + I18n.recordFilePath = recordFilePath; + } + + /** + * Change extra urls to use in bundle discovering + * <p/> + * Note: <b>This method will close the i18n system.</b> + * + * @param extraURL new extra urls to use + */ + public static void setExtraURL(URL[] extraURL) { + I18n.extraURL = extraURL; + // must reset loader urls + I18nLoader.urls = null; + // and close system + close(); + } + + /** + * Change the unique bunlde name to use + * <p/> + * Note: <b>This method will close the i18n system.</b> + * + * @param uniqueBundleName the new unique bundle pattern to use + * + * @since 1.0.6 + */ + public static void setUniqueBundleName(String uniqueBundleName) { + I18n.uniqueBundleName = uniqueBundleName; + // must reset loader urls + I18nLoader.urls = null; + // and close system + close(); + } + + /** + * close i18n caches, says the loader if exists + * <p/> + * This method should be called to reset all caches (languages, bundles,...) + */ + public static void close() { + if (loader != null) { + loader.close(); + loader = null; + } + } + + /** + * Applique le filtre s'il y en a un + * + * @param message le message qui devrait etre retourne avant application du + * filtre. + * @return le message filtre + */ + protected static String applyFilter(String message) { + if (getFilter() != null) { + return getFilter().applyFilter(message); + } + return message; + } + + protected static I18nFilter getFilter() { + return filter; + } + + /** + * Get the i18n loader. + * <p/> + * If no loader found, then instanciate a new one. + * + * @return the instanciated i18n loader + */ + public static synchronized I18nLoader getLoader() { + + if (loader == null) { + loader = new I18nLoader(DEFAULT_LOCALE, uniqueBundleName); + } + return loader; + } + + /** + * Parse a list of {@link Locale} seperated by comma. + * + * Example : fr_FR,en_GB + * + * @param str the string representation of locale separated by comma + * @return list of available locales + * @throws IllegalArgumentException ia a locale is not valid + */ + public static Locale[] parseLocales(String str) throws IllegalArgumentException { + List<Locale> result = new java.util.ArrayList<Locale>(); + String[] bundlesToUse = str.split(","); + for (int i = 0, j = bundlesToUse.length; i < j; i++) { + String s = bundlesToUse[i].trim(); + // on devrait verifier que le bundle existe + try { + Locale l = ConverterUtil.convert(Locale.class, s); + result.add(l); + } catch (Exception e) { + throw new IllegalArgumentException("bundle " + s + " is not a valid locale,e"); + } + } + return result.toArray(new Locale[result.size()]); + } + + public static Locale newLocale(String str) { + if (str == null) { + // get use locale + return newLocale(null, null); + } + try { + return ConverterUtil.convert(Locale.class, str); + } catch (Exception e) { + Logger.getLogger("org.codelutin.i18n.I18n").warning("could not load locale '" + str + " for reason : " + e.getMessage()); + // use default locale + return DEFAULT_LOCALE; + } + } + + public static Locale newLocale(String language, String country) { + if (language == null) { + // get user locale + language = System.getProperty("user.language", DEFAULT_LOCALE.getLanguage()); + country = System.getProperty("user.country", DEFAULT_LOCALE.getCountry()); + } + return newLocale(language + (country == null ? "" : '_' + country)); + } +} //I18n Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18n.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nBundleBridge.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/i18n/I18nBundleBridge.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nBundleBridge.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nBundleBridge.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,44 @@ +/* **##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * +* BundleBridge.java +* +* Created: 6 sept. 06 +* +* @author Arnaud Thimel <thimel@codelutin.com> +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.nuiton.i18n; + +public class I18nBundleBridge extends java.util.ResourceBundle { + + @Override + public java.util.Enumeration<String> getKeys() { + throw new UnsupportedOperationException(); + } + + @Override + public Object handleGetObject(String key) { + return I18n._(key); + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nBundleBridge.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nLoader.java (from rev 1544, nuitonutil/trunk/src/main/java/org/codelutin/i18n/I18nLoader.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nLoader.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nLoader.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,345 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.i18n; + +import java.net.URL; +import java.net.URLClassLoader; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import org.nuiton.i18n.bundle.I18nBundle; +import org.nuiton.i18n.bundle.I18nBundleEntry; +import org.nuiton.i18n.bundle.I18nBundleFactory; +import org.nuiton.util.ClassLoaderUtil; +import org.nuiton.util.Resource; +import org.nuiton.util.StringUtil; + +/** + * Classe responsible of loading of I18n system. + * <p/> + * Contains the current used {@link #language} (can be null, if not set), and the list of already loaded {@link #languages}. + * <p/> + * <p/> + * Note: <b>Init methods are package acces and should not be used alone, but within {@link I18n} class <code>init(XXX)</code> methods.</b> + * + * @author chemit + */ +public class I18nLoader { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static final Log log = LogFactory.getLog(I18nLoader.class); + /** le language actuellement utilise */ + protected Language language; + /** le cache de languages deja charges */ + protected List<Language> languages; + /** le cache des urls de recheche des bundles */ + protected static URL[] urls; + /** le cache de bundles deja charges */ + protected I18nBundle[] bundles; + /** la locale par defaut a utiliser */ + protected final Locale defaultLocale; + /** le nom de l'unique bunlde a charger (mode unique) */ + protected final String uniqueBundleName; + + public I18nLoader(Locale defaultLocale) { + this(defaultLocale, null); + } + + public I18nLoader(Locale defaultLocale, String uniqueBundleName) { + this.defaultLocale = defaultLocale; + this.uniqueBundleName = uniqueBundleName; + } + + /** @return current language loaded or null, if no language was load */ + public Language getLanguage() { + return language; + } + + /** @return le cache de language avec instanciation paresseuse */ + public List<Language> getLanguages() { + if (languages == null) { + languages = new ArrayList<Language>(); + } + return languages; + } + + public Locale getDefaultLocale() { + return defaultLocale; + } + + public boolean isEmpty() { + checkInit(); + boolean isEmpty = I18nBundleFactory.isEmpty(bundles); + return isEmpty; + } + + /** @return array of all locales loaded */ + public Locale[] getLocales() { + checkInit(); + Locale[] result = I18nBundleFactory.getLocales(bundles); + return result; + } + + public I18nBundle[] getBundles() { + checkInit(); + return bundles; + } + + public I18nBundle[] getBundles(Locale l) { + checkInit(); + I18nBundle[] result = I18nBundleFactory.getBundles(l, bundles); + return result; + } + + public I18nBundleEntry[] getBundleEntries() { + checkInit(); + I18nBundleEntry[] result = I18nBundleFactory.getBundleEntries(bundles); + return result; + } + + public I18nBundleEntry[] getBundleEntries(Locale l) { + checkInit(); + I18nBundleEntry[] result = I18nBundleFactory.getBundleEntries(l, defaultLocale, bundles); + return result; + } + + void init() { + + if (isInit()) { + // already init + return; + } + + // get all bundles urls + if (urls == null || urls.length == 0) { + + // cache this expensive search + + if (uniqueBundleName != null) { + // on recherche directement un bundle precis a aprtir + // de son fichier de definition + urls = I18nBundleFactory.getURLs(uniqueBundleName); + if (urls == null) { + log.warn("coudl not find uniqueBundleName i18n " + uniqueBundleName); + } + } + if (urls == null) { + // on utilise le mecanisme de recherche des bundles dans toutes + // les entrees du classloader + urls = getURLs(Language.getLoader(), I18n.getExtraURL()); + } + } + + long t0 = System.nanoTime(); + + // detect bundles + List<I18nBundle> bundleDetected = I18nBundleFactory.detectBundles(urls); + + // save bundles in cache + this.bundles = bundleDetected.toArray(new I18nBundle[bundleDetected.size()]); + + log.info(bundleDetected.size() + " bundle(s) found, [" + getBundleEntries().length + " file(s)] in " + StringUtil.convertTime(System.nanoTime() - t0)); + } + + /** + * Set a new language in loader, given a locale. + * + * @param locale la locale du language requis + * @param bundleManager bundle manager to used + */ + synchronized void setLanguage(Locale locale) { + init(); + if (log.isDebugEnabled()) { + log.debug("locale: " + locale); + } + Language result = getLanguage(locale); + if (result == null) { + result = addLanguage(locale); + } else { + log.debug("using cached language : " + result); + } + language = result; + } + + /** + * Close loader and release cache ofg language. + * <p/> + * Current language will be also clean. + */ + void close() { + if (languages != null) { + log.info("nb languages loaded : " + languages.size()); + for (Language l : languages) { + l.close(); + } + languages.clear(); + languages = null; + } + if (urls != null) { + urls = null; + } + if (bundles != null) { + bundles = null; + } + language = null; + } + + /** + * @param locale la locale du language recherche + * @return le language trouve dans le cache, ou null. + */ + Language getLanguage(Locale locale) { + + if (!(languages == null || languages.isEmpty())) { + for (Language l : languages) { + if (locale.equals(l.getLocale())) { + return l; + } + } + } + return null; + } + + Language addLanguage(Locale locale) { + Language result; + result = new Language(locale); + long t0 = System.nanoTime(); + I18nBundleEntry[] entries = getBundleEntries(locale); + result.load(entries); + log.info(result + ", nbEntries: " + entries.length + ", nbSentences: " + result.size() + " in " + StringUtil.convertTime(System.nanoTime() - t0)); + getLanguages().add(result); + return result; + } + + boolean isInit() { + return bundles != null; + } + + void checkInit() { + if (!isInit()) { + throw new IllegalStateException("should call init method on " + I18nLoader.class); + } + } + + /** + * Detecte les urls de toutes les entrees de bunbles sur tout un classLoader. + * + * Il s'agit du mode initialie de detection des entréés de bundles, i.e des + * fichiers de traductions. + * + * <b>Note: </b> Cette methode devient couteuse des que le classLoader + * contient de nombreuses entrées. Il est meiux d'utiliser le second type + * de chargement qui n'utilise qu'un seul fichier de traduction unifié. + * + * @param loader le classloader a utiliser pour trouver les resources. + * @return les urls des entrees de bundles + */ + public static URL[] getURLs(URLClassLoader loader) { + try { + // on calcule toutes les urls utilisable dans le classloader donnee + List<URL> urlToSeek = new ArrayList<URL>(); + urlToSeek.addAll(Arrays.asList(ClassLoaderUtil.getDeepURLs(loader))); + + // on va maintenant supprimer toutes les urls qui ne respectent pas + // le pattern i18n : il faut que la resource contienne un repertoire i18n + // ce simple test permet de restreindre la recherche des resources + // i18n qui est tres couteuse + int size = urlToSeek.size(); + for (Iterator<URL> it = urlToSeek.iterator(); it.hasNext();) { + URL url = it.next(); + if (!Resource.containsDirectDirectory(url, I18nBundleFactory.DIRECTORY_SEARCH_BUNDLE_PATTERN)) { + if (log.isDebugEnabled()) { + log.debug("skip url with no " + I18nBundleFactory.DIRECTORY_SEARCH_BUNDLE_PATTERN + " directory : " + url); + } + it.remove(); + } + } + if (log.isDebugEnabled()) { + log.debug("detect " + urlToSeek.size() + " i18n capable url (out of " + size + ")"); + } + // on effectue la recherche des urls des resources i18n (tous les + // fichiers de traductions) sur toutes les urls precedemment calculees) + List<URL> result = Resource.getURLs(I18nBundleFactory.SEARCH_BUNDLE_PATTERN, urlToSeek.toArray(new URL[urlToSeek.size()])); + if (log.isDebugEnabled()) { + for (URL url : result) { + log.debug(url.toString()); + } + } + return result.toArray(new URL[result.size()]); + } catch (Exception eee) { + log.warn("Unable to find urls for loader : " + loader + " for reason " + eee.getMessage(), eee); + return new URL[0]; + } + } + + /** + * Recherche la liste des url de toutes les resources i18n, i.e les urls + * des fichiers de traduction. + * + * @param loader le classLoader où trouver les bundles + * @param extraUrl des urls de resources i18n deja calcule, à ajouter au resultat sans traitement particulier + * @return la liste des urls de bundle i18n pour la langue donné + */ + public static URL[] getURLs(URLClassLoader loader, URL... extraUrl) { + + try { + // on calcule toutes les urls utilisable dans le classloader donnee + List<URL> urlToSeek = new ArrayList<URL>(); + urlToSeek.addAll(Arrays.asList(ClassLoaderUtil.getDeepURLs(loader))); + // on ajoute les urls de resources i18n donnes + if (extraUrl.length > 0) { + urlToSeek.addAll(Arrays.asList(extraUrl)); + } + // on va maintenant supprimer toutes les urls qui ne respectent pas + // le pattern i18n : il faut que la resource contienne un repertoire i18n + // ce simple test permet de restreindre la recherche des resources + // i18n qui est tres couteuse + int size = urlToSeek.size(); + for (Iterator<URL> it = urlToSeek.iterator(); it.hasNext();) { + URL url = it.next(); + if (!Resource.containsDirectDirectory(url, I18nBundleFactory.DIRECTORY_SEARCH_BUNDLE_PATTERN)) { + if (log.isDebugEnabled()) { + log.debug("skip url with no " + I18nBundleFactory.DIRECTORY_SEARCH_BUNDLE_PATTERN + " directory : " + url); + } + it.remove(); + } + } + if (log.isDebugEnabled()) { + log.debug("detect " + urlToSeek.size() + " i18n capable url (out of " + size + ")"); + } + // on effectue la recherche des urls des resources i18n (tous les + // fichiers de traductions) sur toutes les urls precedemment calculees) + List<URL> result = Resource.getURLs(I18nBundleFactory.SEARCH_BUNDLE_PATTERN, urlToSeek.toArray(new URL[urlToSeek.size()])); + if (log.isDebugEnabled()) { + for (URL url : result) { + log.debug(url.toString()); + } + } + return result.toArray(new URL[result.size()]); + } catch (Exception eee) { + log.warn("Unable to find urls for loader : " + loader + " for reason " + eee.getMessage(), eee); + return new URL[0]; + } + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nLoader.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nf.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/i18n/I18nf.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nf.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nf.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,34 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +package org.nuiton.i18n; + +/** + * Transition class during project switch between MessageFormat.format syntax + * to String.format syntax. + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + * + * @deprecated Use I18n class instead. + */ +public class I18nf extends I18n { + +} \ No newline at end of file Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/i18n/I18nf.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/i18n/Language.java (from rev 1544, nuitonutil/trunk/src/main/java/org/codelutin/i18n/Language.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/i18n/Language.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/i18n/Language.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,205 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/** + * Language.java + */ + +package org.nuiton.i18n; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URLClassLoader; +import java.util.Enumeration; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.i18n.bundle.I18nBundleEntry; +import org.nuiton.util.RecursiveProperties; + +/** + * This class is used by the i18n class. It encapsulates the translation + * resource for a given language. + * <p/> + * Encoding to be used to read properties files will be ISO-8859-1 since java does it like this. + */ +public class Language { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static final Log log = LogFactory.getLog(Language.class); + + public static URLClassLoader getLoader() { + ClassLoader loader = Language.class.getClassLoader(); + if (loader instanceof URLClassLoader) { + return (URLClassLoader) loader; + } + log.warn("could not find the URLClassLoader : "+loader); + return null; + } + + /** toutes les traductions pour cette langue */ + protected Properties resource; + + /** la locale de la langue */ + protected Locale locale; + + /** @param l the current locale of the language */ + public Language(Locale l) { + this.locale = l; + } + + /** + * charge les traductions de la languea partir d'une liste donnee de + * fichiers de traduction. + * + * @param bundleEntries the used bundles entries to load + */ + public void load(I18nBundleEntry[] bundleEntries) { + + resource = new RecursiveProperties(); + + try { + for (I18nBundleEntry e : bundleEntries) { + e.load(resource); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + /** + * translate takes a sentence and returns its translation if found, the very + * same string otherwise. + * + * @param sentence sentence to translate + * @return translated sentence + */ + public String translate(String sentence) { + if (resource == null) { + recordNotFound(sentence); + return sentence; + } + try { + String result = resource.getProperty(sentence); + if (null != result && !"".equals(result)) { + return result; + } + recordNotFound(sentence); + return sentence; + } catch (MissingResourceException eee) { + log.warn("Resource " + sentence + " unavailable", eee); + return sentence; + } catch (Exception eee) { + log.error("Unexpected error while translating : ", eee); + return sentence; + } + } + + private void recordNotFound(String key) { + if (I18n.recordFilePath != null && key != null && !"".equals(key)) { + File f = new File(I18n.recordFilePath); + Properties recordProps = new Properties(); + try { + if (f.exists()) { + FileInputStream fis = new FileInputStream(f); + recordProps.load(fis); + fis.close(); + } + recordProps.put(key, ""); + FileOutputStream fos = new FileOutputStream(f); + recordProps.store(fos, "Adding the key : " + key); + fos.close(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + /** + * untranslate takes a translated sentence and returns the original one if + * found, the very same string otherwise. + * + * @param sentence sentence to untranslate + * @return untranslated sentence + */ + public String untranslate(String sentence) { + if (resource == null) { + return sentence; + } + try { + Enumeration<?> e = resource.propertyNames(); + // Look for the given sentence through all translations + while (e.hasMoreElements()) { + String key = (String) e.nextElement(); + String translation = resource.getProperty(key); + // If found returns the corresponding key + if (sentence.equals(translation)) { + return key; + } + } + } catch (MissingResourceException eee) { + // Well, this can't happen... + } + // No such translated sentence in our resourceBundle + return sentence; + } + + public Locale getLocale() { + return locale; + } + + public int size() { + return resource == null ? 0 : resource.size(); + } + + public void close() { + if (resource != null) { + log.info(this); + resource.clear(); + resource = null; + } + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + close(); + } + + @Override + public boolean equals(Object o) { + return this == o || o instanceof Language && locale.equals(((Language) o).locale); + } + + @Override + public int hashCode() { + return locale.hashCode(); + } + + @Override + public String toString() { + return "Language <locale: " + locale + ",nbStences:" + (size()) + ">"; + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/i18n/Language.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/i18n/LocaleEditor.java (from rev 1544, nuitonutil/trunk/src/main/java/org/codelutin/i18n/LocaleEditor.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/i18n/LocaleEditor.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/i18n/LocaleEditor.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,57 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.i18n; + +import javax.swing.JComboBox; +import java.util.Locale; + +/** + * A {@link Locale} editor. + * <p/> + * use the static method to have an instance of editor {@link #newEditor(java.util.Locale[])} + * <p/> + * If no locale is given to this method, it will go and seek via + * {@link org.codelutin.i18n.I18nLoader#getLocales()} all loaded locales in i18n system + * + * @author chemit + */ +public class LocaleEditor extends JComboBox { + + /** serialVersionUID */ + private static final long serialVersionUID = -6777873426011538807L; + + protected Locale[] type; + + public static LocaleEditor newEditor(Locale... type) { + return new LocaleEditor(type); + } + + public LocaleEditor(Locale... type) { + super(buildModel(type)); + } + + protected static Locale[] buildModel(Locale... type) { + if (type.length > 0) { + return type; + } + // get availables locales registred in I18n system + type = I18n.getLoader().getLocales(); + return type; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/i18n/LocaleEditor.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/Log4JWrapper.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/Log4JWrapper.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/Log4JWrapper.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/Log4JWrapper.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,83 @@ +/* **##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * Log4JWrapper.java + * + * Created: 10 janv. 07 17:07:54 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.log; + +import org.apache.commons.logging.impl.Log4JLogger; +import org.apache.log4j.Level; + + +/** + * Cette classe n'est utile que parce qu'on ne peut pas modifier le FQCN present + * dans {@link Log4JLogger}. Donc sans cette classe on n'a pas le bon nom + * de classe.method et numero de ligne dans la sortie du log. + * + * @author poussin + */ +public class Log4JWrapper { + + private static Level traceLevel; + + static { + // Releases of log4j1.2 >= 1.2.12 have Priority.TRACE available, earlier + // versions do not. If TRACE is not available, then we have to map + // calls to Log.trace(...) onto the DEBUG level. + + try { + traceLevel = (Level)Level.class.getDeclaredField("TRACE").get(null); + } catch(Exception ex) { + // ok, trace not available + traceLevel = Level.DEBUG; + } + } + + + final static private String FQCN = LutinLog.class.getName() + "."; + + static public void fatal(Log4JLogger log, Object msg, Throwable eee) { + log.getLogger().log(FQCN, Level.FATAL, msg, eee); + } + static public void error(Log4JLogger log, Object msg, Throwable eee) { + log.getLogger().log(FQCN, Level.ERROR, msg, eee); + } + static public void warn(Log4JLogger log, Object msg, Throwable eee) { + log.getLogger().log(FQCN, Level.WARN, msg, eee); + } + static public void info(Log4JLogger log, Object msg, Throwable eee) { + log.getLogger().log(FQCN, Level.INFO, msg, eee); + } + static public void debug(Log4JLogger log, Object msg, Throwable eee) { + log.getLogger().log(FQCN, Level.DEBUG, msg, eee); + } + static public void trace(Log4JLogger log, Object msg, Throwable eee) { + log.getLogger().log(FQCN, traceLevel, msg, eee); + } +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/Log4JWrapper.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLog.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/LutinLog.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLog.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLog.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,455 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + + + +package org.nuiton.log; + +import java.awt.Component; +import java.awt.HeadlessException; +import java.util.TimerTask; + +import javax.swing.SwingUtilities; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.impl.Log4JLogger; + +/** + * LutinLog.java + * + * Created: 9 sept. 06 03:53:09 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + * + * @deprecated on 20090327 this class seam to produce a frame on each + * log call (produce huge memory consumption) + */ +public class LutinLog implements Log { + + private LutinLogFactory factory = null; + private Log parent = null; + private long activeProgressMonitorTime; + private ProgressState progressState = ProgressState.end; + private long timeout = 0; + private int min; + private int max; + private int value; + private ProgressMonitorFrame progressMonitorFrame; + private TimerTask activeProgressMonitorTask = new TimerTask() { + @Override + public void run() { + if (SwingUtilities.isEventDispatchThread()) { + Component frame = getProgressMonitorFrame(); + if (frame != null) { + frame.setVisible(true); + } + } else { + SwingUtilities.invokeLater(this); + } + } + }; + + private TimerTask timeoutTask = new TimerTask() { + @Override + public void run() { + end(); + } + }; + + protected LutinLog(LutinLogFactory factory, Log parent) { + this.factory = factory; + this.parent = parent; + activeProgressMonitorTime = factory.getDefaultActiveProgressMonitorTime(); + timeout = factory.getDefaultTimeout(); + + // Force progressMonitorFrame instanciation to have good message + // displayed when frame is showing + getProgressMonitorFrame(); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + String result = "LutinLog min: " + getMin() + " value:" + getValue() + " max:" + getMax() + " timeout:" + getTimeout(); + return result; + } + + /////////////////////////////////////////////////////////////////////////// + // + // L I S T E N E R + // + /////////////////////////////////////////////////////////////////////////// + + public void addLutinLogListener(LutinLogListener l) { + factory.addLutinLogListener(this, l); + } + + public void removeLutinLogListener(LutinLogListener l) { + factory.removeLutinLogListener(this, l); + } + + /////////////////////////////////////////////////////////////////////////// + // + // F I R E E V E N T + // + /////////////////////////////////////////////////////////////////////////// + + protected void fireLogEvent(LutinLogEvent.LogType type, Object msg, Throwable eee) { + LutinLogEvent e = new LutinLogEvent(this, type, String.valueOf(msg), eee); + try { + factory.listeners.fire(this, "logEvent", e); + } catch (Exception eee1) { + if (parent.isDebugEnabled()) { + parent.debug("Can't fire event", eee1); + } + } + } + + protected void fireProgressEvent(LutinProgressEvent.ProgressType type) { + LutinProgressEvent e = new LutinProgressEvent(this, type); + try { + factory.listeners.fire(this, "progressEvent", e); + } catch (Exception eee1) { + if (parent.isDebugEnabled()) { + parent.debug("Can't fire event", eee1); + } + } + } + + /////////////////////////////////////////////////////////////////////////// + // + // P R O G R E S S + // + /////////////////////////////////////////////////////////////////////////// + + /** + * apres un start le temps avant de mettre le progress en marche (<=0 pour jamais) + * @param time time + */ + public void setActivateProgressMonitorTime(long time) { + activeProgressMonitorTime = time; + } + + /** + * une tache indique son debut + */ + public void start(){ + progressState = ProgressState.start; + value = -1; + + if (activeProgressMonitorTime > 0) { + factory.getTimer().schedule(activeProgressMonitorTask, activeProgressMonitorTime); + } + if (timeout > 0) { + factory.getTimer().schedule(timeoutTask, timeout); + } + fireProgressEvent(LutinProgressEvent.ProgressType.start); + } + /** + * @return ProgressMonitorFrame + */ + protected Component getProgressMonitorFrame() { + if (progressMonitorFrame == null) { + try { + progressMonitorFrame = new ProgressMonitorFrame(this, null); + } catch (HeadlessException he) { + //Unable to create frame + } + } + return progressMonitorFrame; + } + + /** + * Si on a demande a ce que la tache soit arretee. + * + * @return stopped state + */ + public boolean isAskStopTask() { + boolean result = progressState == ProgressState.stopAsked; + return result; + } + /** + * demande ou annule la demande de fin de tache + * @param v + */ + public void setAskStopTask(boolean v) { + if (progressState != ProgressState.end) { + if (v) { + progressState = ProgressState.stopAsked; + fireProgressEvent(LutinProgressEvent.ProgressType.askStop); + } else { + progressState = ProgressState.start; + fireProgressEvent(LutinProgressEvent.ProgressType.cancelAskStop); + } + } + } + + /** + * indique la fin complete d'une tache + */ + public void end() { + progressState = ProgressState.end; + activeProgressMonitorTask.cancel(); + timeoutTask.cancel(); + if (progressMonitorFrame != null) { + progressMonitorFrame.setVisible(false); + } + fireProgressEvent(LutinProgressEvent.ProgressType.end); + } + + /** + * Donne le timeout particulier pour une tache. + * + * @return timeout + */ + public long getTimeout() { + return timeout; + } + /** + * modifie le temps specifiquement pour une tache. A la fin du time out + * cela n'arrete pas la t�che mais arrete simplement de la suivre + * @param time + */ + public void setTimeout(long time) { + timeout = time; + } + public int getMin() { + return min; + } + /** + * une tache indique le min que peut prendre value + * @param value + */ + public void setMin(int value) { + min = value; + fireProgressEvent(LutinProgressEvent.ProgressType.min); + } + public int getMax() { + return max; + } + /** + * une tache indique le max que peut prendre value + * @param value + */ + public void setMax(int value) { + max = value; + fireProgressEvent(LutinProgressEvent.ProgressType.max); + } + public int getValue() { + return value; + } + /** + * la valeur courante pour la tache, -1 indique l'indetermination de la valeur + * @param value + */ + public void setValue(int value) { + this.value = value; + fireProgressEvent(LutinProgressEvent.ProgressType.value); + } + + /////////////////////////////////////////////////////////////////////////// + // + // L O G + // + /////////////////////////////////////////////////////////////////////////// + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#isTraceEnabled() + */ + public boolean isTraceEnabled() { + boolean result = parent.isTraceEnabled(); + return result; + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#isDebugEnabled() + */ + public boolean isDebugEnabled() { + boolean result = parent.isDebugEnabled(); + return result; + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#isInfoEnabled() + */ + public boolean isInfoEnabled() { + boolean result = parent.isInfoEnabled(); + return result; + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#isWarnEnabled() + */ + public boolean isWarnEnabled() { + boolean result = parent.isWarnEnabled(); + return result; + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#isErrorEnabled() + */ + public boolean isErrorEnabled() { + boolean result = parent.isErrorEnabled(); + return result; + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#isFatalEnabled() + */ + public boolean isFatalEnabled() { + boolean result = parent.isFatalEnabled(); + return result; + } + + public void user(Object msg) { + this.user(msg, null); + } + + public void user(Object msg, Throwable eee) { + if(isInfoEnabled()) { + if (parent instanceof Log4JLogger) { + Log4JWrapper.info(((Log4JLogger)parent), msg, eee); + } else { + parent.info(msg, eee); + } + } + fireLogEvent(LutinLogEvent.LogType.user, msg, eee); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#trace(java.lang.Object) + */ + public void trace(Object msg) { + this.trace(msg, null); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#trace(java.lang.Object, java.lang.Throwable) + */ + public void trace(Object msg, Throwable eee) { + if (parent instanceof Log4JLogger) { + Log4JWrapper.trace(((Log4JLogger)parent), msg, eee); + } else { + parent.trace(msg, eee); + } + fireLogEvent(LutinLogEvent.LogType.trace, msg, eee); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#debug(java.lang.Object) + */ + public void debug(Object msg) { + this.debug(msg, null); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#debug(java.lang.Object, java.lang.Throwable) + */ + public void debug(Object msg, Throwable eee) { + if (parent instanceof Log4JLogger) { + Log4JWrapper.debug(((Log4JLogger)parent), msg, eee); + } else { + parent.debug(msg, eee); + } + fireLogEvent(LutinLogEvent.LogType.debug, msg, eee); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#info(java.lang.Object) + */ + public void info(Object msg) { + this.info(msg, null); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#info(java.lang.Object, java.lang.Throwable) + */ + public void info(Object msg, Throwable eee) { + if (parent instanceof Log4JLogger) { + Log4JWrapper.info(((Log4JLogger)parent), msg, eee); + } else { + parent.info(msg, eee); + } + fireLogEvent(LutinLogEvent.LogType.info, msg, eee); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#warn(java.lang.Object) + */ + public void warn(Object msg) { + this.warn(msg, null); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#warn(java.lang.Object, java.lang.Throwable) + */ + public void warn(Object msg, Throwable eee) { + if (parent instanceof Log4JLogger) { + Log4JWrapper.warn(((Log4JLogger)parent), msg, eee); + } else { + parent.warn(msg, eee); + } + fireLogEvent(LutinLogEvent.LogType.warn, msg, eee); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#error(java.lang.Object) + */ + public void error(Object msg) { + this.error(msg, null); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#error(java.lang.Object, java.lang.Throwable) + */ + public void error(Object msg, Throwable eee) { + if (parent instanceof Log4JLogger) { + Log4JWrapper.error(((Log4JLogger)parent), msg, eee); + } else { + parent.error(msg, eee); + } + fireLogEvent(LutinLogEvent.LogType.error, msg, eee); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#fatal(java.lang.Object) + */ + public void fatal(Object msg) { + this.fatal(msg, null); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.Log#fatal(java.lang.Object, java.lang.Throwable) + */ + public void fatal(Object msg, Throwable eee) { + if (parent instanceof Log4JLogger) { + Log4JWrapper.fatal(((Log4JLogger)parent), msg, eee); + } else { + parent.fatal(msg, eee); + } + fireLogEvent(LutinLogEvent.LogType.fatal, msg, eee); + } + +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLog.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogEvent.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/LutinLogEvent.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogEvent.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogEvent.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,93 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * LutinLogEvent.java + * + * Created: 9 sept. 06 04:01:26 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.log; + +import java.util.EventObject; + + +/** @author poussin */ + +public class LutinLogEvent extends EventObject { + + /** */ + private static final long serialVersionUID = 1L; + + private LogType logType; + private String msg; + private Throwable eee; + private long time; + + static public enum LogType { + user, trace, debug, info, warn, error, fatal + } + + /** + * @param source + * @param logType + * @param msg + * @param eee + */ + public LutinLogEvent(Object source, LogType logType, String msg, Throwable eee) { + super(source); + this.logType = logType; + this.msg = msg; + this.eee = eee; + this.time = System.currentTimeMillis(); + } + + /* (non-Javadoc) + * @see java.util.EventObject#getSource() + */ + public LutinLog getLutinLog() { + return (LutinLog) super.getSource(); + } + + /** @return the logType */ + public LogType getLogType() { + return this.logType; + } + + /** @return the msg */ + public String getMsg() { + return this.msg; + } + + /** @return the eee */ + public Throwable getThrowable() { + return this.eee; + } + + /** @return the time */ + public long getTime() { + return this.time; + } +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogEvent.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogFactory.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/LutinLogFactory.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogFactory.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogFactory.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,240 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * LutinLogFactory.java + * + * Created: 9 sept. 06 03:45:29 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.log; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogConfigurationException; +import org.apache.commons.logging.LogFactory; +import org.apache.commons.logging.impl.LogFactoryImpl; +import org.nuiton.util.CategorisedListenerSet; + +import java.util.Timer; + + +/** @author poussin */ + +public class LutinLogFactory extends LogFactory { + + static private LutinLogFactory instance = null; + + protected LogFactory parentFactory = null; + protected CategorisedListenerSet<LutinLogListener> listeners = new CategorisedListenerSet<LutinLogListener>(); + protected long DefaultActiveProgressMonitorTime = 0; + protected long DefaultTimeout = 0; + + private Timer timer; + + static public LutinLogFactory getInstance() { + if (instance == null) { + LogFactory factory = LogFactory.getFactory(); + if (factory instanceof LutinLogFactory) { + instance = (LutinLogFactory) factory; + } else { + instance = new LutinLogFactory(); + } + } + return instance; + } + + static public LutinLog getLutinLog(Class<?> clazz) { + LutinLogFactory factory = LutinLogFactory.getInstance(); + LutinLog result = (LutinLog) factory.getInstance(clazz); + return result; + } + + static public LutinLog getLutinLog(String cat) { + LutinLogFactory factory = LutinLogFactory.getInstance(); + LutinLog result = (LutinLog) factory.getInstance(cat); + return result; + } + + /** @return the defaultActiveProgressMonitorTime */ + public long getDefaultActiveProgressMonitorTime() { + return this.DefaultActiveProgressMonitorTime; + } + + /** + * @param defaultActiveProgressMonitorTime + * the defaultActiveProgressMonitorTime to set + */ + public void setDefaultActiveProgressMonitorTime( + long defaultActiveProgressMonitorTime) { + this.DefaultActiveProgressMonitorTime = defaultActiveProgressMonitorTime; + } + + /** @return the defaultTimeout */ + public long getDefaultTimeout() { + return this.DefaultTimeout; + } + + /** @param defaultTimeout the defaultTimeout to set */ + public void setDefaultTimeout(long defaultTimeout) { + this.DefaultTimeout = defaultTimeout; + } + + /////////////////////////////////////////////////////////////////////////// + // + // L I S T E N E R + // + /////////////////////////////////////////////////////////////////////////// + + /** + * Add listener on all LutinLog + * + * @param l + */ + public void addLutinLogListener(LutinLogListener l) { + listeners.add(this, l); + } + + /** + * Add listener on specific LutinLog + * + * @param log + * @param l + */ + public void addLutinLogListener(LutinLog log, LutinLogListener l) { + listeners.addCategory(this, log); + listeners.add(log, l); + } + + /** + * Add listener on all LutinLog + * + * @param l + */ + public void removeLutinLogListener(LutinLogListener l) { + listeners.remove(this, l); + } + + /** + * Add listener on specific LutinLog + * + * @param log + * @param l + */ + public void removeLutinLogListener(LutinLog log, LutinLogListener l) { + listeners.remove(log, l); + } + + /** + * Return le réel commons-logging a utiliser + * + * @return the parentFactory + */ + protected LogFactory getParentFactory() { + if (this.parentFactory == null) { + this.parentFactory = new LogFactoryImpl(); + } + return this.parentFactory; + } + + /////////////////////////////////////////////////////////////////////////// + // + // C O M M O N S - L O G G I N G M E T H O D + // + /////////////////////////////////////////////////////////////////////////// + + /* (non-Javadoc) + * @see org.apache.commons.logging.LogFactory#getAttribute(java.lang.String) + */ + + @Override + public Object getAttribute(String arg0) { + Object result = getParentFactory().getAttribute(arg0); + return result; + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.LogFactory#getAttributeNames() + */ + @Override + public String[] getAttributeNames() { + String[] result = getParentFactory().getAttributeNames(); + return result; + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.LogFactory#getInstance(java.lang.Class) + */ + @Override + public Log getInstance(Class arg0) throws LogConfigurationException { + Log log = getParentFactory().getInstance(arg0); + Log result = new LutinLog(this, log); + listeners.addCategory(this, result); + return result; + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.LogFactory#getInstance(java.lang.String) + */ + @Override + public Log getInstance(String arg0) throws LogConfigurationException { + Log log = getParentFactory().getInstance(arg0); + Log result = new LutinLog(this, log); + listeners.addCategory(this, result); + return result; + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.LogFactory#release() + */ + @Override + public void release() { + getParentFactory().release(); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.LogFactory#removeAttribute(java.lang.String) + */ + @Override + public void removeAttribute(String arg0) { + getParentFactory().removeAttribute(arg0); + } + + /* (non-Javadoc) + * @see org.apache.commons.logging.LogFactory#setAttribute(java.lang.String, java.lang.Object) + */ + @Override + public void setAttribute(String arg0, Object arg1) { + getParentFactory().setAttribute(arg0, arg1); + } + + /** @return the logger timer */ + public Timer getTimer() { + if (timer == null) { + timer = new Timer("LutinLogTimer", true); + } + return timer; + } + +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogFactory.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogListener.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/LutinLogListener.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogListener.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogListener.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,45 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * LutinLogListener.java + * + * Created: 11 sept. 06 11:35:53 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.log; + +import java.util.EventListener; + + +/** @author poussin */ + +public interface LutinLogListener extends EventListener { + + public void progressEvent(LutinProgressEvent e); + + public void logEvent(LutinLogEvent e); + +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinLogListener.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinProgressEvent.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/LutinProgressEvent.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/LutinProgressEvent.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/LutinProgressEvent.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,70 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * LutinLogEvent.java + * + * Created: 9 sept. 06 04:01:26 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.log; + +import java.util.EventObject; + + +/** @author poussin */ + +public class LutinProgressEvent extends EventObject { + + /** */ + private static final long serialVersionUID = 1L; + private ProgressType type; + + static public enum ProgressType { + min, max, value, askStop, cancelAskStop, start, end + } + + /** + * @param source + * @param type + */ + public LutinProgressEvent(Object source, ProgressType type) { + super(source); + this.type = type; + } + + /* (non-Javadoc) + * @see java.util.EventObject#getSource() + */ + public LutinLog getLutinLog() { + return (LutinLog) super.getSource(); + } + + /** @return the type */ + public ProgressType getType() { + return this.type; + } + +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/LutinProgressEvent.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/MonitorMapper.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/MonitorMapper.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/MonitorMapper.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/MonitorMapper.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,237 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * MonitorMapper.java + * + * Created: 13 sept. 06 11:39:06 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.log; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.log.LutinProgressEvent.ProgressType; + +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JProgressBar; +import javax.swing.JTextField; +import javax.swing.SwingUtilities; +import java.awt.Button; +import java.awt.Component; +import java.awt.Container; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.beans.Statement; + + +/** + * Helper to monitor LutinLog. This class permit to say which component used + * to display text, which component used to display progress and what is the + * cancel button + * + * @author poussin + */ + +public class MonitorMapper implements LutinLogListener, ActionListener { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private Log log = LogFactory.getLog(MonitorMapper.class); + + protected LutinLog lutinLog; + protected Container parentContainer; + protected Component label; + protected JProgressBar progress; + protected Component cancel; + protected boolean changeCancelText; + + /** + * @param lutinLog LutinLog to monitor + * @param parentContainer component that contains all other component + * if not null, then when task begin setVisible(true) is called + * and when task end setVisible(false) is called + * @param label component that have setText method to display user log + * ({@link JLabel}, {@link JTextField}, ...) + * @param progress progress widget + * @param cancel componant that have addActionListener + * ({@link JButton},{@link Button}, ...) + * @param changeCancelText if true try to change text display in cancel + * component switch between "Cancel" and "Don't cancel" + */ + public MonitorMapper(LutinLog lutinLog, Container parentContainer, + Component label, JProgressBar progress, Component cancel, + boolean changeCancelText) { + this.lutinLog = lutinLog; + this.parentContainer = parentContainer; + this.label = label; + this.progress = progress; + this.cancel = cancel; + this.changeCancelText = changeCancelText; + + lutinLog.addLutinLogListener(this); + addActionListener(cancel, this); + } + + /** + * Try to call addActionListener on component, do nothing if call failed + * + * @param c + * @param action + */ + protected void addActionListener(Component c, ActionListener action) { + try { + if (c != null) { + Statement statement = new Statement(c, "addActionListener", new Object[]{action}); + statement.execute(); + } + } catch (Exception eee) { + if (log.isTraceEnabled()) { + log.trace("Can't modify call addActionListener on: " + c, eee); + } + } + } + + /** + * try to call setText on component, do nothing if call failed + * + * @param c + * @param text text to put in component + */ + protected void setText(Component c, String text) { + try { + if (c != null) { + Statement statement = new Statement(c, "setText", new Object[]{text}); + statement.execute(); + } + } catch (Exception eee) { + if (log.isTraceEnabled()) { + log.trace("Can't modify call setText on: " + c, eee); + } + } + } + + /* (non-Javadoc) + * @see org.codelutin.log.LutinLogListener#logEvent(org.codelutin.log.LutinLogEvent) + */ + public void logEvent(LutinLogEvent e) { + if (e.getLogType() == LutinLogEvent.LogType.user) { + SwingUtilities.invokeLater(new HandleLogEvent(e)); + } + } + + /* (non-Javadoc) + * @see org.codelutin.log.LutinLogListener#progressEvent(org.codelutin.log.LutinProgressEvent) + */ + public void progressEvent(LutinProgressEvent e) { + SwingUtilities.invokeLater(new HandleProgressEvent(e)); + } + + /* (non-Javadoc) + * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) + */ + public void actionPerformed(ActionEvent e) { + boolean oldValue = lutinLog.isAskStopTask(); + lutinLog.setAskStopTask(!oldValue); + } + + + /** + * Used to update UI + * + * @author poussin + */ + class HandleLogEvent implements Runnable { + protected LutinLogEvent e; + + public HandleLogEvent(LutinLogEvent e) { + this.e = e; + } + + public void run() { + setText(label, e.getMsg()); + } + } + + /** + * Used to update UI + * + * @author poussin + */ + class HandleProgressEvent implements Runnable { + protected LutinProgressEvent e; + + public HandleProgressEvent(LutinProgressEvent e) { + this.e = e; + } + + public void run() { + if (e.getType() == ProgressType.start) { + int min = e.getLutinLog().getMin(); + int max = e.getLutinLog().getMax(); + int value = e.getLutinLog().getValue(); + progress.setMinimum(min); + progress.setMaximum(max); + progress.setValue(value); + String text = value + " of " + max; // TODO i18n + progress.setString(text); + if (parentContainer != null) { + parentContainer.setVisible(true); + } + } else if (e.getType() == ProgressType.min) { + int min = e.getLutinLog().getMin(); + progress.setMinimum(min); + } else if (e.getType() == ProgressType.max) { + int max = e.getLutinLog().getMax(); + progress.setMaximum(max); + int value = e.getLutinLog().getValue(); + String text = value + " of " + max; // TODO i18n + progress.setString(text); + } else if (e.getType() == ProgressType.value) { + int max = e.getLutinLog().getMax(); + int value = e.getLutinLog().getValue(); + progress.setValue(value); + String text = value + " of " + max; // TODO i18n + progress.setString(text); + } else if (e.getType() == ProgressType.askStop) { + if (changeCancelText) { + setText(cancel, "Don't cancel"); // TODO i18n + } + } else if (e.getType() == ProgressType.cancelAskStop) { + if (changeCancelText) { + setText(cancel, "Cancel"); // TODO i18n + } + } else if (e.getType() == ProgressType.end) { + if (parentContainer != null) { + parentContainer.setVisible(false); + } + progress.setMinimum(0); + progress.setMaximum(0); + progress.setValue(0); + progress.setString(""); + } + } + } +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/MonitorMapper.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressMonitorFrame.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/ProgressMonitorFrame.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressMonitorFrame.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressMonitorFrame.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,94 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * ProgressMonitorFrame.java + * + * Created: 13 sept. 06 11:05:41 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.log; + +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JProgressBar; +import javax.swing.SwingConstants; +import javax.swing.WindowConstants; +import java.awt.Component; + +// 20060923 poussin FIXME we must can used i18n in util lib. (perhaps put i18n directly in util lib) +//import static org.codelutin.i18n.I18n._; + +/** @author poussin */ + +public class ProgressMonitorFrame extends JFrame { + + /** serialVersionUID */ + private static final long serialVersionUID = 3878314562707954612L; + protected LutinLog lutinLog; + protected JLabel label; + protected JProgressBar progress; + protected JButton cancel; + protected MonitorMapper monitorMapper; + + /** + * @param lutinLog log that ProgressMonitorFrame must monitor + * @param extraComponent optionnal (can be null) user component to put in + * frame + */ + public ProgressMonitorFrame(LutinLog lutinLog, Component extraComponent) { + super("ProgressMonitor"); + + this.lutinLog = lutinLog; + + Box box = Box.createVerticalBox(); + + if (extraComponent != null) { + box.add(extraComponent); + } + + label = new JLabel("Message"); + label.setHorizontalTextPosition(SwingConstants.CENTER); + box.add(label); + + progress = new JProgressBar(); + progress.setStringPainted(true); + box.add(progress); + + cancel = new JButton(); + cancel.setText("Cancel"); // TODO i18n + box.add(cancel); + + this.add(box); + this.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); + this.pack(); + + monitorMapper = new MonitorMapper(lutinLog, null, label, progress, cancel, true); + } + + +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressMonitorFrame.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressState.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/ProgressState.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressState.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressState.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,39 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * ProgressState.java + * + * Created: 11 sept. 06 12:41:41 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.log; + + +/** @author poussin */ + +public enum ProgressState { + start, stopAsked, end +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/ProgressState.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/UserLog.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/UserLog.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/UserLog.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/UserLog.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,233 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ + +package org.nuiton.log; + +import java.awt.GraphicsEnvironment; +import javax.swing.JOptionPane; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.ListenerSet; + +/** + * Classe permettant d'afficher facillement des messages a l'utilisateur. + * Si une interface graphique est disponible alors des boites de dialogue + * sont affichees. Il est aussi possible d'indique des composants a utiliser + * pour afficher les messages. N'importe quel composant ayant une methode + * setText convient + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ +public class UserLog { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static Log log = LogFactory.getLog(UserLog.class); + + public static enum Level { + DEBUG, INFO, WARN, ERROR, FATAL + } + + protected static ListenerSet<Object> listeners = new ListenerSet<Object>(); + protected static boolean graphicUI = true; + + public static void addListeners(ListenerSet<Object> l) { + listeners.add(l); + } + + public static void removeListeners(ListenerSet<Object> l) { + listeners.remove(l); + } + + /** + * Enable/disable UI log display. + * + * @param graphicUI <tt>true</tt> to enable + */ + public static void setGraphicUI(boolean graphicUI) { + UserLog.graphicUI = graphicUI; + } + + /** + * Return true if UI login is enabled and available. + * + * @return graphicUI enable + */ + public static boolean isGraphicUI() { + return graphicUI && !GraphicsEnvironment.isHeadless(); + } + + /** + * Appel la methode setText de tous les listeners avec le message en + * parametre et si {@link #isGraphicUI} retourne vrai affiche une boite + * de dialogue avec le message + * + * @param level le niveau du message + * @param msg le message + * @param cause l'exception s'il y en a une + */ + protected static void show(Level level, String msg, Throwable cause) { + try { + listeners.fire("setText", msg); + } catch (Exception e) { + log.warn("Can't call setText on listener", e); + } + + if (isGraphicUI()) { + String title = level.name(); + int type = JOptionPane.PLAIN_MESSAGE; + switch (level) { + case DEBUG: + type = JOptionPane.PLAIN_MESSAGE; + break; + case INFO: + type = JOptionPane.INFORMATION_MESSAGE; + break; + case WARN: + type = JOptionPane.WARNING_MESSAGE; + break; + case ERROR: + case FATAL: + type = JOptionPane.ERROR_MESSAGE; + break; + } + JOptionPane.showMessageDialog(null, msg, title, type); + } + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + */ + public static void debug(String msg) { + if (log.isDebugEnabled()) { + log.debug(msg); + } + show(Level.DEBUG, msg, null); + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + * @param cause exception cause + */ + public static void debug(String msg, Throwable cause) { + if (log.isDebugEnabled()) { + log.debug(msg, cause); + } + show(Level.DEBUG, msg, cause); + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + */ + public static void info(String msg) { + log.info(msg); + show(Level.INFO, msg, null); + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + * @param cause exception cause + */ + public static void info(String msg, Throwable cause) { + log.info(msg, cause); + show(Level.INFO, msg, cause); + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + */ + public static void warn(String msg) { + log.warn(msg); + show(Level.WARN, msg, null); + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + * @param cause exception cause + */ + public static void warn(String msg, Throwable cause) { + log.warn(msg, cause); + show(Level.WARN, msg, cause); + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + */ + public static void error(String msg) { + log.error(msg); + show(Level.ERROR, msg, null); + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + * @param cause exception cause + */ + public static void error(String msg, Throwable cause) { + log.error(msg, cause); + show(Level.ERROR, msg, cause); + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + */ + public static void fatal(String msg) { + log.fatal(msg); + show(Level.FATAL, msg, null); + } + + /** + * Log message using commons-logging and display message box if UI is + * available and non disabled. + * + * @param msg message to display + * @param cause exception cause + */ + public static void fatal(String msg, Throwable cause) { + log.fatal(msg, cause); + show(Level.FATAL, msg, cause); + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/UserLog.java ___________________________________________________________________ Name: svn:keywords + Revision Date Author Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/log/package.html (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/log/package.html) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/log/package.html (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/log/package.html 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,107 @@ +<html> + <body> + +Ce package permet de mettre en place facilement des logs dans les applications. +Il se base sur commons-logging de cette fa�on toutes les applications existantes +utilisant commons-logging sont compatible avec LutinLog. +<p> +LutinLog ajout les fonctionnalit�s suivantes: +<li> user(String), user(String, Throwable) qui permette de logg� des + informations � destination de l'utilisateur +<li> le suivi des taches: start, min, max, value, end, cancel +<li> leve des events sur toutes les methodes: info, warn, error, start, end, ... + que les listeners peuvent recevoir +<li> des classes permettant d'afficher facilement ces log dans une interface + graphique. + +<h1>To do</h1> + +<li> beautiful ProgressMonitorFrame :) +<li> Il faut mettre en place les MetaLutinLog qui est l'encapsulation de + plusieurs LutinLog +<li> Ajouter des methodes sur LutinLogFactory pour r�cup�rer des MetaLutinLog +(meta de tous les LutinLog existant, meta des LutinLog d'un Thread) +<li> Il faut am�liorer le ProgressMonitor pour qu'il puisse afficher si +l'utilisateur le souhaite les d�tails d'un MetaLutinLog, c-a-d qu'on affiche +toutes les taches en cours (message + progress + cancel?) + +<h1>Utilisation</h1> + +il faut lancer java avec + +<pre> java -Dorg.apache.commons.logging.LogFactory=org.codelutin.log.LutinLogFactory </pre> + +ensuite soit vous n'avez pas besoin des nouvelles fonctionnalit�s et vous pouvez +utiliser commons-logging comme habituellement. + +<pre> +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +class Toto { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private Log log = LogFactory.getLog(Toto.class); + + public void Titi() { + if (log.isTraceEnabled()) { + log.trace("Titi called"); + } + } +</pre> + +Ou si vous souhaitez utiliser les nouvelles fonction + +<pre> +import org.codelutin.log.LutinLog; +import org.codelutin.log.LutinLogFactory; + +class Toto { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private LutinLog log = LutinLogFactory.getLutinLog(Toto.class); + + public void Titi() { + if (log.isTraceEnabled()) { + log.trace("Titi called"); + } + // ... do something + log.setActivateProgressMonitorTime(1000); + log.user("task started"); + log.setMin(0); + log.setMax(100); + log.start(); + // ... + for (int i=0; i<100; i++) { + if (log.isAskStopTask()) { + break; + } + log.setValue(i); + //... + } + //... + log.end(); + log.user("task finished"); + } +</pre> + +Dans cette exemple si la t�che dur plus de 1s (1000 millisecondes) alors la +fen�tre de suivi de la t�che est montrer. Sur cette fen�tre l'utilisateur peut +demander l'arret de t�che, on v�rifie dont au d�but de chaque boucle que +l'utiilisateur n'a pas demand� l'arret de la t�che. +<p> +Il est bien sur possible d'utiliser ces propres composant pour afficher +l'avancement d'une t�che, Il est bien sur possible de faire soit m�me les +listener qui sont � l'�coute du LutinLog, mais il est souvent plus simple +d'utiliser MonitorMapper. Il suffit de lui passer en argument les composants +� mettre a jour. +<p> +Il faut bien faire attention de garder une variable accessible de MonitorMapper +car sinon il ne se passera rien, cela est du au fait que les listeners de +LutinLog sont tous encapsul� dans des WeakReference, pour �viter les fuites +m�moire en ajoutant tout le temps de listener sans jamais les supprimer. Ici +la suppression est automatique. + + </body> +</html> + \ No newline at end of file Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/log/package.html ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ApplicationConfig.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ApplicationConfig.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ApplicationConfig.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ApplicationConfig.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,989 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +package org.nuiton.util; + +import org.apache.commons.beanutils.ConstructorUtils; +import org.apache.commons.beanutils.ConvertUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import static org.nuiton.i18n.I18n._; + +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; +import java.lang.annotation.Target; +import java.lang.reflect.InvocationTargetException; +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; +import java.util.LinkedList; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import java.util.Properties; +import java.beans.PropertyChangeSupport; +import java.beans.PropertyChangeListener; + +/** + * <h1>To do</h1> + * <p/> + * <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> + * <p/> + * <h1>Usage</h1> + * <li> create subclass of ApplicationConfig, where in constructor you call + * addAliases, setConfigFileName, setDefaultActionPackage, setDefaultActionClass, setDefaultActionMethod + * to have properly value. + * <p/> + * <li> conf = new MonAppConfig(); + * <li> conf.parse(args); + * <li> here you can used conf.getOption(key); + * <li> conf.doAction(0); + * <li> ... + * <li> conf.doAction(n); + * <p/> + * <h1>Lecture des fichiers de configuration</h1> + * <p/> + * <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) + * <p/> + * <h1>La sauvegarde</h1> + * <p/> + * <p/> + * La sauvegarde des options se fait via une des trois methodes disponible + * <p/> + * <ul> + * <li> {@link #save(File, boolean,String[])} 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> + * <p/> + * Lors de l'utilisation de la methode {@link #saveForSystem(String[])} ou + * {@link #saveForUser(String[])} 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. + * <p/> + * <h1>Les options de configuration</h1> + * <p/> + * <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). + * <p/> + * <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/> + * <p/> + * Les options sur la ligne de commande sont de la forme: + * <pre> + * --option key value + * --monOption key value1 value2 + * </pre> + * <p/> + * <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> + * <p/> + * <h1>Les actions</h1> + * <p/> + * 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/> + * <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/> + * <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/> + * <p/> + * Les arguments sont automatiquement converti dans le bon type reclame par la + * methode. + * <p/> + * <p/> + * Si l'on veut des arguments optionnels le seul moyen actuellement est + * d'utiliser une methode avec des arguments variants + * <p/> + * <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. + * <p/> + * <pre> + * doAction(0); + * ... do something ... + * doAction(1); + * </pre> + * <p/> + * <p/> + * dans cette exemple on fait un traitement entre l'execution des actions + * de niveau 0 et les actions de niveau 1. + * <p/> + * <h1>Les arguments non parses</h1> + * <p/> + * <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/> + * <p/> + * Dans cet exemple seule la premiere option sera considere comme une option. + * On retrouvera dans unparsed: "mon arg", "--option", "k2", "v2", "--", "autre" + * <p/> + * <h1>Les alias</h1> + * <p/> + * 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}. + * <p/> + * <pre> + * addAlias("-v", "--option", "verbose", "true"); + * addAlias("-o", "--option", "outputfile"); + * addAlias("-i", "--mon.package.MaClass#MaMethode", "import"); + * </pre> + * <p/> + * <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: + * <p/> + * <pre> + * addAlias("cl", "Code Lutin"); + * addAlias("bp", "Benjamin POUSSIN); + * </pre> + * <p/> + * <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". + * <p/> + * <h1>Conversion de type</h1> + * Pour la conversion de type nous utilisons common-beans. Les types supporte + * sont: + * <p/> + * <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> + * <p/> + * Pour suporter d'autre type, il vous suffit d'enregistrer de nouveau + * converter dans commons-beans + * + * @author poussin + * @version $Revision$ + * @since 0.30 + * <p/> + * Last update $Date$ + * by $Author$ + */ +public class ApplicationConfig { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private Log log = LogFactory.getLog(ApplicationConfig.class); + + /** + * used to know what is separator between la class et la method sur la + * ligne de commande + */ + static final private String CLASS_METHOD_SEPARATOR = "#"; + + static final public String CONFIG_FILE_NAME = "config.file"; + + 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 + "."; + + /** vrai si on est en train de parser les options de la ligne de commande */ + protected boolean inParseOptionPhase = false; + + protected Properties defaults = new Properties(); + protected Properties classpath = new Properties(defaults); + protected Properties etcfile = new Properties(classpath); + protected Properties homefile = new Properties(etcfile); + protected Properties curfile = new Properties(homefile); + protected Properties env = new Properties(curfile); + protected Properties jvm = new Properties(env); + protected Properties line = new Properties(jvm); + protected Properties options = new Properties(line); + + protected Map<String, CacheItem<?>> cacheOption = new HashMap<String, CacheItem<?>>(); + protected Map<Class<?>, Object> cacheAction = new HashMap<Class<?>, Object>(); + + /** contient apres l'appel de parse, la liste des arguments non utilises */ + protected List<String> unparsed = new ArrayList<String>(); + + protected Map<Integer, List<Action>> actions = new HashMap<Integer, List<Action>>(); + + /** suport of config modification */ + protected PropertyChangeSupport pcs = new PropertyChangeSupport(this); + + static public class Action { + + @Retention(RetentionPolicy.RUNTIME) + @Target(ElementType.METHOD) + static public @interface Step { + int value() default 0; + } + + protected int step; + protected Object o; + protected Method m; + protected String[] params; + + public Action(int step, Object o, Method m, String... params) { + this.step = step; + this.o = o; + this.m = m; + this.params = params; + } + + 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() { + 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 default property key + * @param value default property value + */ + protected void setDefaultOption(String key, String value) { + defaults.setProperty(key, value); + } + + /** + * Save configuration, in specified file + * + * @param file file where config will be writen + * @param forceAll if true save all config option + * (with defaults, classpath, env, command line) + * @param excludeKeys optional list of keys to exclude from + * @throws IOException if IO pb + */ + public void save(File file, boolean forceAll, String... excludeKeys) 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); + + for (String excludeKey : excludeKeys) { + prop.remove(excludeKey); + } + 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. + * + * @param excludeKeys optional list of keys to exclude from + */ + public void saveForSystem(String... excludeKeys) { + File file = new File(systemPath + getConfigFileName()); + try { + save(file, false, excludeKeys); + } catch (IOException eee) { + if (log.isWarnEnabled()) { + log.warn(_("lutinutil.error.applicationconfig.save", file), eee); + } + } + } + + /** + * Save configuration, in user home directory using the + * {@link #getConfigFileName}. Default, env and commande line note saved + * + * @param excludeKeys optional list of keys to exclude from + */ + public void saveForUser(String... excludeKeys) { + File file = new File(userPath + getConfigFileName()); + try { + save(file, false, excludeKeys); + } catch (IOException eee) { + if (log.isWarnEnabled()) { + log.warn(_("lutinutil.error.applicationconfig.save", file), eee); + } + } + } + + /** + * Return list of unparsed command line argument + * + * @return list of unparsed arguments + */ + public List<String> getUnparsed() { + return unparsed; + } + + /** + * Add action to list of action to do + * + * @param action action to add, can be null. + */ + public void addAction(Action action) { + if (action != null) { + Integer step = action.step; + List<Action> list = actions.get(step); + if (list == null) { + list = new LinkedList<ApplicationConfig.Action>(); + actions.put(step, list); + } + list.add(action); + } + } + + public void doAction(int step) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { + List<Action> list = actions.get(step); + if (list != null) { + for (Action a : list) { + a.doAction(); + } + } + } + + public void setUseOnlyAliases(boolean useOnlyAliases) { + this.useOnlyAliases = useOnlyAliases; + } + + public boolean isUseOnlyAliases() { + return useOnlyAliases; + } + + /** + * All argument in aliases as key is substitued by target + * + * @param alias alias string as '-v' + * @param target substitution as '--option verbose true' + */ + public void addAlias(String alias, String... target) { + aliases.put(alias, Arrays.asList(target)); + } + + /** + * Add alias for action. This method put just -- front the actionMethod and + * call {@link #addAlias(String, String[])} + * + * @param alias the alias to add for the given method action + * @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(String, String)} + * + * @param name file name + */ + public void setConfigFileName(String name) { + // put in defaults, this permit user to overwrite it on commande line + setDefaultOption(CONFIG_FILE_NAME, name); + } + + public String getConfigFileName() { + String result = options.getProperty(CONFIG_FILE_NAME); + return result; + } + + /** + * Set option value + * + * @param key property key + * @param value property value + */ + public void setOption(String key, String value) { + if (inParseOptionPhase) { + line.setProperty(key, value); + } else { + options.setProperty(key, value); + } + } + + /** + * get option value as string + * + * @param key the option's key + * @return String representation value + */ + public String getOption(String key) { + String value = options.getProperty(key); + return value; + } + + /** + * Permet de recuperer l'ensemble des options commencant par une certaine + * chaine + * + * @param prefix debut de cle a recuperer + * @return la liste des options filtrées + */ + public Properties getOptionStartsWith(String prefix) { + Properties result = new Properties(); + + for (String key : options.stringPropertyNames()) { + if(key.startsWith(prefix)) { + result.setProperty(key, options.getProperty(key)); + } + } + + return result; + } + + /** + * get option value as typed value + * + * @param <T> type of the object wanted as return type + * @param clazz type of object wanted as return type + * @param key the option's key + * @return typed value + */ + @SuppressWarnings("unchecked") + 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 = (CacheItem<T>)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); + } else { + result = cacheItem.item; + } + + return result; + } + + /** + * get option value as typed value + * + * @param key the option's 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 the option's 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 the option's 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 the option's 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 the option's 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 the option's 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 the option's 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 the option's 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 the option's 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 + */ + protected Map<String, Method> getMethods() { + // looking for all methods set on ApplicationConfig + Method[] allMethods = this.getClass().getMethods(); + Map<String, Method> methods = new HashMap<String, Method>(); + for (Method m : allMethods) { + String methodName = m.getName(); + if (methodName.startsWith("set")) { + methodName = methodName.substring(3).toLowerCase(); + methods.put(methodName, m); + } + } + return methods; + } + + /** + * 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 + * @return the arguments found for the given method + */ + protected String[] getParams(Method m, ListIterator<String> args) { + 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.toArray(new String[result.size()]); + } + + /** + * Create action from string, string must be [package.][class][#][method] + * if package, class or method missing, default is used + * + * @param name name of the action + * @param args + * @return the created action + * @throws ArgumentsParserException + * @throws IllegalAccessException + * @throws IllegalArgumentException + * @throws InstantiationException + * @throws java.lang.reflect.InvocationTargetException + */ + protected Action createAction(String name, ListIterator<String> args) throws ArgumentsParserException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { + Action result = null; + + Class<?> clazz; + Method method = null; + String className; + String methodName; + + // looking for method name + int sep = name.lastIndexOf(CLASS_METHOD_SEPARATOR); + if (sep == -1) { + throw new IllegalArgumentException(String.format( + "Can't find action method in %s", name)); + } else { + className = name.substring(0, sep); + methodName = name.substring(sep + 1); + } + + // looking for class name + try { + clazz = Class.forName(className); + } catch (ClassNotFoundException eee) { + throw new IllegalArgumentException(String.format( + "Can't find action class %s", className)); + } + + List<Method> methods = ObjectUtil.getMethod(clazz, methodName, true); + if (methods.size() > 0) { + if (methods.size() > 1) { + log.warn(String.format( + "More than one method found, used the first: %s", methods)); + } + method = methods.get(0); + } + + if (method != null) { + args.remove(); // remove option from command line, because is used now + + // 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) { + step = annotation.value(); + } + + String[] params = getParams(method, args); + result = new Action(step, o, method, params); + } + + return result; + } + + /** + * Parse option and call set necessary method, read jvm, env variable, + * Load configuration file and prepare Action. + * + * @param args argument as main(String[] args) + * @throws ArgumentsParserException + * + */ + public void parse(String[] args) throws ArgumentsParserException { + try { + Map<String, Method> methods = getMethods(); + + List<String> arguments = new ArrayList<String>(args.length); + for (String arg : args) { + if (aliases.containsKey(arg)) { + arguments.addAll(aliases.get(arg)); + } else { + arguments.add(arg); + } + } + + inParseOptionPhase = true; + // 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)) { + i.remove(); // remove this arg because is used now + Method m = methods.get(optionName); + String[] params = getParams(m, i); + log.debug(String.format("Set option '%s' with method '%s %s'", optionName, m, Arrays.toString(params))); + ObjectUtil.call(this, m, params); + } + } + } + inParseOptionPhase = false; + + // + // second load options from all sources + // + // JVM + jvm.putAll(System.getProperties()); + // ENV + env.putAll(System.getenv()); + + // classpath + String filename = getConfigFileName(); + URL inClasspath = ClassLoader.getSystemClassLoader().getResource(filename); + if (inClasspath == null) { + inClasspath = ApplicationConfig.class.getResource(filename); + } + if (inClasspath != null) { + log.info("Chargement du fichier de config: " + inClasspath); + classpath.load(inClasspath.openStream()); + } + + File etcConfig = new File(systemPath + filename); + if (etcConfig.exists()) { + log.info("Chargement du fichier de config: " + etcConfig); + etcfile.load(etcConfig.toURI().toURL().openStream()); + } + + 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/filename + File config = new File(filename); + if (config.exists()) { + log.info("Chargement du fichier de config: " + config); + curfile.load(config.toURI().toURL().openStream()); + } + + // + // third parse action and do action + // + 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); + addAction(action); + } + } + + // + // not used args added to unparsed + // + arguments.remove("--"); + unparsed.addAll(arguments); + + } catch (Exception eee) { + eee.printStackTrace(); + throw new ArgumentsParserException("Can't parse argument", eee); + } + } + + /** + * For debugging + */ + public void printConfig() { + System.out.println("-------------------Value-------------------------"); + System.out.println("defaults " + defaults); + System.out.println("classpath " + classpath); + System.out.println("etcfile " + etcfile); + System.out.println("homefile " + homefile); + System.out.println("curfile " + curfile); + System.out.println("env " + env); + System.out.println("jvm " + jvm); + System.out.println("line " + line); + System.out.println("options " + options); + System.out.println("-------------------------------------------------"); + } + + protected void firePropertyChange(String propertyName,Object oldValue,Object newValue) { + pcs.firePropertyChange(propertyName,oldValue,newValue); + } + + public void addPropertyChangeListener(PropertyChangeListener listener) { + pcs.addPropertyChangeListener(listener); + } + + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.addPropertyChangeListener(propertyName, listener); + } + + public void removePropertyChangeListener(PropertyChangeListener listener) { + pcs.removePropertyChangeListener(listener); + } + + public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.removePropertyChangeListener(propertyName, listener); + } + + public synchronized boolean hasListeners(String propertyName) { + return pcs.hasListeners(propertyName); + } + + public synchronized PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { + return pcs.getPropertyChangeListeners(propertyName); + } + + public synchronized PropertyChangeListener[] getPropertyChangeListeners() { + return pcs.getPropertyChangeListeners(); + } + + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ApplicationConfig.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParser.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ArgumentsParser.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParser.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParser.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,393 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * +* ArgumentsParser.java +* +* Created: 22 août 2003 +* +* @author Benjamin Poussin <poussin@codelutin.com> +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.nuiton.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; + +/** + * Parser d'option de la ligne de commande. + * IDEA: ajouter le type de l'argument a parser (int, double, String, boolean, Class, File, ...) + * et mettre des methodes pour récupérer directement ce type. + * + * @author poussin + * + * @deprecated since 0.30 , prefer use of {@link ApplicationConfig} instead + */ +@Deprecated +public class ArgumentsParser { + + /** La liste des arguments qui ne sont pas des options */ + protected ArrayList<String> arguments = new ArrayList<String>(); + /** le nom à afficher pour l'usage */ + protected String name = ""; + + /** + * la liste des options, la cle est une option, et la valeur est la liste + * des options qui ont été lu grâce à celle-ci. + */ + protected HashMap<ArgumentsParserOption, ArrayList<ArgumentsParserOption>> options = + new HashMap<ArgumentsParserOption, ArrayList<ArgumentsParserOption>>(); + /** liste a plat de toutes les options lus. */ + protected ArrayList<ArgumentsParserOption> parsedOptions = new ArrayList<ArgumentsParserOption>(); + + /** + * Constructor for the ArgumentsParser object + * + * @param name le nom à afficher pour l'usage + */ + public ArgumentsParser(String name) { + this.name = name; + } + + /** + * Permet de d'ajouter une option facilement au parser, sans avoir besoin de + * créer un objet Option. + * + * @param optionName le nom de cette option. + * @param acceptedOption la liste des marqueurs acceptables pour cette + * option. exemple -o, --option, --options + * @param argument le nombre d'argument que cette option a + * @param description description de cette option + * @return retourne l'option créer et qui sera utilisé + * @see #addOption(ArgumentsParserOption) + */ + public ArgumentsParserOption addOption(String optionName, + String description, int argument, String... acceptedOption) { + return addOption(new ArgumentsParserDefaultOption + (optionName, description, argument, acceptedOption)); + } + + /** + * Permet d'ajouter une option au parseur + * + * @param option l'option à ajouter + * @return retourne l'option passé en paramètre + */ + public ArgumentsParserOption addOption(ArgumentsParserOption option) { + options.put(option, new ArrayList<ArgumentsParserOption>()); + return option; + } + + /** + * Permet de vérifier la coherence de toutes les options. Cela consiste à + * regarder si deux options n'utilise pas les même marqueurs, si deux + * options n'ont pas le même nom, si le nombre de répétition min d'une + * option n'est pas suppérieur au nombre de répétition max + * + * @return une chaine de caractère indiquant toutes les erreurs. Si la + * chaine est vide alors il n'y a pas d'erreur. + */ + public String checkCoherence() { + StringBuffer result = new StringBuffer(); + HashSet<String> optionNames = new HashSet<String>(); + HashSet<String> used = new HashSet<String>(); + + for (ArgumentsParserOption option : options.keySet()) { + if (optionNames.contains(option.getName())) { + result.append("option name " + option.getName() + + " is allready used\n"); + } + optionNames.add(option.getName()); + + String[] acceptedOptions = option.getAcceptedOption(); + for (String acceptedOption : acceptedOptions) { + if (used.contains(acceptedOption)) { + result.append("Option " + acceptedOption + " in " + + option.getName() + " is allready used\n"); + } + used.add(acceptedOption); + } + + if (option.getRepetitionMax() > 0 + && option.getRepetitionMin() > option.getRepetitionMax()) { + result.append("repetition min is over repetition max for: " + + option.getName() + "\n"); + option.setRepetitionMax(option.getRepetitionMin()); + } + } + return result.toString(); + } + + /** + * Permet de vérifier la cohérence de la ligne de commande par rapport aux + * contraintes des options. Cela consiste à vérifier que chaque option est + * bien répété le nmobre de fois souhaité par l'option qui à permis de la + * lire. + * + * @return vrai s'il n'y a pas d'erreur + * @throws ArgumentsParserException une exception est levé dès qu'une + * erreur est détectée. + */ + boolean checkParsing() throws ArgumentsParserException { + for (ArgumentsParserOption option : options.keySet()) { + ArrayList<ArgumentsParserOption> list = options.get(option); + if (option.getRepetitionMin() > 0 + && list.size() < option.getRepetitionMin()) { + throw new ArgumentsParserException( + "Error option repeted less than accepted need " + + option.getRepetitionMin() + " find " + list.size() + ": " + + option); + } + if (option.getRepetitionMax() > 0 + && list.size() > option.getRepetitionMax()) { + throw new ArgumentsParserException( + "Error option repeted more than accepted: " + option); + } + } + return true; + } + + /** + * Retourne les arguments de la ligne de commande qui n'ont pas été lu pas + * les options + * + * @return la liste des arguments non lu par les options. + */ + public ArrayList<String> getArguments() { + return arguments; + } + + /** + * Retourne le nom utilisé pour l'affichage de l'usage + * + * @return la chaine de caratère utilisée pour l'usage + */ + public String getName() { + return name; + } + + /** + * Permet de savoir si une option a ete trouvée sur la ligne de commande + * + * @param optionName le nom de l'option dont il faut vérifier l'existance + * @return vrai si l'option existe sur la ligne de commande + */ + public boolean hasParsedOption(String optionName) { + return getParsedOptions(optionName).size() != 0; + } + + /** + * Retourne le premier argument d'un certain type + * + * @param optionName le nom de l'option à retourner + * @return la valeur de l'option si elle existe, null sinon + */ + public String[] getParsedOption(String optionName) { + ArrayList<ArgumentsParserOption> list = getParsedOptions(optionName); + if (list.size() == 0) { + return null; + } else { + return list.get(0).getArguments(); + } + } + + /** + * Retourne la liste de toutes les options créées durant le parsage de la + * ligne de commande. + * + * @return la liste de toutes les options lus + */ + public ArrayList<ArgumentsParserOption> getParsedOptions() { + return parsedOptions; + } + + /** + * Retourne la liste de toutes les options d'un certain type + * + * @param optionName le nom des options à retourner + * @return la liste des options d'un certain nom, ou une liste vide si + * aucune option de ce nom existe ou si cette option n'a pas été trouvé + * sur la ligne de commande + */ + public ArrayList<ArgumentsParserOption> getParsedOptions(String optionName) { + ArrayList<ArgumentsParserOption> result = new ArrayList<ArgumentsParserOption>(); + for (ArgumentsParserOption option : options.keySet()) { + if (optionName.equals(option.getName())) { + result = options.get(option); + } + } + return result; + } + + /** + * Permet de recherche une option permettant de lire l'argument courant de + * la ligne de commande et d'utiliser une copie de cette option pour lire la + * suite de la ligne de commande. + * + * @param args la ligne de commande + * @param index la position courant de parsage de la ligne de commande + * @return retourne l'option qui a permit de lire la ligne de commande + * ou null si aucune option ne peut lire l'argument courant. + */ + ArgumentsParserOption lookingForOption(String[] args, int index) { + for (ArgumentsParserOption option : options.keySet()) { + ArgumentsParserOption copy = option.copy(); + if (copy.parse(args, index)) { + ArrayList<ArgumentsParserOption> list = options.get(option); + parsedOptions.add(copy); + list.add(copy); + return copy; + } + } + return null; + } + + + /** + * Une methode main pour tester la librairie + * + * @param args The command line arguments + * @throws Exception on fait suivre toutes les erreurs + */ + public static void main(String[] args) throws Exception { + ArgumentsParser ap = new ArgumentsParser("ArgumentsParserTest"); + ap.addOption("project", "le nom du projet", 1, "-p") + .setRepetitionMin(1); + + ap.addOption("lib", "les librairies", 1, "-l") + .setRepetitionMin(2).setRepetitionMax(1); + + ap.addOption("truc", "les dummy", 1, "-t"); + + ap.addOption("package", "le package utilisé", + 1, "-k", "--package").setRepetitionMax(10); + + System.out.println(ap.usage()); + System.out.println(); + System.out.println("check coherence..."); + System.out.println(ap.checkCoherence()); + System.out.println("parsing..."); + ap.parse(args); + System.out.println(ap.getParsedOptions()); + System.out.println(ap.getParsedOptions("package")); + System.out.println(ap.getArguments()); + } + + /** + * Cette méthode permet de parser une ligne de commande. Aucune + * réinitialisation n'est faite entre deux appels. + * + * @param args la ligne de commande à parser + * @return la liste de toutes les options lus + * @throws ArgumentsParserException si la vérification de la lecture + * montre des incohérence une exception est levée + */ + public ArgumentsParserOption[] parse(String[] args) throws ArgumentsParserException { + for (int i = 0; i < args.length; i++) { + ArgumentsParserOption option = lookingForOption(args, i); + if (option != null) { + i += option.count(); + } else { + arguments.add(args[i]); + } + } + + checkParsing(); + + return (ArgumentsParserOption[]) parsedOptions.toArray( + new ArgumentsParserOption[parsedOptions.size()]); + } + + /** + * <p> + * <p/> + * Permet d'afficher l'usage gràce aux informations des options: répétition, + * description, ...</p> <p> + * <p/> + * la chaîne retourné est de la forme suivante</p> <pre> + * usage: ArgumentsParserTest [package{10}][truc+] lib project+ + * <p/> + * package(-k, --package) le package utilisé + * truc(-t) les dummy + * lib(-l) les librairies + * project(-p) le nom du projet + * </pre> <p> + * <p/> + * ArgumentsParserTest est le nom passé au constructeur de ArgumentsParser. + * </p> <p> + * <p/> + * une option qui a une répétition min à 0 est entre [ ]</p> <p> + * <p/> + * une option qui a une répétition max à 0 à un + ajouté</p> <p> + * <p/> + * une option qui a une répétition max à supérieur à 1 à le nombre max + * ajouté entre {}</p> + * + * @return la chaîne de caratère de l'usage. + */ + public String usage() { + StringBuffer result = new StringBuffer(); + result.append("usage: " + getName() + " "); + for (ArgumentsParserOption option : options.keySet()) { + if (option.getRepetitionMin() <= 0) { + result.append("["); + } else { + result.append(" "); + } + result.append(option.getName()); + if (option.getRepetitionMax() <= 0) { + result.append("+"); + } else if (option.getRepetitionMax() > 1) { + result.append("{" + option.getRepetitionMax() + "}"); + } + + for (int a = 0; a < option.count(); a++) { + result.append(" <arg" + a + ">"); + } + + if (option.getRepetitionMin() <= 0) { + result.append("]"); + } else { + result.append(" "); + } + } + result.append("\n\n"); + for (ArgumentsParserOption option : options.keySet()) { + result.append(option.getName()); + result.append("("); + String[] acceptedOption = option.getAcceptedOption(); + for (int i = 0; i < acceptedOption.length; i++) { + result.append(acceptedOption[i]); + if (i + 1 < acceptedOption.length) { + result.append(", "); + } + } + result.append(")"); + result.append("\t"); + result.append(option.getDescription()); + result.append("\n"); + } + return result.toString(); + } +} +// -- end class ArgumentsParser + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParser.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserDefaultOption.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ArgumentsParserDefaultOption.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserDefaultOption.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserDefaultOption.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,222 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +/** + * ArgumentsParserDefaultOption.java Created: 22 août 2003 + * + *@author Benjamin Poussin <poussin@codelutin.com> + * + * Copyright Code Lutin + *@version $Revision$ Mise a jour: $Date$ par : $Author$ + */ + +package org.nuiton.util; + +import java.util.ArrayList; + +/** + * Description of the Class + * + * @author poussin + * created 22 août 2003 + * + * @deprecated since 0.30 , prefer use of {@link ApplicationConfig} instead + */ +public class ArgumentsParserDefaultOption implements ArgumentsParserOption {// ArgumentsParserDefaultOption + + /** Toutes les options accepté: -o --option */ + String[] acceptedOption; + /** L'option utilisé sur la ligne de commande */ + String parsedOption; + /** Le nom de cette option */ + String name; + /** le nombre d'argument de cette option */ + int argument = 0; + /** la liste des arguments */ + ArrayList<String> argumentList = new ArrayList<String>(); + /** + * le nombre de fois minimum que l'option peut-être répétée sur la ligne de + * commande + */ + int repetitionMin = 0; + /** + * le nombre de fois maximum que l'option peut-être répétée sur la ligne de + * commande: 1 par defaut + */ + int repetitionMax = 1; + /** Description of the argument */ + String description = ""; + + /** + * @param name le nom de l'option + * @param acceptedOption la liste variante de l'option accepté: -o --option + * @param argument le nombre d'argument que cette option accepte + * @param description TODO Description of the Parameter + */ + public ArgumentsParserDefaultOption(String name, String description, + int argument, String... acceptedOption) { + this.name = name; + this.description = description; + this.acceptedOption = acceptedOption; + this.argument = argument; + } + + public String[] getAcceptedOption() { + return acceptedOption; + } + + /** + * TODO Description of the Method + * + * @return TODO Description of the Return Value + */ + public ArgumentsParserOption copy() { + return new ArgumentsParserDefaultOption(name, description, argument, acceptedOption).setRepetitionMin(getRepetitionMin()).setRepetitionMax(getRepetitionMax()); + } + + /** + * Description of the Method + * + * @param args Description of the Parameter + * @param index Description of the Parameter + * @return vrai si le parsing a reussi + */ + public boolean parse(String[] args, int index) { + parsedOption = args[index++]; + if (acceptOption(parsedOption)) { + for (int i = 0; i < count(); i++) { + argumentList.add(args[index + i]); + } + return true; + } + return false; + } + + /** + * Gets the usedOption attribute of the DefaultOption object + * + * @return The usedOption value + */ + public String getUsedOption() { + return parsedOption; + } + + /** + * Gets the description attribute of the DefaultOption object + * + * @return The description value + */ + public String getDescription() { + return description; + } + + + /** + * Get repetitionMin property. + * + * @return RepetitionMin property. + */ + public int getRepetitionMin() { + return this.repetitionMin; + } + + /** + * Set repetitionMin property. + * + * @param repetitionMin New repetitionMin property. + * @return TODO Description of the Return Value + */ + public ArgumentsParserOption setRepetitionMin(int repetitionMin) { + this.repetitionMin = repetitionMin; + return this; + } + + + /** + * Get repetitionMax property. + * + * @return RepetitionMax property. + */ + public int getRepetitionMax() { + return this.repetitionMax; + } + + /** + * Set repetitionMax property. + * + * @param repetitionMax New repetitionMax property. + * @return TODO Description of the Return Value + */ + public ArgumentsParserOption setRepetitionMax(int repetitionMax) { + this.repetitionMax = repetitionMax; + return this; + } + + + /** + * Gets the name attribute of the DefaultOption object + * + * @return The name value + */ + public String getName() { + return name; + } + + /** + * Gets the arguments attribute of the DefaultOption object + * + * @return The arguments value + */ + public String[] getArguments() { + return (String[]) argumentList.toArray(new String[count()]); + } + + /** + * return numbers of args for this option + * + * @return numbers of args for this option + */ + public int count() { + return argument; + } + + /** + * Description of the Method + * + * @param optionName Description of the Parameter + * @return Description of the Return Value + */ + protected boolean acceptOption(String optionName) { + for (int i = 0; i < acceptedOption.length; i++) { + if (acceptedOption[i].equals(optionName)) { + return true; + } + } + return false; + } + + /** + * TODO Description of the Method + * + * @return TODO Description of the Return Value + */ + public String toString() { + return name + "(" + parsedOption + ")" + argumentList; + } +}// ArgumentsParserDefaultOption + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserDefaultOption.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserException.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ArgumentsParserException.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserException.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserException.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,44 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%*/ + +package org.nuiton.util; + +/** + * Argument parsing exception + * + * @author Benjamin Poussin <poussin@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class ArgumentsParserException extends Exception { // ArgumentsParserException + + /** serialVersionUID. */ + private static final long serialVersionUID = 8265924907001359910L; + + public ArgumentsParserException(String msg) { + super(msg); + } + + public ArgumentsParserException(String msg, Throwable eee) { + super(msg, eee); + } + +} // ArgumentsParserException + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserException.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserOption.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ArgumentsParserOption.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserOption.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserOption.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,84 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.nuiton.util; + +/** + * Cette classe représente une option de la ligne de commande + * + * @author poussin + * created 22 août 2003 + * + * @deprecated since 0.30 , prefer use of {@link ApplicationConfig} instead + */ +public interface ArgumentsParserOption extends Cloneable {// Option + /** + * Essai de parser un argument. Si cela a fonctionné, retourne un argument + * sinon retourne null. + * + *@param arg liste des arguments de la ligne de commande + *@param index l'index ou le parser est rendu + *@return vrai si le parsing a réussi + */ + public boolean parse(String[] arg, int index); + + /** + * Retourne le nom de l'option + * + * @return le nom + */ + public String getName(); + + public String getDescription(); + + public String [] getAcceptedOption(); + + public int getRepetitionMin(); + public int getRepetitionMax(); + public ArgumentsParserOption setRepetitionMin(int repetitionMin); + public ArgumentsParserOption setRepetitionMax(int repetitionMax); + + /** + * Retourne l'option utilisée sur la ligne de commande + * + *@return l'option utilisée sur la ligne de commende + */ + public String getUsedOption(); + + /** + * Retourne la liste des arguments de l'option. + * + *@return la liste des arguments de l'option. + */ + public String[] getArguments(); + + /** + * Permet de connaitre le nombre d'argument consommé par cet objet + * + *@return le nombre d'argument + */ + public int count(); + + /** + * Copie l'objet + * + *@return retourne un nouvel objet + */ + public ArgumentsParserOption copy(); +}// Option + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ArgumentsParserOption.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ArrayUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ArrayUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ArrayUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ArrayUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,209 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * ArrayUtil.java + * + * Created: 31 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +public class ArrayUtil { // ArrayUtil + + /** + * Permet de convertir un tableau en une liste, le type primitif + * est encapsulé dans un objet. + * + * @param a le tableau a convertir + * @return la liste + * @deprecated avec l'auto-boxing en java 5 et plus ? + */ + static public List<Double> asList(double[] a) { + ArrayList<Double> result = new ArrayList<Double>(a.length); + for (double anA : a) { + result.add(anA); + } + return result; + } + + static public <T> List<T> asList(T[] a) { + return Arrays.asList(a); + } + + /** + * Permet de convertir un tableau en une liste, le type primitif + * est encapsulé dans un objet. + * + * @param a le tableau a convertir + * @return la liste + * @deprecated avec l'auto-boxing en java 5 et plus ? + */ + static public List<Integer> asList(int[] a) { + ArrayList<Integer> result = new ArrayList<Integer>(a.length); + for (int anA : a) { + result.add(anA); + } + return result; + } + + public static int[] asIntArray(String[] a) { + int[] result = new int[a.length]; + for (int i = 0; i < a.length; i++) { + result[i] = StringUtil.toInt(a[i]); + } + return result; + } + + + /** + * Fait la somme des 2 tableaux et retourne un nouveau tableau, les + * 2 tableaux passés en argument ne sont pas modifiés. Les deux tableaux + * doivent être non null et avoir la même taille. + * + * @param a le premier tableau + * @param b le second tableau + * @return le tableau des sommes + */ + static public int[] sum(int[] a, int[] b) { + if (a == null || b == null || a.length != b.length) { + throw new IllegalArgumentException("Au moins des tableaux est null ou les tableaux ne font pas la même taille"); + } + int[] result = new int[a.length]; + for (int i = 0; i < a.length; i++) { + result[i] = a[i] + b[i]; + } + return result; + } + + static public int[] concat(int[]... tabs) { + int length = 0; + for (int[] tab : tabs) { + if (tab != null) { + length += tab.length; + } + } + int[] result = new int[length]; + length = 0; + for (int[] tab : tabs) { + if (tab != null) { + System.arraycopy(tab, 0, result, length, tab.length); + length += tab.length; + } + } + return result; + } + + /** + * Retourne un nouveau tableau qui est la concatenation des deux autres. + * Essai de garder pour le tableau resultat le type des tableaux en entré + * si possible. [Double], [Number] -> [Number]; [Double], [Long] -> [Object] + * + * @param tabs les tableaux + * @return le nouveau tableau ou null, si les deux tableaux sont null + * todo essayer de retourner le meilleur type de tableau possible + * [Double], [Long] -> [Number] + */ + static public Object[] concat(Object[]... tabs) { + Object[] result = null; + Class<?> clazz = null; + int length = 0; + for (Object[] tab : tabs) { + if (tab != null) { + length += tab.length; + Class<?> tmp = tab.getClass().getComponentType(); + if (clazz == null) { + clazz = tmp; + } else if (tmp.isAssignableFrom(clazz)) { + clazz = tmp; + } else if (clazz.isAssignableFrom(tmp)) { + // do nothing, because clazz can't be better + } else { + clazz = Object.class; + } + } + } + + if (clazz != null) { + result = (Object[]) Array.newInstance(clazz, length); + length = 0; + for (Object[] tab : tabs) { + if (tab != null) { + System.arraycopy(tab, 0, result, length, tab.length); + length += tab.length; + } + } + } + return result; + } + + /** + * Ajoute a un tableau un ensemble d'element. Le type du tableau retourné + * est le meilleur possible. + * + * @param tab les valeurs initiales du tableau + * @param elems les elemements a ajouter + * @return un nouveau tableau contenant a la fin les elements souhaites + */ + @SuppressWarnings("unchecked") + static public <E, F extends E> E[] concatElems(E[] tab, F... elems) { + E[] result; + result = (E[]) concat(tab, elems); + return result; + } + + /** + * Recherche dans le table le 1er element qui correspond a la classe + * passée en argument. + * + * @param tab le tableau dans lequel il faut chercher + * @param clazz la classe de l'objet souhaité + * @return un objet de la classe demandé, ou null si aucun ne correspond + */ + static public <A> A search(Object[] tab, Class<A> clazz) { + A result = null; + for (Object o : tab) { + if (clazz.isInstance(o)) { + result = clazz.cast(o); + } + } + return result; + } + + @SuppressWarnings({"unchecked"}) + static public <T> T[] toArray(Collection list, Class<T> clazz) { + T[] result = (T[]) Array.newInstance(clazz, list == null ? 0 : list.size()); + int i = 0; + for (Object o : list) { + result[i++] = (T) o; + } + return result; + } +} // ArrayUtil + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ArrayUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedList.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/BoundedList.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedList.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedList.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,231 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * +* BoundedList.java +* +* Created: 30 mai 2005 +* +* @author Arnaud Thimel <thimel@codelutin.com> +* @version $Revision$ +*/ + + +package org.nuiton.util; + +import java.util.ArrayList; +import java.util.Collection; + +/** ArrayList with minimum and maximum sizes. For each operation, the size is checked and the BoundedList to ensure that it is kept in the range. */ +public class BoundedList<E> extends ArrayList<E> { + /** */ + private static final long serialVersionUID = -3211387041114409849L; + + //By defaut, maxSize is set to -1 (infinite) + private int minSize = 0; + private int maxSize = -1; + + /** + * Indicates if the list size is at the maximum + * + * @return true is the maximum size has been reached + */ + public boolean isFull() { + return (maxSize == -1 || size() >= maxSize); + } + + /** + * Indicates if the list size is to the minimum + * + * @return true is the list size is the minimum size + */ + public boolean isToMinimum() { + return (size() <= minSize); + } + + /** + * Creates a new BoundedList with the specified initialCapacity. The min size is set to 0 and the max size to the infinite. + * + * @param initialCapacity + */ + public BoundedList(int initialCapacity) { + super(initialCapacity); + } + + /** Creates a new BoundedList with the default capacity. The min size is set to 0 and the max size to the infinite. */ + public BoundedList() { + super(); + } + + /** + * Creates a new BoundedList with the specified collection of elements. The min size is set to 0 and the max size to the infinite. + * + * @param arg0 + */ + public BoundedList(Collection<E> arg0) { + super(arg0); + } + + /** + * Creates a new empty BoundedList with the specified min and max sizes. Please be informed that -1 represents the infinite. + * + * @param minSize + * @param maxSize + */ + public BoundedList(int minSize, int maxSize) { + super(); + if (minSize > 0) + this.minSize = minSize; + if (minSize > -1) + this.maxSize = maxSize; + } + + /** + * Appends the specified element to the end of this list. + * + * @param o the Object to be added + */ + @Override + public boolean add(E o) { + if (checkNewSize(1)) + return super.add(o); + else + throw getException("Cannot add element. Use set to replace element or remove to free space or addAll"); + } + + /** + * Inserts the specified element at the specified position in this list. + * + * @param index the position where to add the Object + * @param o the Object to be added + */ + @Override + public void add(int index, E o) { + if (checkNewSize(1)) + super.add(index, o); + else + throw getException("Cannot add element. Use set to replace element or remove to free space or addAll"); + } + + /** + * Appends all of the elements in the specified Collection to the end of this list, in the order that they are returned by the specified Collection's Iterator. + * + * @param c the collection of Objects to be added + */ + @Override + public boolean addAll(Collection<? extends E> c) { + if (checkNewSize(c.size())) + return super.addAll(c); + else + throw getException("Cannot add element. Use set to replace element or remove to free space or addAll"); + } + + /** + * Inserts all of the elements in the specified Collection into this list, starting at the specified position. + * + * @param index the index where to start adding the collection of objects + * @param c the collection of Objects to be added + */ + @Override + public boolean addAll(int index, Collection<? extends E> c) { + if (checkNewSize(c.size())) + return super.addAll(index, c); + else + throw getException("Cannot add element. Use set to replace element or remove to free space or addAll"); + } + + /** Returns a shallow copy of this BoundedList instance */ + @SuppressWarnings("unchecked") + @Override + public Object clone() { + BoundedList<E> bL = (BoundedList<E>) super.clone(); + bL.minSize = minSize; + bL.maxSize = maxSize; + return bL; + } + + /* + public Object set(int index, Object o) { + //Pas d'action particulière à priori + return super.set(index, o); + } + */ + + /** + * Removes the element at the specified position in this list. + * + * @param index the position of the element to be removed + */ + @Override + public E remove(int index) { + if (checkNewSize(-1)) + return super.remove(index); + else + throw getException("Cannot remove element, minSize is " + minSize); + } + + /** + * Removes from this List all of the elements whose index is between fromIndex, inclusive and toIndex, exclusive. + * + * @param fromIndex index of first element to be removed + * @param toIndex index after last element to be removed + */ + @Override + protected void removeRange(int fromIndex, int toIndex) { + if (checkNewSize(-(toIndex - fromIndex))) + super.removeRange(fromIndex, toIndex); + else + throw getException("Cannot remove element, minSize is " + minSize); + } + + /** Removes a single instance of the specified element from this list, if it is present (optional operation). */ + @Override + public boolean remove(Object o) { + if (checkNewSize(-1) || !contains(o)) + return super.remove(o); + else + throw getException("Cannot remove element, minSize is " + minSize); + } + + /** Removes from this collection all of its elements that are contained in the specified collection (optional operation). */ + @Override + public boolean removeAll(Collection<?> c) { + //On ne sait pas si les éléments de la Collection sont contenus dans la liste. + //De plus, on ne sait pas si les instances sont présentes un ou plusieurs fois (Si elles y sont +sieurs fois elles sont supprimées +sieurs fois) + if (checkNewSize(-c.size())) + return super.removeAll(c); + else + throw getException("Cannot remove element, minSize is " + minSize); + } + + private boolean checkNewSize(int size) { + if (size == 0) //Pas de changement de taille ! + return (((size()) >= minSize) && ((maxSize == -1) || (size() <= maxSize))); + else if (size > 0) //Ajout d'un elem - vérification qu'on ne dépasse pas la borne max + return ((maxSize == -1) || ((size() + size) <= maxSize)); + return ((size() + size) >= minSize); //Suppression d'un élem - on vérifie qu'on ne descend pas en dessous de la borne min + } + + private RuntimeException getException(String msg) { + return new BoundedListOutOfBoundsException(msg); + } + + @Override + public String toString() { + return /*"(" + minSize + ", " + maxSize + ") " +*/ super.toString(); + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedList.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedListOutOfBoundsException.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/BoundedListOutOfBoundsException.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedListOutOfBoundsException.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedListOutOfBoundsException.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,61 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * +* BoundedListOfBoundsException.java +* +* Created: 30 mai 2005 +* +* @author Arnaud Thimel <thimel@codelutin.com> +* @version $Revision$ +*/ + + +package org.nuiton.util; + + +public class BoundedListOutOfBoundsException extends RuntimeException { + + /** */ + private static final long serialVersionUID = 7006384682459926080L; + + /** + * + */ + public BoundedListOutOfBoundsException() { + super(); + } + + /** @param message */ + public BoundedListOutOfBoundsException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public BoundedListOutOfBoundsException(String message, Throwable cause) { + super(message, cause); + } + + /** @param cause */ + public BoundedListOutOfBoundsException(Throwable cause) { + super(cause); + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/BoundedListOutOfBoundsException.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/CallAnalyse.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/CallAnalyse.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/CallAnalyse.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/CallAnalyse.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,330 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * CallAnalyse.java + * + * Created: 25 ao�t 2005 14:09:22 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import org.apache.commons.collections.primitives.ArrayLongList; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** +* Cette classe permet de faire des analyses sur les appels de methode +* En debut de methode on appelle la methode {@link #enter}, et en fin de methode +* la methode {@link #exit}. +* <p> +* Ensuite on peut récuperer les statistiques par Thread ou de tous les threads +* <p> +* On a comme statistique +* <li> le temps d'execution +* <li> la memore utilisé +* <li> le nombre d'appels +*/ +public class CallAnalyse { // CallAnalyse + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private Log log = LogFactory.getLog(CallAnalyse.class); + + static private List<ThreadStatistics> listThreadStatistics = + new ArrayList<ThreadStatistics>(); + + static private ThreadLocal<ThreadStatistics> stats = + new ThreadLocal<ThreadStatistics>(){ + @Override + protected synchronized ThreadStatistics initialValue(){ + ThreadStatistics result = new ThreadStatistics(); + listThreadStatistics.add(result); + return result; + } + }; + + /** + * Permet d'activer les statistiques, pour le thread courant + */ + static public void activate(){ + stats.get().setActivated(true); + } + + /** + * Permet de desactiver les statistiques, pour le thread courant + */ + static public void desactivate(){ + stats.get().setActivated(false); + } + + /** + * Permet de savoir si les statistiques sont activées ou non, pour le + * thread courant + */ + static public boolean isActivate(){ + return stats.get().getActivated(); + } + + /** + * @param name le nom de l'appel a monitorer + */ + static public void enter(String name){ + ThreadStatistics t = stats.get(); + if(t.getActivated()){ + t.get(name).enter(); + } + } + + /** + * Indique la sortie de l'appel, name doit avoir ete utilisé lors d'un enter + * @param name le nom de l'appel a monitorer, doit etre identique a + * celui utilisé pour la methode enter + */ + static public void exit(String name){ + ThreadStatistics t = stats.get(); + if(t.getActivated()){ + t.get(name).exit(); + } + } + + /** + * @return the statistics for the current thread + */ + static public ThreadStatistics getThreadStatistics(){ + return stats.get(); + } + + /** + * @return the statistics for all threads + */ + static public List<ThreadStatistics> getAllThreadStatistics(){ + return listThreadStatistics; + } + + static public class ThreadStatistics extends TreeMap<String, CallStatistics>{ + /** */ + private static final long serialVersionUID = -36051448464013504L; + protected boolean activated = false; + public boolean getActivated(){ + return activated; + } + public void setActivated(boolean activated){ + this.activated = activated; + } + public CallStatistics get(String name){ + CallStatistics result = super.get(name); + if(result == null){ + put(name, result = new CallStatistics(name)); + } + return result; + } + public String toString(){ + return values().toString(); + } + } + + /** + * This method will get all the statistics from all the threads and put it + * all together in a {@link Map} which key is the name of the watched + * element and the value is its instance of {@link CallStatisticsSummary} + * + * @return A map with all collected statistics + */ + public static Map<String, CallStatisticsSummary> getSummary() { + Map<String, CallStatisticsSummary> results = new HashMap<String, CallStatisticsSummary>(); + for (ThreadStatistics stats : CallAnalyse.getAllThreadStatistics()) { + for (String name : stats.keySet()) { + CallStatisticsSummary stat = results.get(name); + if (stat == null) { + stat = new CallStatisticsSummary(name); + results.put(name, stat); + } + stat.addCallStats(stats.get(name)); + } + } + return results; + } + + /** + * CallStatistics is the class which handles values on excecution time and + * memory usage. + * Each CallStatistics object is for one particular name. + * + * @author bpoussin + */ + static public class CallStatistics implements Cloneable { + protected String name = null; + protected long calls = 0; + protected long minTime = Long.MAX_VALUE; + protected long maxTime = Long.MIN_VALUE; + protected long sumTime = 0; + protected long minMemory = Long.MAX_VALUE; + protected long maxMemory = Long.MIN_VALUE; + protected long sumMemory = 0; + /** pile contenant le temps de appel, util pour les appels recursifs */ + protected ArrayLongList times = new ArrayLongList(); + protected ArrayLongList memories = new ArrayLongList(); + protected Runtime runtime = Runtime.getRuntime(); + + public CallStatistics(String name){ + this.name = name; + } + public void enter(){ + times.add(System.nanoTime()); + memories.add(getMemory()); + } + public void exit(){ + calls ++; + + if(times.size() == 0){ + log.info("To many exit call for " + name); + return; + } + long time = times.removeElementAt(times.size() - 1); + time = System.nanoTime() - time; + if(time < minTime || minTime == Long.MAX_VALUE){ + minTime = time; + } + if(time > maxTime){ + maxTime = time; + } + sumTime += time; + + long memory = memories.removeElementAt(memories.size() - 1); + memory = getMemory() - memory; + if(memory < minMemory || minMemory == Long.MAX_VALUE){ + minMemory = memory; + } + if(memory > maxMemory){ + maxMemory = memory; + } + sumMemory += memory; + } + public String getName(){ + return name; + } + public long getCalls(){ + return calls; + } + + public long getMinTime(){ + return minTime; + } + public long getMaxTime(){ + return maxTime; + } + public long getSumTime(){ + return sumTime; + } + public long getAvgTime(){ + if (calls == 0){ + return 0; + } else { + return sumTime / calls; + } + } + + public long getMinMemory(){ + return minMemory; + } + public long getMaxMemory(){ + return maxMemory; + } + public long getSumMemory(){ + return sumMemory; + } + public long getAvgMemory(){ + if ( calls == 0) { + return 0; + } else { + return sumMemory / calls; + } + } + + protected long getMemory(){ + // runtime.gc(); + return runtime.totalMemory() - runtime.freeMemory(); + } + + @Override + public String toString(){ + return getName() + " calls=" + getCalls() + + " time=" + StringUtil.convertTime(getSumTime()) + + "(" + StringUtil.convertTime(getMinTime()) + "/" + StringUtil.convertTime(getAvgTime()) + "/" + StringUtil.convertTime(getMaxTime()) + ")" + + " memory=" + StringUtil.convertMemory(getSumMemory()) + + "(" + StringUtil.convertMemory(getMinMemory()) + "/" + StringUtil.convertMemory(getAvgMemory()) + "/" + StringUtil.convertMemory(getMaxMemory()) + ")" + ; + } + + } //CallStatistics + + /** + * This class is collecting data from different CallStatistics classes by + * using the method {@link #addCallStats(org.codelutin.util.CallAnalyse.CallStatistics)}. + * + * @author thimel + */ + static public class CallStatisticsSummary extends CallStatistics { + + public CallStatisticsSummary(String name) { + super(name); + } + + /** + * This methods read the given {@link CallStatistics} and add values to + * its own + * + * @param other an other CallStatistics object + */ + public void addCallStats(CallStatistics other) { + if (other == null || this.equals(other)) { + return; + } + calls += other.getCalls(); + if(other.getMinTime() < minTime || minTime == Long.MAX_VALUE){ + minTime = other.getMinTime(); + } + if(other.getMaxTime() > maxTime){ + maxTime = other.getMaxTime(); + } + + sumTime += other.getSumTime(); + + if(other.getMinMemory() < minMemory || minMemory == Long.MAX_VALUE){ + minMemory = other.getMinMemory(); + } + if(other.getMaxMemory() > maxMemory){ + maxMemory = other.getMaxMemory(); + } + sumMemory += other.getSumMemory(); + } + } //CallStatisticsSummary + +} // CallAnalyse + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/CallAnalyse.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/CardinalityHelper.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/CardinalityHelper.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/CardinalityHelper.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/CardinalityHelper.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,253 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Une classe avec des méthodes utiles sur les cardinalités : + * <p/> + * parser une cardinalité {@link #parseCardinalite(String, boolean)} + * <p/> + * afficher une cardinité {@link #printCardinalite(StringBuilder, String, int, int, boolean, String, String, String, String)} + * <p/> + * et pour tester des cardinalités : + * <p/> + * {@link #isMandatory(int)}, savoir si une cardinalité est obligatoire à + * partir de son min. + * <p/> + * {@link #isRepetable(int)}, savoir si une cardinalité est répétable à partir + * de son max. + * <p/> + * {@link #isMaxBounded(int)}, savoir si une cardinalité est bornée sur son max + * à partir de son max. + * <p/> + * {@link #isDefaultMandatory(int, int)}, savoir si la cardinalité est la + * cardinalité obligatoire par défaut {1}. + * <p/> + * {@link #isDefaultOptional(int, int)}, savoir si la cardinalité est la + * cardinalité optionel par défaut {0,1}. + * <p/> + * {@link #isAvailable(int, int)}, savoir si il reste encore des occurrences + * disponibles sur une cardianlité à partir d'un nombre d'oocurrence et du max + * de la cardinalité. + * + * @author tony + */ +public class CardinalityHelper { + + static final Pattern PATTERN_OPTIONAL = Pattern.compile("\\[.*\\]"); + static final Pattern PATTERN_MANDATORY = Pattern.compile("\\<.*\\>"); + + /** XXX + ou XXX * */ + public static final Pattern PATTERN_NO_MAX_BOUND = Pattern.compile("(.*)(\\+|\\*)"); + + /** XXX {n} n est un entier */ + public static final Pattern PATTERN_EXTACLY = Pattern.compile("(.*)\\{([0-9]+)\\}"); + + /** XXX {n,m} n est un entier, m est un entier ou * */ + public static final Pattern PATTERN_BOUNDED = Pattern.compile("(.*)\\{([0-9]+),([0-9]+|\\*)\\}"); + + /** + * Indique si une cardinalité est la cardinalité obligatoire par défaut {1} + * + * @param min le min de la cardinalité à tester + * @param max le max de la cardinalité à tester + * @return <code>true</code> si min==1 et max=1 + */ + public static boolean isDefaultMandatory(int min, int max) { + return min == 1 && max == 1; + } + + /** + * Indique si une cardinalité est la cardinalité optionel par défaut {0,1} + * + * @param min le min de la cardinalité à tester + * @param max le max de la cardinalité à tester + * @return <code>true</code> si min==0 && max==1 + */ + public static boolean isDefaultOptional(int min, int max) { + return min == 0 && max == 1; + } + + /** + * Indique si une cardinalité est obligatoire à partir de son min + * + * @param min le min de la cardinalité à tester + * @return <code>true</code> if min>0 + */ + public static boolean isMandatory(int min) { + return min > 0; + } + + /** + * Indique si une cardinalité est majorée à partir de son max + * + * @param max le max de la cardinalité à tester + * @return <code>true</code> si max!=-1 + */ + public static boolean isMaxBounded(int max) { + return max != -1; + } + + /** + * Indique si une cardinalité est répétable à partir de son max + * + * @param max le max de la cardinalité à tester + * @return <code>true</code> si max>0 || max==-1 + */ + public static boolean isRepetable(int max) { + return !isMaxBounded(max) || max > 1; + } + + /** + * Indique si on n'a pas encore atteint la borne max d'une cardinalité à + * partir de son max et d'un nombre d'occurrences déjà atteint. + * + * @param current le nombre d'occurence actuel + * @param max la borne max de la cardinalité + * @return <code>true</code> si la cardinalité n'a pas atteint sa borne max + */ + + public static boolean isAvailable(int current, int max) { + return !isMaxBounded(max) || current < max; + } + + /** + * Retourne le min par défault d'une cardinalité à partir du critère + * obligatoire ou non. + * + * @param mandatory le critère à tester + * @return <code>1</code> si obligatoire, 0 sinon. + */ + public static int getDefaultMin(boolean mandatory) { + return mandatory ? 1 : 0; + } + + /** + * Parse la cardinalite à la fin d'un texte. + * + * @param txt la valeur dont on cherche la cardinalité + * @param mandatory si vrai, valeurs par default {1}, sinon {0,1} + * @return un tableau contenant 3 object : le texte donné sans les + * informations de cardinalité, la répétitionMin, la répétitionMax. + */ + public static Object[] parseCardinalite(String txt, boolean mandatory) { + + Object[] result = new Object[3]; + Matcher matcher; + + // always trim the text + txt = txt.trim(); + if ((matcher = PATTERN_NO_MAX_BOUND.matcher(txt)).matches()) { + // find a no max cardinalite *|+ + result[0] = matcher.group(1).trim(); + result[1] = getDefaultMin(matcher.group(2).equals("+")); + result[2] = -1; + } else if ((matcher = PATTERN_EXTACLY.matcher(txt)).matches()) { + // found a exactly cardinalite {n} + result[0] = matcher.group(1).trim(); + result[1] = Integer.valueOf(matcher.group(2)); + result[2] = result[1]; + } else if ((matcher = PATTERN_BOUNDED.matcher(txt)).matches()) { + // found a bounded cardinalite {n,m} + result[0] = matcher.group(1).trim(); + result[1] = Integer.valueOf(matcher.group(2)); + String max = matcher.group(3); + result[2] = max.equals("*") ? -1 : Integer.valueOf(max); + } else { + // no cardinalite was found, use default values + result[0] = txt.trim(); + result[1] = getDefaultMin(mandatory); + result[2] = 1; + } + return result; + } + + /** + * Imprime dans le builder, le txt + une cardinalité. + * + * @param sb le builder + * @param txt le txt à imprimer + * @param min la caridnalité min + * @param max la cardinalité max + * @param mandatory pour indiquer dans quel cas on affiche la cardinalité : + * si elle correspond aux valeurs par défaut + * de mandatory {1} ou optionel {0,1}, pas d'impression. + * @param mo le caractère ouvrant pour un object obligatoire + * @param mc le caractère fermant pour un object obligatoire + * @param oo le caractère ouvrant pour un object optionel + * @param oc le caractère fermant pour un object optionel + */ + public static void printCardinalite(StringBuilder sb, String txt, int min, int max, boolean mandatory, String mo, String mc, String oo, String oc) { + // flag pour indiquer s'il faut ou non imprimer les bordures + boolean print = false; + + boolean maxBounded = isMaxBounded(max); + if (isMandatory(min)) { + sb.append(mo).append(txt).append(mc); + if (isDefaultMandatory(min, max)) { + if (mandatory || mo.length() > 0) { + // rien a faire on a la valeur par defaut attendue, ou la + // bordure existe et remplace la valeur par defaut + } else { + // pas de bordure, ou valeur optionel attendue, on doit imprimer la cardinalite + print = true; + } + } else { + if (!maxBounded && min == 1) { + sb.append('+'); + } else { + print = true; + } + } + } else { + sb.append(oo).append(txt).append(oc); + if (isDefaultOptional(min, max)) { + if (!mandatory || oo.length() > 0) { + // rien a faire on a la valeur par defaut attendue, ou la + // bordure existe et remplace la valeur par defaut + } else { + // pas de bordure, ou valeur optionel attendue, on doit imprimer la cardinalite + print = true; + } + } else { + if (!maxBounded) { + sb.append('*'); + } else { + print = true; + } + } + } + if (print) { + sb.append('{'); + sb.append(min); + if (max != min) { + sb.append(','); + sb.append(maxBounded ? max : "*"); + } + sb.append('}'); + } + } + + protected CardinalityHelper() { + // do not instanciate + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/CardinalityHelper.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/CategorisedListenerSet.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/CategorisedListenerSet.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/CategorisedListenerSet.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/CategorisedListenerSet.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,260 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * CategorisedListenerSet.java + * + * Created: 13 mai 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.beans.Statement; +import java.util.Iterator; +import java.util.WeakHashMap; + +/** + * Objet permettant de géré plusieurs liste de listener de facon simple. + * Chaque liste de listener est rangé en fonction d'une cle (categorie) + * Une categorie peut avoir un pere, dans ce cas si un event doit etre lancé + * sur une categorie il est aussi lancer sur le pere de la categorie. + * Mais attention l'inverse n'est pas vrai, un event lancé sur un père n'est + * jamais lancé sur ses fils. + * Il existe une Category spéciale {@link #ALL} qui permet d'envoyer un event + * a tous les listeners. + * Si cette classe est la derniere classe a conserver l'objet categorie + * alors la categorie est libere et ainsi que les listeners si c'etait aussi + * leur derniers referencements + * <p/> + * <p> Si les categories sont representees par des Class, alors vous pouvez + * utiliser la hierachie de classe pour creer de facon automatique les pere + * + * @see org.codelutin.util.ListenerSet + */ +public class CategorisedListenerSet<Listener> { // CategorisedListenerSet + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private Log log = LogFactory.getLog(CategorisedListenerSet.class); + + /** + * permet de remplacer toutes les categories. + * Si on utilise cette category, alors tous les listeners present + * seront utilisé. + */ + static public final Object ALL = new Object(); + + /** + * HashMap de ListenerSet, en cle l'objet qui caracterise la categorie + * en valeur un ListenerSet + */ + protected WeakHashMap<Object, ListenerSet<Listener>> listeners = new WeakHashMap<Object, ListenerSet<Listener>>(); + protected WeakHashMap<Object, Object> categoryParent = new WeakHashMap<Object, Object>(); + protected boolean isClassCategory = true; +// protected Class listenerClass = null; + + /** + * Construit un CategorisedListenerSet qui accepte n'importe quel type + * de listener et dont le isClassCategory est activé + */ + public CategorisedListenerSet() { + } + +// /** +// * Construit un CategorisedListenerSet qui accepte les listeners +// * dont le type est passé en parametre et dont le isClassCategory est activé +// */ +// public CategorisedListenerSet(Class listenerClass){ +// this.listenerClass = listenerClass; +// } + + /** + * @param listenerClass la classe dont doit heriter les listeners pour + * etre accepté lors de l'ajout + * @param isClassCategory si vrai et que les categorie passé en arguement + * lors de l'ajout sont de type Class alors lors du fire on recherche aussi + * les peres dans la hierarchie d'heritage de la classe (Super class et + * interfaces) + */ + public CategorisedListenerSet(Class listenerClass, boolean isClassCategory) { +// this(listenerClass); + this.isClassCategory = isClassCategory; + } + + + protected void checkCategory(Object category) { + if (category == ALL) { + throw new IllegalArgumentException("ALL category can't be use to add listener or add Category"); + } + } + + /** + * Ajoute une categorie en indiquant sont pere. Une categorie ne peut + * avoir qu'un seul pere, si la nouvelle categorie existait deja + * alors l'appel a cette methode change son pere. + * + * @param parent le pere de la categorie, null si on ne souhaite pas de pere + * @param newCategory la nouvelle caterogie + */ + public void addCategory(Object parent, Object newCategory) { + checkCategory(parent); + checkCategory(newCategory); + categoryParent.put(newCategory, parent); + } + + /** + * Ajoute un listener sur une certaine categorie, si la categorie n'existe + * alors on la crée en ne lui affectant pas de père + * + * @param category la categorie dans lequel il faut ajouter le listener + * @param l le listener a ajouter + */ + public void add(Object category, Listener l) { + checkCategory(category); + ListenerSet<Listener> listeners = getListeners(category); + listeners.add(l); + } + + /** + * Supprime un listener d'une categorie, si la categorie ou le listener + * n'existe pas, rien ne se passe. + * + * @param category la categorie dans lequel il faut supprimer le listener + * @param l le listener a supprimer + */ + public void remove(Object category, Listener l) { + ListenerSet<Listener> listeners = getListeners(category); + listeners.remove(l); + } + + /** + * Permet de lancer un event dans une categorie, l'event est aussi propagé + * sur les ancètres de la categorie + * + * @param category la categorie a partir duquel il faut lancer l'evenement + * @param methodName le nom de la méthode de la classe listener + * @param event l'objet event a passer en paramètre de la methode du + * listener + */ + public void fire(Object category, String methodName, Object event) + throws Exception { + if (log != null && log.isTraceEnabled()) { + log.trace("fire category: " + category + " method: " + methodName); + } + ListenerSet<Listener> ls = getAllListeners(category); + ls.fire(methodName, event); +/* for(Iterator i=iterator(category); i.hasNext();){ + Object o = i.next(); + Log.logDevFinest("org.codelutin.util.CategorisedListenerSet.fire", "fire on: " + o); + Statement stm = new Statement(o, methodName, new Object[]{event}); + stm.execute(); + } +*/ + } + + /** + * Permet de lancer un event dans une categorie, l'event est aussi propagé + * sur les ancètres de la categorie, si un meme objet etait listener + * dans plusieurs categories alors il ne recevra qu'une seul notification + * + * @param category la categorie a partir duquel il faut lancer l'evenement + * @param methodName le nom de la méthode de la classe listener + */ + public void fire(Object category, String methodName) throws Exception { + for (Listener l : getAllListeners(category)) { + Statement stm = new Statement(l, methodName, null); + stm.execute(); + } + } + + /** + * Retourne un Iterator sur tous les listeners qu'il faut prevenir si on + * souhaite prevenir une certaine categorie. Ceci inclue les ancetre de la + * categorie + */ + public Iterator<Listener> iterator(Object category) { + return getAllListeners(category).iterator(); + } + + /** + * Retourne un ListenerSet contenant tous les listeners c'est à dire les + * listener de la categorie demandé mais aussi les listeners des ancetres + */ + protected ListenerSet<Listener> getAllListeners(Object category) { + ListenerSet<Listener> result = new ListenerSet<Listener>(); + if (category == ALL) { + for (ListenerSet<Listener> ls : listeners.values()) { + result.addAll(ls); + } + } else { + Object parentCategory = category; + while (parentCategory != null) { + result.addAll(getListeners(parentCategory)); + if (isClassCategory && parentCategory instanceof Class) { + result.addAll(getListenersClass((Class) parentCategory)); + } + parentCategory = categoryParent.get(parentCategory); + } + } + if (log != null && log.isTraceEnabled()) { + log.trace("getAllListeners category: " + category + " result: " + result); + } + return result; + } + + protected ListenerSet<Listener> getListenersClass(Class category) { + ListenerSet<Listener> result = new ListenerSet<Listener>(); + Class superClass = category.getSuperclass(); + if (superClass != null) { + result.addAll(getAllListeners(superClass)); + } + for (Class c : category.getInterfaces()) { + result.addAll(getAllListeners(c)); + } + return result; + } + + /** + * Retourne un ListenerSet contenant seulement les listener de la categorie + * demandé. Si la categorie n'existe pas alors elle est créé. + */ + protected ListenerSet<Listener> getListeners(Object category) { + ListenerSet<Listener> result = listeners.get(category); + if (result == null) { + listeners.put(category, result = new ListenerSet<Listener>()); + } + if (log != null && log.isTraceEnabled()) { + log.trace("getListeners category: " + category + " result: " + result); + } + return result; + } + + public String toString() { + return "Listeners Category: " + categoryParent + "\nListener: " + listeners; + } + +} // CategorisedListenerSet + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/CategorisedListenerSet.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ClassLoaderUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ClassLoaderUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ClassLoaderUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ClassLoaderUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,110 @@ +package org.nuiton.util; + +import org.apache.commons.logging.LogFactory; + +import java.lang.reflect.Method; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Stack; + +/** + * A usefull class with method for ClassLoader + * + * @author chemit + */ +public class ClassLoaderUtil { + + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static final org.apache.commons.logging.Log log = LogFactory.getLog(ClassLoaderUtil.class); + + /** + * Returns the all urls to be used in a {@link java.net.URLClassLoader}. + * <p/> + * If classloader has only one url and the url is a jar, try to load in manifest class-path + * + * @param loader the classloader (if null will use system one) + * @return all the url found in the classloader + */ + static public URL[] getDeepURLs(URLClassLoader loader) { + Stack<URL> urlToTreate = new Stack<URL>(); + List<URL> urlTreated = new ArrayList<URL>(); + + // first get the urls from classloader + URL[] result = getURLs(loader); + + urlToTreate.addAll(Arrays.asList(result)); + while (!urlToTreate.isEmpty()) { + URL currentUrl = urlToTreate.pop(); + // save the url + urlTreated.add(currentUrl); + if (Resource.isJar(currentUrl.toString())) { + // jar invocation + try { + URL[] newArrayURLs = Resource.getClassPathURLsFromJarManifest(currentUrl); + if (newArrayURLs == null) { + continue; + } + List<URL> newURLs = Arrays.asList(newArrayURLs); + for (URL newURL : newURLs) { + if (!urlTreated.contains(newURL) && !urlToTreate.contains(newURL)) { + urlToTreate.add(newURL); + } + } + } catch (Exception e) { + if (log.isDebugEnabled()) { + // this is not a such error, but some jar can not be + log.debug("error with url" + currentUrl + " for reason : " + e.getMessage()); + } + } + } + } + return urlTreated.toArray(new URL[urlToTreate.size()]); + } + + /** + * Recupere la liste des urls d'un {@link java.net.URLClassLoader}. + * <p/> + * Note : Un cas particulier est positionné pour JBoss qui utilise la method getAllURLs. + * + * @param classLoader le class loader a scanner + * @return les urls du classloade. + */ + static public URL[] getURLs(URLClassLoader classLoader) { + if (classLoader == null) { + classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); + } + Method m; + try { + // Essai de récupération de la méthode getAllURLs() de RepositoryClassLoader (JBoss) + m = classLoader.getClass().getMethod("getAllURLs"); + } catch (Exception e) { + m = null; + } + URL[] result; + if (m == null) { + result = classLoader.getURLs(); + } else { + try { + result = (URL[]) m.invoke(classLoader); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } + return result; + } + + static public void printLoader(ClassLoader loader) { + log.info(loader); + if (loader instanceof URLClassLoader) { + URL[] urls = getURLs((URLClassLoader) loader); + for (URL url : urls) { + log.info(url); + } + } + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ClassLoaderUtil.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/CollectionUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/CollectionUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/CollectionUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/CollectionUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,153 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * CollectionUtil.java + * + * Created: 23 févr. 2006 09:03:39 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.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: nuitonutil/trunk/src/main/java/org/nuiton/util/CollectionUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ConverterUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ConverterUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ConverterUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ConverterUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,129 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import org.apache.commons.beanutils.ConvertUtils; +import org.apache.commons.beanutils.Converter; + +/** + * Une classe contenant des méthodes utiles sur les converters et les conversions + * + * @author tony + */ +public class ConverterUtil { + + /** le paquetage où chercher les implentations de Converter, si non présents dans le système */ + protected static final String CONVERTER_PACKAGE = "org.nuiton.util"; + + /** + * Cherche un converter pour un <code>type</code> donné. + * <p/> + * Recherche dans un premier temps dans les converteurs déjà connus. + * <p/> + * Si le type est une énum et qu'aucun converter, n'a été trouvé, on + * enregistre un nouveau convert d'enum. + * <p/> + * Sinon on tente d'instancier un converteur dans le paquetage dédié aux + * converteurs {@link #CONVERTER_PACKAGE}. + * + * @param type le type à convertir + * @return le converter trouvé, ou null si non trouvé + */ + public static <T> Converter getConverter(Class<T> type) { + Converter converter = ConvertUtils.lookup(type); + if (converter != null) { + return converter; + } + if (type.isEnum()) { + registerEnumConverter(type); + return ConvertUtils.lookup(type); + } + // on essaye de trouver un converter dans le paquetage des converters + try { + registerConverter0(type); + converter = ConvertUtils.lookup(type); + } catch (Exception e) { + throw new RuntimeException(e); + } + return converter; + } + + /** + * Convertir une valeur! + * + * @param type le type de donnée recherchée + * @param toConvert l'object a convertir + * @return la nouvelle instance de l'objet converti typé ou null + */ + @SuppressWarnings({"unchecked"}) + public static <T> T convert(Class<T> type, Object toConvert) { + + T result = null; + Converter converter = getConverter(type); + if (converter != null) { + return (T) converter.convert(type, toConvert); + } + return result; + } + + public static void registerConverter(Class type) throws IllegalAccessException, InstantiationException, ClassNotFoundException { + if (ConvertUtils.lookup(type) == null) { + registerConverter0(type); + } + } + + protected static void registerConverter0(Class type) throws IllegalAccessException, InstantiationException, ClassNotFoundException { + Class<?> aClass = Class.forName(CONVERTER_PACKAGE + "." + type.getSimpleName() + "Converter"); + Converter converter = (Converter) aClass.newInstance(); + ConvertUtils.register(converter, type); + } + + /** + * Enregistre un nouveau converter pour un type d'enum donné, avec une + * valeur par defaut. + * + * @param type le type d'enum à convertir + * @param defaultValue la valeur par defaut. + */ + public static void registerEnumConverter(Class<?> type, Object defaultValue) { + if (EnumConverter.isEnabled(type, type) && ConvertUtils.lookup(type) == null) { + Converter converter = new EnumConverter(type, defaultValue); + ConvertUtils.register(converter, type); + } + } + + /** + * Enregistre un nouveau converter pour un type d'enum donné, sans utiliser + * de valeur par defaut. + * + * @param type le type d'enum à convertir + */ + public static void registerEnumConverter(Class<?> type) { + registerEnumConverter(type, null); + } + + public static byte[] convert(char[] chars) { + byte[] bytes = new byte[chars.length]; + for (int i = 0; i < chars.length; i++) { + bytes[i] = (byte) (chars[i] & 0xff); + } + return bytes; + } + + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ConverterUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/DigestGenerator.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/DigestGenerator.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/DigestGenerator.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/DigestGenerator.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,395 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* + * Modified by Landais Gabriel, Code Lutin 2008 + * + * Works with standard org.w3c.dom XML classes + * + */ + +package org.nuiton.util; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.SortedMap; +import java.util.TreeMap; + +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.w3c.dom.ProcessingInstruction; +import org.w3c.dom.Text; + +/** + * Helper class to provide the functionality of the digest value generation. This is an implementation of the DHASH + * algorithm on . + */ +public class DigestGenerator { + + /** + * This method is an overloaded method for the digest generation for Document + * + * @param document + * @param digestAlgorithm + * @return Returns a byte array representing the calculated digest + * @throws Exception + */ + public byte[] getDigest(Document document, String digestAlgorithm) + throws Exception { + byte[] digest; + try { + MessageDigest md = MessageDigest.getInstance(digestAlgorithm); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(9); + Collection childNodes = getValidElements(document); + dos.writeInt(childNodes.size()); + for (Object childNode : childNodes) { + Node node = (Node) childNode; + if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { + dos.write(getDigest((ProcessingInstruction) node, + digestAlgorithm)); + } + else if (node.getNodeType() == Node.ELEMENT_NODE) { + dos.write(getDigest((Element) node, digestAlgorithm)); + } + } + dos.close(); + md.update(baos.toByteArray()); + digest = md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + return digest; + } + + /** + * This method is an overloaded method for the digest generation for Node + * + * @param node + * @param digestAlgorithm + * @return Returns a byte array representing the calculated digest value + * @throws Exception + */ + public byte[] getDigest(Node node, String digestAlgorithm) throws Exception { + if (node.getNodeType() == Node.ELEMENT_NODE) { + return getDigest((Element) node, digestAlgorithm); + } + if (node.getNodeType() == Node.TEXT_NODE) { + return getDigest((Text) node, digestAlgorithm); + } + if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { + return getDigest((ProcessingInstruction) node, digestAlgorithm); + } + return new byte[0]; + } + + /** + * This method is an overloaded method for the digest generation for Element + * + * @param element + * @param digestAlgorithm + * @return Returns a byte array representing the calculated digest value + * @throws Exception + */ + public byte[] getDigest(Element element, String digestAlgorithm) + throws Exception { + byte[] digest; + try { + MessageDigest md = MessageDigest.getInstance(digestAlgorithm); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(1); + dos.write(getExpandedName(element).getBytes("UnicodeBigUnmarked")); + dos.write((byte) 0); + dos.write((byte) 0); + Collection attrs = getAttributesWithoutNS(element); + dos.writeInt(attrs.size()); + for (Object attr : attrs) { + dos.write(getDigest((Attr) attr, digestAlgorithm)); + } + Node node = element.getFirstChild(); + // adjoining Texts are merged, + // there is no 0-length Text, and + // comment nodes are removed. + int length = element.getChildNodes().getLength(); + dos.writeInt(length); + while (node != null) { + dos.write(getDigest(node, digestAlgorithm)); + node = node.getNextSibling(); + } + dos.close(); + md.update(baos.toByteArray()); + digest = md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new Exception(e); + } catch (IOException e) { + throw new Exception(e); + } + return digest; + } + + /** + * This method is an overloaded method for the digest generation for ProcessingInstruction + * + * @param pi + * @param digestAlgorithm + * @return Returns a byte array representing the calculated digest value + * @throws Exception + */ + public byte[] getDigest(ProcessingInstruction pi, String digestAlgorithm) + throws Exception { + byte[] digest; + try { + MessageDigest md = MessageDigest.getInstance(digestAlgorithm); + md.update((byte) 0); + md.update((byte) 0); + md.update((byte) 0); + md.update((byte) 7); + md.update(pi.getTarget().getBytes("UnicodeBigUnmarked")); + md.update((byte) 0); + md.update((byte) 0); + md.update(pi.getNodeValue().getBytes("UnicodeBigUnmarked")); + digest = md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new Exception(e); + } catch (UnsupportedEncodingException e) { + throw new Exception(e); + } + return digest; + } + + /** + * This method is an overloaded method for the digest generation for Attr + * + * @param attribute + * @param digestAlgorithm + * @return Returns a byte array representing the calculated digest value + * @throws Exception + */ + public byte[] getDigest(Attr attribute, String digestAlgorithm) + throws Exception { + byte[] digest = new byte[0]; + if (!(attribute.getLocalName().equals("xmlns") || attribute + .getLocalName().startsWith("xmlns:"))) { + try { + MessageDigest md = MessageDigest.getInstance(digestAlgorithm); + md.update((byte) 0); + md.update((byte) 0); + md.update((byte) 0); + md.update((byte) 2); + md.update(getExpandedName(attribute).getBytes( + "UnicodeBigUnmarked")); + md.update((byte) 0); + md.update((byte) 0); + md.update(attribute.getValue().getBytes("UnicodeBigUnmarked")); + digest = md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new Exception(e); + } catch (UnsupportedEncodingException e) { + throw new Exception(e); + } + } + return digest; + } + + /** + * This method is an overloaded method for the digest generation for Text + * + * @param text + * @param digestAlgorithm + * @return Returns a byte array representing the calculated digest value + * @throws Exception + */ + public byte[] getDigest(Text text, String digestAlgorithm) throws Exception { + byte[] digest; + try { + MessageDigest md = MessageDigest.getInstance(digestAlgorithm); + md.update((byte) 0); + md.update((byte) 0); + md.update((byte) 0); + md.update((byte) 3); + md.update(text.getTextContent().getBytes("UnicodeBigUnmarked")); + digest = md.digest(); + } catch (NoSuchAlgorithmException e) { + throw new Exception(e); + } catch (UnsupportedEncodingException e) { + throw new Exception(e); + } + return digest; + } + + /** + * This method is an overloaded method for getting the expanded name namespaceURI followed by the local name for + * Element + * + * @param element + * @return Returns the expanded name of Element + */ + public String getExpandedName(Element element) { + return element.getNamespaceURI() + ":" + element.getLocalName(); + } + + /** + * This method is an overloaded method for getting the expanded name namespaceURI followed by the local name for + * Attr + * + * @param attribute + * @return Returns the expanded name of the Attr + */ + public String getExpandedName(Attr attribute) { + return attribute.getNamespaceURI() + ":" + attribute.getLocalName(); + } + + /** + * Gets the collection of attributes which are none namespace declarations for an Element + * + * @param element + * @return Returns the collection of attributes which are none namespace declarations + */ + public Collection getAttributesWithoutNS(Element element) { + SortedMap map = new TreeMap(); + for (int i = 0; i < element.getAttributes().getLength(); i++) { + Attr attribute = (Attr) element.getAttributes().item(i); + if (!(attribute.getLocalName().equals("xmlns") || attribute + .getLocalName().startsWith("xmlns:"))) { + map.put(getExpandedName(attribute), attribute); + } + } + return map.values(); + } + + /** + * Gets the valid element collection of an Document. Element and ProcessingInstruction only + * + * @param document + * @return Returns a collection of ProcessingInstructions and Elements + */ + public Collection getValidElements(Document document) { + ArrayList list = new ArrayList(); + NodeList childNodes = document.getChildNodes(); + for (int i = 0; i < childNodes.getLength(); i++) { + Node node = childNodes.item(i); + if (node.getNodeType() == Node.ELEMENT_NODE + || node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { + list.add(node); + } + } + return list; + } + + /** + * Gets the String representation of the byte array + * + * @param array + * @return Returns the String of the byte + */ + public String getStringRepresentation(byte[] array) { + String str = ""; + for (byte anArray : array) { + str += anArray; + } + return str; + } + + /** + * Compares two Nodes for the XML equality + * + * @param node + * @param comparingNode + * @param digestAlgorithm + * @return Returns true if the Node XML contents are equal + * @throws Exception + */ + public boolean compareNode(Node node, Node comparingNode, + String digestAlgorithm) throws Exception { + return Arrays.equals(getDigest(node, digestAlgorithm), getDigest( + comparingNode, digestAlgorithm)); + } + + /** + * Compares two Documents for the XML equality + * + * @param document + * @param comparingDocument + * @param digestAlgorithm + * @return Returns true if the Document XML content are equal + * @throws Exception + */ + public boolean compareDocument(Document document, + Document comparingDocument, String digestAlgorithm) + throws Exception { + return Arrays.equals(getDigest(document, digestAlgorithm), getDigest( + comparingDocument, digestAlgorithm)); + } + + /** + * Compares two Attributes for the XML equality + * + * @param attribute + * @param comparingAttribute + * @param digestAlgorithm + * @return Returns true if the Document XML content are equal + * @throws Exception + */ + public boolean compareAttribute(Attr attribute, Attr comparingAttribute, + String digestAlgorithm) throws Exception { + return Arrays.equals(getDigest(attribute, digestAlgorithm), getDigest( + comparingAttribute, digestAlgorithm)); + } + + /** String representing the MD5 digest algorithm */ + public static final String md5DigestAlgorithm = "MD5"; + + /** String representing the SHA digest algorithm */ + public static final String shaDigestAlgorithm = "SHA"; + + /** String representing the SHA1 digest algorithm */ + public static final String sha1DigestAlgorithm = "SHA1"; +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/DigestGenerator.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/EnumConverter.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/EnumConverter.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/EnumConverter.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/EnumConverter.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,136 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import org.apache.commons.beanutils.ConversionException; +import org.apache.commons.beanutils.Converter; +import static org.apache.commons.logging.LogFactory.getLog; +import static org.nuiton.i18n.I18n._; + +import java.util.EnumSet; + +/** + * classe pour convertir une chaine en un objet Enum type-safe en + * connaissant le type d'enumération utilisée {@link #enumType}. + * <p/> + * Il est possible aussi de convertir une Enum à partir de sa valeur ordinal. + * <p/> + * Pour enregister un nouveau convertissemnt pour un type d'Enum utiliser les + * méthodes * {@link ConverterUtil#registerEnumConverter(Class)}, + * et {@link ConverterUtil#registerEnumConverter(Class,Object)} . + * + * @author chemit + * @see Enum + * @see Enum#ordinal() + */ +public class EnumConverter implements Converter { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static org.apache.commons.logging.Log log = getLog(EnumConverter.class); + + /** valeur par default à utiliser, si pas non trouvée et {@link #useDefault} actif. */ + protected Object defaultValue; + + /** flag pour utiliser la valeur par defaut {@link #defaultValue} si non trouvé. */ + protected boolean useDefault; + + /** le type de l'énumération à convertir */ + protected Class<?> enumType; + + public Object convert(Class aClass, Object value) { + if (value == null) { + if (useDefault) { + return defaultValue; + } + throw new ConversionException(_("lutinutil.error.convertor.noValue", this)); + } + if (isEnabled(aClass, enumType)) { + Object result; + if (isEnabled(value.getClass(), enumType)) { + result = value; + return result; + } + if (value instanceof String) { + try { + result = valueOf(aClass, value); + } catch (IllegalArgumentException e) { + // try an ordinal conversion + result = convertFromOrdinal(aClass, value); + } + return result; + } + if (value instanceof Integer) { + // try a ordinal conversion + result = convertFromOrdinal(aClass, value); + return result; + } + } + throw new ConversionException(_("lutinutil.error.no.convertor", aClass.getName(), value)); + } + + public EnumConverter(Class<?> enumType, Object defaultValue) { + this.enumType = enumType; + this.defaultValue = defaultValue; + useDefault = defaultValue != null; + if (log.isDebugEnabled()) { + log.debug(toString() + '<' + enumType + '>'); + } + } + + public EnumConverter(Class<?> enumType) { + this(enumType, null); + } + + protected static boolean isEnabled(Class aClass, Class<?> enumType) { + return aClass != null && aClass.isEnum() && aClass == enumType; + } + + protected Object convertFromOrdinal(Class aClass, Object value) { + Object result = null; + try { + int ordinal = Integer.valueOf(value + ""); + EnumSet<?> vals = allOf(aClass); + if (ordinal > -1 && ordinal < vals.size()) { + for (Enum<?> val : vals) { + if (val.ordinal() == ordinal) { + result = val; + break; + } + } + } + } catch (NumberFormatException e1) { + // quiet conversion + result = null; + } + return result; + } + + @SuppressWarnings({"unchecked"}) + protected Object valueOf(Class aClass, Object value) { + Object result; + result = Enum.valueOf(aClass, (String) value); + return result; + } + + @SuppressWarnings({"unchecked"}) + protected EnumSet<?> allOf(Class aClass) { + EnumSet<?> vals; + vals = EnumSet.allOf(aClass); + return vals; + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/EnumConverter.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/EnumEditor.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/EnumEditor.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/EnumEditor.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/EnumEditor.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,51 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import static org.nuiton.util.CollectionUtil.toGenericSet; + +import javax.swing.JComboBox; +import java.util.EnumSet; + +/** + * Une éditeur d'enum. + * + * @author chemit + */ +public class EnumEditor extends JComboBox { + + /** serialVersionUID */ + private static final long serialVersionUID = 2693771553067104538L; + + protected Class<? extends Enum<?>> type; + + public static EnumEditor newEditor(Class<?> type) { + return new EnumEditor(type); + } + + public EnumEditor(Class<?> type) { + super(buildModel(type)); + } + + protected static Object[] buildModel(Class<?> type) { + Class<Enum> enumClass = ReflectUtil.getEnumClass(type); + EnumSet result = EnumSet.allOf(enumClass); + return toGenericSet(result, Object.class).toArray(new Object[result.size()]); + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/EnumEditor.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ExceptionUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ExceptionUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ExceptionUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ExceptionUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,48 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * +* ExceptionUtil.java +* +* Created: Thu Aug 29 2002 +* +* @author <poussin@codelutin.com> +* Copyright Code Lutin +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.nuiton.util; + +import java.io.PrintWriter; +import java.io.StringWriter; + +public class ExceptionUtil{ // ExceptionUtil + + protected ExceptionUtil() { + + } + + static public String stackTrace(Throwable eee){ + StringWriter result = new StringWriter(); + eee.printStackTrace(new PrintWriter(result)); + return result.toString(); + } + +} // ExceptionUtil Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ExceptionUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/FileCompletion.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/FileCompletion.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/FileCompletion.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/FileCompletion.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,258 @@ +/* + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.nuiton.util; + +import org.nuiton.i18n.I18n; +import static org.nuiton.i18n.I18n._; + +import java.io.Console; +import java.io.File; +import java.io.FilenameFilter; +import java.io.IOException; +import java.util.Locale; + +/** + * <p> + * Class d'aide a la saisie de chemin de fichier + * </p> + * <p> + * Integration : + * </p> + * <pre> + * (le 1er argument definit si l'on peut creer un fichier (ex : pour enregistrer)) + * (le 2eme definit si la sorti est possible sans saisir un fichier) + * FileCompletion fc = new FileCompletion(true,true); + * if (fc.consoleAvailable()) + * System.out.print(fc.read()); + * </pre> + * <p> + * Utilisation : + * </p> + * <p> + * ".." pour annuler ou pour revenir au repertoire précédent + * </p> + * <p> + * Entrer pour afficher la liste des fichiers, ou pour compléter le chemin + * </p> + * <p> + * Entrer pour afficher la liste des fichiers, ou pour compléter le chemin + * </p> + * Saisir "!s" a la fin du nom de fichier pour l'enregistrer (si l'option est active) + * <p> + * </p> + * Saisir "!q" pour quitter et renvoyer null (si l'option est active) + * <p> + * Limitation : + * </p> + * <p> + * FIXME: Si l'enregistrement est active, enregistrer un fichier finissant par "!s" est impossible + * </p> + * <p> + * FIXME: Ouvrir un fichier finissant par ".." l'est égualement + * </p> + * <p> + * FIXME: Si la sortie est ecive, un fichier "!q" ne peut pas etre utilise + * </p> + * + * @author Letellier Sylvain + */ +public class FileCompletion { + private boolean exit; + private boolean creation; + private boolean consoleAvailable; + + private Console console; + + /** + * Constructeur + * + * @param creation TODO + * @param exit TODO + */ + public FileCompletion(boolean creation, boolean exit) { + this.exit = exit; + this.creation = creation; + + // TODO does this util class init i18n ? + if (Locale.getDefault().getLanguage().equals("fr")) { + I18n.init("fr", "FR"); + } + else { + I18n.init("en", "US"); + } + + console = System.console(); + consoleAvailable = (console != null); + } + + /** + * demande a l'utilisateur de saisir un chemin + * + * @return TODO + * @throws IOException TODO + */ + public String read() throws IOException { + if (creation) { + System.out.println(_("lutinutil.fileCompletion.save")); + } + if (exit) { + System.out.println(_("lutinutil.fileCompletion.exit")); + } + System.out.println(_("lutinutil.fileCompletion.cancel")); + System.out.println(_("lutinutil.fileCompletion.enter")); + String line = System.getProperty("user.dir"); + File f; + line = line + readLine("> " + line + File.separator); + f = new File(line); + String moreLastLine = line; + boolean isDirectory = true; + do { + if (f.isDirectory() || !f.exists()) { + String lastLine = line; + if (!f.exists() && !f.isDirectory()) { + File fTmp = f.getParentFile(); + String file = f.getName(); + if (file.matches("^.*\\!s$") && creation) + return f.getCanonicalPath().substring(0, + f.getCanonicalPath().length() - 2); + if (file.matches("^.*\\!q$") && exit) + return null; + if (file.matches("^.*\\.\\.$")) + line = fTmp.getCanonicalPath(); + else { + Filter filtre = new Filter(); + filtre.setFilter(file); + String[] listFichier = fTmp.list(filtre); + if (listFichier.length == 1) { + if (!(fTmp.getParentFile() == null)) { + line = fTmp.getCanonicalPath() + File.separator + + listFichier[0]; + } + else { + line = fTmp.getCanonicalPath() + listFichier[0]; + } + } else if (listFichier.length > 1) { + afficherListe(listFichier); + } else { + line = moreLastLine; + } + + } + } else if (f.exists() && f.isDirectory() + && !(f.getParentFile() == null)) { + Filter filtre = new Filter(); + filtre.setFilter(f.getName()); + String[] listFichier = f.getParentFile().list(filtre); + if (listFichier.length <= 1 + || line.charAt(line.length() - 1) == File.separatorChar) { + + line = f.getCanonicalPath(); + isDirectory = true; + } else if (listFichier.length > 1) { + isDirectory = false; + afficherListe(listFichier); + } + + } + moreLastLine = line; + f = new File(line); + if (f.isDirectory() && isDirectory + && !(line.charAt(line.length() - 1) == File.separatorChar)) + line = line + File.separator; + String read = readLine("> " + line); + line = line + read; + f = new File(line); + if (read.equals("") || read.equals(File.separator)) + afficherListe(f.list()); + + if (line.matches(".* " + File.separator + ".*") + || line.matches(".*" + File.separator + " .*")) + line = lastLine; + f = new File(line); + } + } while (!f.exists() || f.isDirectory()); + return line; + } + + /** Filtre les fichiers a afficher */ + class Filter implements FilenameFilter { + private String filtre; + + /** + * @param dir TODO + * @param name TODO + * @return boolean + */ + public boolean accept(File dir, String name) { + return name.startsWith(filtre); + } + + /** + * le parametre est le debut des noms de fichiers a afficher + * + * @param s TODO + */ + public void setFilter(String s) { + filtre = s; + } + } + + /** + * @param path TODO + * @return String + */ + private String readLine(String path) { + String lineNonNull = null; + while (lineNonNull == null) + lineNonNull = console.readLine(path); + return lineNonNull; + } + + /** @return boolean */ + public boolean consoleAvailable() { + return consoleAvailable; + } + + /** @param listefichiers TODO */ + private void afficherListe(String[] listefichiers) { + if (listefichiers != null) { + int i = 0; + int nomMax = 0; + for (String l : listefichiers) + nomMax = Math.max(nomMax, l.length()); + // System.out.println(); + for (String l : listefichiers) { + String space = ""; + int nbSpace = (nomMax + 1) - l.length(); + for (int j = 0; j < nbSpace; j++) { + space += " "; + } + if (i++ < 2) + System.out.print(l + space); + else { + i = 0; + System.out.println(l); + } + } + System.out.println(); + } + } +} + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/FileCompletion.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/FileUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/FileUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/FileUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/FileUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,903 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * FileUtil.java + * + * Created: 22 nov. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.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 File getCurrentDirectory() { + return currentDirectory; + } + + 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 le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + * @see #getFile(javax.swing.filechooser.FileFilter[]) + */ + static public File getFile(String... patternOrDescriptionFilters) { + File result; + result = getFile(null, patternOrDescriptionFilters); + 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 le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + */ + static public File getFile(javax.swing.filechooser.FileFilter... filters) { + File result = getFile(null, 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 parent le component parent du dialog + * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données + * par deux, le pattern du filtre + la description du filtre + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + * @see #getFile(javax.swing.filechooser.FileFilter[]) + */ + static public File getFile(java.awt.Component parent, String... patternOrDescriptionFilters) { + File result; + result = getFile("Ok", "Ok", parent, patternOrDescriptionFilters); + 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 title le titre de la boite de dialogue + * @param approvalText le label du boutton d'acceptation + * @param parent le component parent du dialog + * @param patternOrDescriptionFilters les filtres a utiliser, les chaines doivent etre données + * par deux, le pattern du filtre + la description du filtre + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + * @see #getFile(javax.swing.filechooser.FileFilter[]) + */ + static public File getFile(String title, String approvalText,java.awt.Component parent, 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(title, approvalText, parent, 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 parent le component parent du dialog + * @param filters les filtres a ajouter + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + */ + static public File getFile(java.awt.Component parent, javax.swing.filechooser.FileFilter... filters) { + File result = getFile("Ok", "Ok", parent, 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 title le titre de la boite de dialogue + * @param approvalText le label du boutton d'acceptation + * @param parent le component parent du dialog + * @param filters les filtres a ajouter + * @return le fichier accepté, ou null si rien n'est chois ou l'utilisateur a annulé + */ + static public File getFile(String title, String approvalText, java.awt.Component parent, 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); + chooser.setDialogTitle(title); + int returnVal = chooser.showDialog(parent, approvalText); + 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; + } + + /** + * @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(null,"Ok", "Ok"); + } + + /** + * @param title le nom de la boite de dialogue + * @param approvalText le texte de l'action d'acceptation du répertoire dans le file chooser + * @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) { + String result = getDirectory(null, title, approvalText); + return result; + } + + /** + * @param parent le component parent du dialog + * @param title le nom de la boite de dialogue + * @param approvalText le texte de l'action d'acceptation du répertoire dans le file chooser + * @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(java.awt.Component parent, 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(parent, 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; + } + + /** + * Permet de convertir un fichier en un tableau de byte + * + * @param file le fichier source à convertire + * @return le contenu du fichier sous la forme d'un tableau de bytes. + * @throws IOException if any io pb + */ + 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 recopier un stream dans un fichier + * + * @param src the incoming stream to grab + * @param dst the dst file + * @return the file filled by incoming input stream + * @throws IOException if any io pb + * @throws NullPointerException if src or dst parameter is null + */ + static public File inputStreamToFile(InputStream src, File dst) throws IOException, NullPointerException { + if (src == null) { + throw new NullPointerException("parameter 'src' can not be null"); + } + if (dst == null) { + throw new NullPointerException("parameter 'dst' can not be null"); + } + + ByteArrayOutputStream result = new ByteArrayOutputStream(); + BufferedOutputStream tmp = new BufferedOutputStream(result); + for (int b = src.read(); b != -1; b = src.read()) { + tmp.write(b); + } + src.close(); + tmp.close(); + byteToFile(result.toByteArray(), dst); + return dst; + } + + /** + * Permet de convertir des bytes en fichier, le fichier sera automatiquement + * supprimé a la fin de la JVM. + * + * @param bytes the array of bytes to copy in dstination file + * @return le fichier temporaire contenant les bytes + * @throws IOException if any io pb + */ + 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 the array of bytes to put in the given destination file + * @param file le fichier dans lequel il faut ecrire les bytes + * @return le fichier passé en parametre + * @throws IOException if any io pb + */ + 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 the given reader + * @return the reader on the given file + * @throws IOException if any io pb + */ + 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 the given file + * @param encoding (ISO-8859-1, UTF-8, ...) + * @return the buffered reader in the given encoding + * @throws IOException if any io pb + */ + 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 the given file + * @return the writer on the given file + * @throws IOException if any io pb + */ + 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 the given file + * @param encoding (ISO-8859-1, UTF-8, ...) + * @return the buffered writer on the given file with given encoding + * @throws IOException if any io pb + */ + 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; + } + + + /** + * 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 if any io pb + */ + 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 le prefix du repertoire a creer + * @param suffix le suffix du repertoire a creer. + * @return the temprary created file + * @throws java.io.IOException if any io pb + */ + 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 the first file + * @param f2 the second file + * @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 le contenu du fichier + * @throws IOException if any io pb + */ + 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 { + //fixme on doit tester le retour de la méthode, car il se peut que le répertoire + // ne puisse être crée. + 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 { + //fixme on doit tester le retour de la méthode, car il se peut que le répertoire + // ne puisse être crée. + 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 if any io pb + */ + 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 if any io pb + */ + 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 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 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 flag pour indiquer si on doit descendre dans les sous répertoires + * @return une liste d'objet {@link 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 un flag pour indiquer si on doit descendre dans les répertoires + * @return une liste d'objet {@link 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 le chemin du répertoire à supprimer + * @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 le répertoire à supprimer + * @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 (File aList : list) { + result = result && walkAfter(aList, 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 (File aList : list) { + result = result && walkBefore(aList, 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 { + //fixme on doit tester le retour de la méthode, car il se peut que le répertoire + // ne puisse être copié. + 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 le répertoire source à copier + * @param destDir le répertoire destination où copier + * @param includePatterns les patterns que doivent resperter les + * fichiers/repertoires pour etre copié. Si vide alors tout est copié + * @throws IOException if any io pb + */ + 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 le répertoire source à copier + * @param destDir le répertoire destination où copier + * @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 if any io pb + */ + 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 le répertoire source à copier + * @param destDir le répertoire destination où copier + * @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 if any io pb + */ + 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); + //fixme on doit tester le retour de la méthode, car il se peut que le répertoire + // ne puisse être copié. + destFile.mkdirs(); + } else { + log.debug("copy " + path + " to " + destFile); + copy(file, destFile); + } + } + } + } + + /** + * @param b first operande + * @param c seconde operande + * @return b^c + * @deprecated Y'a un opérateur java qui fait ca très bien :) il s'agit de ^ + */ + static private boolean xor(boolean b, boolean c) { + if (b) { + return !c; + } else { + return c; + } + } + + /** + * @param file le fichier à tester. + * @param includePatterns les patterns pour accepeter le fichier depuis son nom + * @return <code>true</code> si le fichier est accepté, <code>false> autrement. + */ + 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: nuitonutil/trunk/src/main/java/org/nuiton/util/FileUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverter.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/FormatConverter.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverter.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverter.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,96 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * FormatConverter.java + * + * Created: 14 septembre 2005 00:55:19 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import org.nuiton.util.FormatMap.Format; + +/** + * Un converter est un objet qui permet de passé d'une representation d'un + * objet vers une autre representation. Le mininum que converter doit savoir + * faire, est de converter une representation Java vers le format qu'il + * gère et inversement. Pour des raisons d'optimisation, il est possible + * qu'un converter sache passé d'un autre type que java vers sa representation + * pour eviter une conversion supplémentaire qui pourrait-etre couteuse. + * + * @param <A> le type de l'objet a convertir + */ +public interface FormatConverter<A> { // FormatConverter + + static final public Format FORMAT_JAVA = new Format("Format Java"); + + /** + * Convertie une valeur vers la representation FORMAT géré par cette classe + * + * @param factory la factory utilisable pour rechercher d'autre converter + * si la representation Java n'est pas presente dans values et que l'on + * en a besoin + * @param format le format souhaité en sortie + * @param values une map contenant les différentes representation de la + * meme valeur. Les cles de la map sont les valeurs retournés par la + * methode getFormat(). + * @param args des arguments qui peuvent-être utile pour la conversion. + * par exemple si dans une application on a construit son propre + * converter et que pour la conversion, on a besoin d'un Context applicatif + * il peut-etre passé dans les args. Si le converter a besoin d'autre + * converter les memes args lui seront passé. + * @return l'objet dans la representation demandés par type + * @throws IllegalArgumentException si auncun moyen n'est trouve pour + * convertir une des valeurs de values dans le format géré par cette classe. + * Ou s'il manque dans les args des objets utils pour la conversion. + */ + public A convert(FormatConverterFactory factory, + Format format, FormatMap values, Object... args); + + /** + * Convertie une valeur vers le Java + * + * @param factory la factory utilisable pour rechercher d'autre converter + * si la representation Java n'est pas presente dans values et que l'on + * en a besoin + * @param format le format à utiliser comme valeur d'entré + * @param values une map contenant les différentes representation de la + * meme valeur. La valeur interessante dans la map pour cette methode + * est celle retournée par values.get(getFormat()) si cet appel, ne + * retourne pas quelque chose de valid, la methode doit lever une exception + * @param args des arguments qui peuvent-être utile pour la conversion. + * par exemple si dans une application on a construit son propre + * converter et que pour la conversion, on a besoin d'un Context applicatif + * il peut-etre passé dans les args. Si le converter a besoin d'autre + * converter les memes args lui seront passé. + * @return la valeur java + * @throws IllegalArgumentException si le format géré par cette classe n'est + * pas trouvé dans les values. Ou s'il manque dans les args des objets utils + * pour la conversion. + */ + public Object unconvert(FormatConverterFactory factory, + Format format, FormatMap values, Object... args); + +} // FormatConverter + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverter.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverterFactory.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/FormatConverterFactory.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverterFactory.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverterFactory.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,189 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * FormatConverterFactory.java + * + * Created: 14 septembre 2005 00:19:51 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import org.apache.commons.collections.map.MultiKeyMap; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.FormatMap.Format; + +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedList; + +/** + * Factory permet d'enregistrer des objets de changement de format, et de + * les recupérer pour les utiliser. + * Les objets converter doivent au moins savoir convertir les objets depuis + * une representation Java. Pour des raisons d'optimisation, il est possible + * qu'il sache aussi convertir a partir d'autre representation, qui si elle + * existe sont moins couteuse a convertir. + * Il faut aussi que les converter sache convertir de leur representation vers + * un objet Java. + * par exemple si on enregistre les converiseurs suivant: + * <pre> + * addConverter(new MatrixToXMLFormatConverter()); + * addConverter(new MatrixToSQLFormatConverter()); + * FormatConverterFactory.convert(Matrix.class, MatrixToXMLFormatConverter.TYPE, + * values, AppContext); + * </pre> + * Dans ce cas pour des raisons d'optimisation + */ +public class FormatConverterFactory { // FormatConverterFactory + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private Log log = LogFactory.getLog(FormatConverterFactory.class); + + static protected FormatConverterFactory instance = null; + /** <Class, from, to -> FormatConverter> */ + protected MultiKeyMap converters = new MultiKeyMap(); + + synchronized static public FormatConverterFactory getInstance() { + if (instance == null) { + instance = new FormatConverterFactory(); + } + return instance; + } + + /** + * Permet d'enregitrer un converter pour permettre la convertion d'une + * certain type Java d'une representation vers une autre. + * par exemple le type String d'un objet Java vers une chaine XML + * + * @param clazz la class de la representation Java de l'objet + * @param format le format géré par le FormatConverter + * @param c le converter a enregistrer + */ + public void addConverter(Class clazz, Format format, FormatConverter c) { + converters.put(clazz, format, c); + } + + /** + * permet de recupere le converter pour la classe souhaitée. + * + * @param clazz la classe de l'objet dont on souhaite le converter + * @param format qui doit être géré par le converter + * @param defaultConverter si aucun converter trouvé, ce converter est + * retourné + * @return le converter souhaité ou defaultConverter + */ + public FormatConverter getConverter(Class clazz, Format format, + FormatConverter defaultConverter) { + FormatConverter result = (FormatConverter) converters.get(clazz, format); + if (result == null) { + result = defaultConverter; + } + return result; + } + + /** + * @return retourne null si aucun converter trouvé + * @see #getConverter(Class, FormatMap.Format, FormatConverter) + */ + public FormatConverter getConverter(Class clazz, Format format) { + return getConverter(clazz, format, null); + } + + /** + * Permet de retrouver le meilleur converter disponible pour l'argument + * clazz + * + * @param clazz la classe de l'objet dont on souhaite le converter + * @param format qui doit être géré par le converter + * @param defaultConverter si aucun converter trouvé, ce converter est + * retourné + * @return le converter souhaité ou defaultConverter + */ + public FormatConverter findConverter(Class clazz, Format format, + FormatConverter defaultConverter) { + FormatConverter result = null; + + LinkedList<Class> interfaces = new LinkedList<Class>(); + // On recherche la le transformer le plus spécifique sur les Class + Class parent = clazz; + while (result == null && parent != null) { + Collections.addAll(interfaces, parent.getInterfaces()); + result = getConverter(parent, format); + parent = parent.getSuperclass(); + } + + // Si on a pas encore trouve de transformer on recherche + // un encodeur/decodeur pour les interfaces + for (Iterator<Class> i = interfaces.iterator(); result == null && i.hasNext();) { + result = getConverter(i.next(), format); + } + + if (result == null) { + log.warn("Aucun converter trouvé pour le type: " + clazz); + result = defaultConverter; + } + log.debug("converter " + result + " utilisé pour le type: " + clazz); + + return result; + } + + /** + * @return retourne null si aucun converter trouvé + * @see #findConverter(Class, FormatMap.Format, FormatConverter) + */ + public FormatConverter findConverter(Class clazz, Format format) { + return findConverter(clazz, format, null); + } + + public Object convert(Format format, FormatMap values, Object... args) { + FormatConverter c = findConverter(values.getType(), format); + if (c == null) { + throw new IllegalArgumentException("Aucun converter utilisable pour les arguments donnés class: " + values.getType().getName() + " format: " + format); + } + return c.convert(this, format, values, args); + } + + public Object unconvert(Format format, FormatMap values, Object... args) { + FormatConverter c = findConverter(values.getType(), format); + if (c == null) { + throw new IllegalArgumentException("Aucun converter utilisable pour les arguments donnés"); + } + return c.unconvert(this, format, values, args); + } + + public Object convert(FormatConverter defaultConverter, + Format format, FormatMap values, Object... args) { + FormatConverter c = findConverter(values.getType(), format, defaultConverter); + return c.convert(this, format, values, args); + } + + public Object unconvert(FormatConverter defaultConverter, + Format format, FormatMap values, Object... args) { + FormatConverter c = findConverter(values.getType(), format, defaultConverter); + return c.unconvert(this, format, values, args); + } + +} // FormatConverterFactory + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/FormatConverterFactory.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/FormatMap.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/FormatMap.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/FormatMap.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/FormatMap.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,190 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * FormatMap.java + * + * Created: 16 septembre 2005 10:41:58 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ +package org.nuiton.util; + +import org.nuiton.util.FormatMap.Format; + +import java.util.HashMap; +import java.util.Map; + +/** + * Classe servant de conteneur pour les différentes representation d'un objet + * Les representations doivents être des instances de {@link Format}. Le mieux + * est lors de l'ecriture des convertisseurs pour un nouveau format est de + * créer une instance final static de {@link Format} Format pour representer + * ce format + * <p/> + * <h2>Utilisation</h2> + * <pre> + * FormatMap values = new FormatMap(MonObject.class); + * values.put(FormatConverter.FORMAT_JAVA, monInstance); + * Element xml = (Element)values.convert(XMLConverter.FORMAT_XML); + * Object sql = values.convert(SQLConverter.FORMAT_SQL); + * </pre> + * <pre> + * FormatMap values = new FormatMap(MonObject.class); + * values.put(FormatConverter.FORMAT_XML, monInstanceEnXML); + * Object sql = values.convert(SQLConverter.FORMAT_SQL); + * </pre> + * Dans ce second cas, la demande de la version SQL, transforme automatiquement + * la representation XML qui est la seul presente en Java, puis a partir de + * cette representation Java, on recupere la representation SQL. Bien sur + * Si le convertisseur SQL, peut directement convertir le XML en SQL, alors + * la conversion Java ne sera pas faite. + * <p/> + * Il est souvent plus simple de faire une petite classe avec les methodes + * getSQL() et getXML(), qui retourne les valeurs directement dans le bon type + * et qui n'ont pas besoin d'argument. + */ +public class FormatMap extends HashMap<Format, Object> { // FormatMap + + /** */ + private static final long serialVersionUID = -3386611811885092898L; + + static public class Format { + + protected String name = null; + + public Format(String name) { + this.name = name; + } + + @Override + public String toString() { + return name; + } + } + protected Class<?> clazz = null; + + public FormatMap(Class<?> clazz) { + this.clazz = clazz; + } + + public Class<?> getType() { + return clazz; + } + + /** + * Met a jour la valeur de l'objet. Toutes les autres valeurs calculées + * sont oubliées et seront recalculé en fonction de cette nouvelle valeur + * + * @param format le format a utiliser + * @param value + */ + public void setValue(Format format, Object value) { + clear(); + put(format, value); + } + + /** + * Utilise le FormatConverterFactory par defaut pour la conversion + * + * @param format le format a utiliser + * @param args les arguments + * @return l'objet converti + */ + public Object convert(Format format, Object... args) { + return convert(FormatConverterFactory.getInstance(), format, args); + } + + /** + * Recupere la valeur dans le format demandé + * + * @param factory la FormatConverterFactory a utiliser + * @param format le format souhaité + * @param args des arguments facultatifs en fonction du context d'utilisation + * @return l'objet converti + */ + public Object convert(FormatConverterFactory factory, Format format, + Object... args) { + Object result = null; + Map<Format, Object> values = this; + //if (!values.containsKey(format) || + // !format.equals(FormatConverter.FORMAT_JAVA)) { + // throw new IllegalArgumentException("Aucun valeur disponible"); + //} + + if (values.containsKey(format)) { + result = values.get(format); + } else if (format.equals(FormatConverter.FORMAT_JAVA)) { + // on recherche une representation, que l'on convertie en Java + if (values.isEmpty()) { + throw new IllegalArgumentException("Aucun valeur disponible"); + } + Format otherFormat = values.keySet().iterator().next(); + result = unconvert(factory, otherFormat, args); + values.put(format, result); + } else { + result = factory.convert(format, this, args); + // on stocke la valeur trouver pour les prochaines fois + values.put(format, result); + } + + return result; + } + + /** Utilise le FormatConverterFactory par defaut pour la conversion + * @param format le format utilise + * @param args + * @return l'objet java + */ + public Object unconvert(Format format, Object... args) { + return unconvert(FormatConverterFactory.getInstance(), format, args); + } + + /** + * Donne la representation Java de l'objet en essayant de partir de la + * representation passé en parametre. + * + * @param factory la factory a utiliser + * @param format le format de départ souhaité + * @param args des arguments facultatifs en fonction du context d'utilisation + * @return l'objet java + */ + public Object unconvert(FormatConverterFactory factory, Format format, + Object... args) { + Object result = null; + Map<Format, Object> values = this; + if (!values.containsKey(format) && + !values.containsKey(FormatConverter.FORMAT_JAVA)) { + throw new IllegalArgumentException("Aucun valeur disponible"); + } + + // si on a deja la representation Java on la retourne tout de suite + if (values.containsKey(FormatConverter.FORMAT_JAVA)) { + result = values.get(FormatConverter.FORMAT_JAVA); + } else if (values.containsKey(format)) { + result = factory.unconvert(format, this, args); + values.put(FormatConverter.FORMAT_JAVA, result); + } + + return result; + } +} // FormatMap + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/FormatMap.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/GZUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,96 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * GZUtil.java + * + * Created: 3 nov. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public class GZUtil { // GZUtil + + /** Retourne la string decompressee */ + public static StringBuffer bytesToStringBuffer(byte[] in) { + try { + if (in == null || in.length == 0) { + return new StringBuffer(""); + } + GZIPInputStream gz = new GZIPInputStream(new BufferedInputStream(new ByteArrayInputStream(in))); + StringBuffer sb = new StringBuffer(); + int c; + + while ((c = gz.read()) != -1) { + sb.append((char) c); + } + gz.close(); + return sb; + } + catch (IOException eee) { + throw new GZUtilException("Probleme dans la decompression", eee); + } + } + + /** Retourne la string decompressee */ + public static String bytesToString(byte[] in) { + return bytesToStringBuffer(in).toString(); + } + + /** Retourne la string compressee */ + public static byte[] stringBufferToBytes(StringBuffer elem) { + return stringToBytes(elem.toString()); + } + + /** Retourne la string compressee */ + public static byte[] stringToBytes(String elem) { + try { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + GZIPOutputStream gz = new GZIPOutputStream(new BufferedOutputStream(baos)); + Reader sr = new BufferedReader(new StringReader(elem)); + int c; + while ((c = sr.read()) != -1) { + gz.write((char) c); + } + gz.close(); + + return baos.toByteArray(); + } + catch (IOException eee) { + throw new GZUtilException("Probleme dans la compression", eee); + } + } + +} // GZUtil + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtilException.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/GZUtilException.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtilException.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtilException.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,44 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * GZUtilException.java + * + * Created: 3 nov. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +public class GZUtilException extends RuntimeException { // GZUtilException + /** */ + private static final long serialVersionUID = -3342417793974741697L; + + public GZUtilException(String msg) { + super(msg); + } + + public GZUtilException(String msg, Throwable eee) { + super(msg, eee); + } +} // GZUtilException + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/GZUtilException.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/H2TypeEnum.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/H2TypeEnum.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/H2TypeEnum.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/H2TypeEnum.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,30 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +/** + * Une énumération pour représenter les différentes types d'implantation dans H2 + * + * @author chemit + */ +public enum H2TypeEnum { + derby, + h2, + hsql, + mckoi +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/H2TypeEnum.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/HashList.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/HashList.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/HashList.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/HashList.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,148 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * HashList.java + * + * Created: 2 nov. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; + +/** + * Cette objet permet de gerer l'unicité des objets ajouté. + * Lorsque l'on appelle la methode add sur cette objet, il verifie + * en premier que l'objet n'est pas deja dans la liste. S'il y est + * alors il n'est pas ajouter, sinon il est ajouter. + * L'utilisation de la methode set n'est pas permise + * <p/> + * FIXME: la serialisation n'est pas modifier, c-a-d que seul le tableau est + * conserve et pas la hashSet, donc apres recuperation, l'uticite n'est plus + * garantie. Il faut donc surcharger readObject et writeObject pour conserver + * le HashSet + */ +public class HashList<E> extends ArrayList<E> { // HashList + + /** */ + private static final long serialVersionUID = -334941610313293930L; + + protected HashSet<E> set = new HashSet<E>(); + + public HashList() { + super(); + } + + public HashList(Collection<? extends E> c) { + addAll(c); + } + + public HashList(int initialCapacity) { + super(initialCapacity); + } + + @Override + public E set(int index, E element) { + throw new UnsupportedOperationException("You can't use set method in HashList"); + } + + @Override + public boolean add(E o) { + boolean result = !contains(o); + add(size(), o); + return result; + } + + @Override + public void add(int index, E element) { + if (set.add(element)) { + super.add(index, element); + } + } + + /** + * supprime l'element demandé. Si l'elment n'existe pas alors, null + * est retrouné. + */ + @Override + public E remove(int index) { + if (set.remove(get(index))) { + return super.remove(index); + } + return null; + } + + @Override + public void clear() { + set.clear(); + super.clear(); + } + + @Override + public boolean addAll(Collection<? extends E> c) { + boolean modified = false; + Iterator<? extends E> e = c.iterator(); + while (e.hasNext()) { + if (add(e.next())) + modified = true; + } + return modified; + + } + + @Override + public boolean addAll(int index, Collection<? extends E> c) { + boolean modified = false; + Iterator<? extends E> e = c.iterator(); + while (e.hasNext()) { + add(index++, e.next()); + modified = true; + } + return modified; + + } + + @Override + protected void removeRange(int fromIndex, int toIndex) { + for (int i = toIndex - 1; i >= fromIndex; i--) { + remove(i); + } + } + + @Override + public boolean contains(Object elem) { + return set.contains(elem); + } + + @Override + public Object clone() { + HashList<E> result = new HashList<E>(this); + return result; + } + +} // HashList + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/HashList.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/IOUtils.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/IOUtils.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/IOUtils.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/IOUtils.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,86 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; + +import java.nio.channels.FileChannel; + +/** + * IOUtils. + * + * TODO ADD COMMENT HERE ! + * + * @deprecated use {FileUtil} instead + */ +public class IOUtils { + + /** + * Copy a file + */ + public static void copyFile(File in, File out) throws java.io.IOException { + + FileChannel sourceChannel = new FileInputStream(in).getChannel(); + FileChannel destinationChannel = new FileOutputStream(out).getChannel(); + + sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel); + + sourceChannel.close(); + destinationChannel.close(); + + return; + } + + /** + * Get a temporary file path + */ + public static String getTemporaryFilePath(String tempFilePrefix, + File tmpDirectory) throws java.io.IOException { + + // Get a File object with given prefix, default suffix is ".tmp" + File temporaryFile = File.createTempFile(tempFilePrefix, null, + tmpDirectory); + String temporaryFilePath = temporaryFile.getPath(); + + return temporaryFilePath; + } + + /** + * Get a ByteArrayOutputStream containing all data that could be read from the given InputStream + */ + public static ByteArrayOutputStream readBytesFrom(InputStream inputStream, + int defaultBufferSize) throws java.io.IOException { + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream( + defaultBufferSize); + byte[] buffer = new byte[defaultBufferSize]; + + int readBytes = inputStream.read(buffer); + while (readBytes > 0) { + outputStream.write(buffer, 0, readBytes); + readBytes = inputStream.read(buffer); + } + + return outputStream; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/IOUtils.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/LRUMapMultiKey.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/LRUMapMultiKey.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/LRUMapMultiKey.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/LRUMapMultiKey.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,230 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * LRUMapMultiKey.java + * + * Created: 23 mai 2006 04:08:03 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Set; + + +/** @author poussin */ + +public class LRUMapMultiKey extends LinkedHashMap<LRUMapMultiKey.Key, Object> { + + private static final long serialVersionUID = 1L; + + private static final Log log = LogFactory.getLog(LRUMapMultiKey.class); + + /** @author poussin */ + static public class Key extends ArrayList<Object> { + + private static final long serialVersionUID = 1L; + + // protected LRUMapMultiKey map = null; + // protected Reference ref = null; + protected int hash = 0; + + public Key(Object... k) { + Collections.addAll(this, k); + } + + @Override + public int hashCode() { + if (hash == 0) { + hash = super.hashCode(); + } + return hash; + } + +// /* (non-Javadoc) +// * @see java.util.AbstractList#equals(java.lang.Object) +// */ +// @Override +// public boolean equals(Object o) { +// if (o != null && o instanceof Reference) { +// Object ref = ((Reference)o).get(); +// if (ref == null) { +// boolean result = o.hashCode() == hashCode(); +// return result; +// } +// } +// return super.equals(o); +// } + +// /* (non-Javadoc) +// * @see java.lang.Object#finalize() +// */ +// @Override +// protected void finalize() throws Throwable { +// if (map != null) { +// for (Iterator i=iterator(); i.hasNext();) { +// Object k = i.next(); +// Set<Reference<Key>> list = map.keys.get(k); +// if (list != null) { +// Object o = ref; +// if (o == null) { +// o = this; +// } +// boolean ok = list.remove(o); +// if (list.size() == 0) { +// map.keys.remove(k); +// } +// } +// } +// } +// } + + } + + + protected Map<Object, Set<Key>> keys = new HashMap<Object, Set<Key>>(); + protected int maxSize; + + public LRUMapMultiKey(int maxSize) { + super(maxSize <= 0 ? 1000 : maxSize * 100 / 75, (float) 0.75, true); + this.maxSize = maxSize; + } + + public Key createKey(Object... k) { + return new Key(k); + } + + /* (non-Javadoc) + * @see java.util.WeakHashMap#clear() + */ + @Override + public void clear() { + keys.clear(); + super.clear(); + } + + /* (non-Javadoc) + * @see java.util.WeakHashMap#remove(java.lang.Object) + */ + @Override + public Object remove(Object k) { + if (k instanceof Key) { + return super.remove(k); + } else { + ArrayList<Key> result = new ArrayList<Key>(); + Set<Key> list = keys.remove(k); + if (list != null) { + for (Iterator<Key> i = list.iterator(); i.hasNext();) { + Key key = i.next(); + result.add(key); + super.remove(key); + } + list.clear(); // not necessary but perhaps help the garbage + } + return result; + } + } + + /* (non-Javadoc) + * @see java.util.WeakHashMap#put(java.lang.Object, java.lang.Object) + */ + @Override + public Object put(Key key, Object value) { +// if (!(akey instanceof Key)) { +// throw new IllegalArgumentException("key must be Key object"); +// } +// Key key = (Key)akey; + for (Iterator i = key.iterator(); i.hasNext();) { + Object k = i.next(); + Set<Key> list = keys.get(k); + if (list == null) { + list = new HashSet<Key>(); + keys.put(k, list); + } + list.add(key); +//System.out.println("+++++++++++++++++++ put key: " + key + " list("+k+") == " + list.size()); + } +//System.out.println("++++++++++++++++++++++++++++ LRU size = " + size() + " maxSize: " + maxSize); + Object result = super.put(key, value); +//System.out.println("+++++++++++++++++ LRU size = " + size()); + return result; + } + + /* (non-Javadoc) + * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry) + */ + @Override + protected boolean removeEldestEntry(Map.Entry<Key, Object> eldest) { + if (this.maxSize > 0 && size() > this.maxSize) { + Key key = (Key) eldest.getKey(); + for (Iterator i = key.iterator(); i.hasNext();) { + Object k = i.next(); + Set<Key> list = keys.get(k); + if (list != null) { + list.remove(key); + if (list.size() == 0) { + keys.remove(k); + } + } + } + + if (!containsKey(eldest.getKey())) { + log.warn("possible memory leak !!! removeEldestEntry (" + eldest.getKey().getClass() + ")" + eldest.getKey() + " size " + size() + " maxSize" + maxSize); + } + return true; + } + return false; + } + +// /* (non-Javadoc) +// * @see org.apache.commons.collections.map.LRUMap#removeLRU(org.apache.commons.collections.map.AbstractLinkedMap.LinkEntry) +// */ +// @Override +// protected boolean removeLRU(AbstractLinkedMap.LinkEntry entry) { +// Key key = (Key)entry.getKey(); +// for (Iterator i=key.iterator(); i.hasNext();) { +// Object k = i.next(); +// Set<Key> list = keys.get(k); +// if (list != null) { +// boolean ok = list.remove(key); +// if (list.size() == 0) { +// keys.remove(k); +// } +// } +// } +// return true; +// } + +} + + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/LRUMapMultiKey.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ListenerSet.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ListenerSet.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ListenerSet.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ListenerSet.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,249 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +/* * + * ListenerSet.java + * + * Created: 10 mai 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +package org.nuiton.util; + +import java.beans.Statement; +import java.lang.ref.Reference; +import java.util.HashSet; +import java.util.Iterator; + +/** + * <p>Cette classe permet de mettre en place facilement le support de listeners. + * Elle ne permet d'ajouter qu'une seul fois le meme listener. Si elle est + * la derniere à avoir une référence sur le listener, le listener est supprimé + * de la liste des listeners.</p> + * <p>Si on souhaite avoir une vérification sur le type de listener ajouté + * il faut utiliser le constructeur qui prend une classe en paramètre. Dans ce + * cas la méthode {@link #add(Object)} vérifie que l'object passé est bien + * du type ou un enfant du type donné en paramètre du constructeur + * <p>Il y a deux façon de prévenir les listeners d'un event soit par le + * mécanisme inclu dans cette classe en utilisant la méthode {@link #fire} soit + * en utilisant soit même l'Iterateur sur les listeners encore valide.</p> + * <pre> + * ListenerSet listeners = new ListenerSet(); + * ... + * listeners.fire("monEvent", MonObjetEvent); + * </pre> + * ou bien + * <pre> + * ListenerSet listeners = new ListenerSet(); + * ... + * for(Iterator i=listeners.iterator(); i.hasNext();){ + * MonListener l = (MonListener)i.next(); + * l.monEvent(MonObjetEvent); + * } + * </pre> + * Cette deuxième façon de faire est plus sûr car elle n'utilise pas + * l'introspection et donc une vérification est faite sur le nom de la méthode + * à appeler à la compilation, mais elle est plus verbeuse à écrire. + * + * @see org.codelutin.util.CategorisedListenerSet + */ +public class ListenerSet<Listener> implements Iterable<Listener> { // ListenerSet + + /** DOCUMENTME Description of the Field DOCUMENTME Description of the Field DOCUMENTME Description of the Field */ +// protected Class<T> listenerClass = null; + /** DOCUMENTME Description of the Field */ + protected HashSet<Reference<Listener>> listeners = new HashSet<Reference<Listener>>(); + + /** DOCUMENTME Constructor for the ListenerSet object */ + public ListenerSet() { + } + +// /** +// * Constructeur permettant de passer une classe que devra s'attisfaire les +// * listener que l'on souhaite ajouter +// * +// * @param listenerClass DOCUMENTME Description of the Parameter +// */ +// public ListenerSet(Class<T> listenerClass) { +// this.listenerClass = listenerClass; +// } + + public int size() { + return listeners.size(); + } + + /** + * Ajoute un listener dans la liste des listeners. + * + * @param l le listener à ajouter. Si l'objet passé est null, rien n'est fait + * si l'objet n'est pas du type passé en argument du constructeur + * une IllegalArgumentException est levée. + */ + public void add(Listener l) { + if (l == null) { + return; + } +// if (listenerClass == null || listenerClass.isInstance(l)) { + TransparenteWeakReference<Listener> ref = new TransparenteWeakReference<Listener>(l); + listeners.add(ref); +// } else { +// throw new IllegalArgumentException("Listener object (" +// + l.getClass().getName() + ") is not compatible with class: " +// + listenerClass.getName()); +// } + } + + /** + * ajoute tous les listeners d'un ListenerSet + * + * @param ls The feature to be added to the All attribute + */ + public void addAll(ListenerSet<Listener> ls) { +// if (listenerClass == null || (ls.listenerClass != null && +// listenerClass.isAssignableFrom(ls.listenDOCUMENTME Description of the ExceptionerClass))) { + listeners.addAll(ls.listeners); +// } else { +// throw new IllegalArgumentException("Listener object (" +// + ls.listenerClass + ") is not compatible with : " +// + listenerClass); +// } + } + + /** + * Appel la méthode du listener en passant l'objet event en paramètre + * Cette méthode echoue si la methode ou l'objet contenant la methode a + * appeler n'est pas public + * + * @param methodName le nom de la methode a appeler + * @param event l'event a passer en parametre de la methode a appeler + * @throws Exception si un des listeners leve une exception lors de l'appel + */ + public void fire(String methodName, Object event) throws Exception { + for (Iterator i = iterator(); i.hasNext();) { + Object o = i.next(); + Statement stm = new Statement(o, methodName, new Object[]{event}); + stm.execute(); + } + } + + /** + * Appel la méthode du listener sans argument + * Cette méthode echoue si la methode ou l'objet contenant la methode a + * appeler n'est pas public + * + * @param methodName le nom de la methode a appeler + * @throws Exception si un des listeners leve une exception lors de l'appel + */ + public void fire(String methodName) throws Exception { + for (Iterator i = iterator(); i.hasNext();) { + Object o = i.next(); + Statement stm = new Statement(o, methodName, null); + stm.execute(); + } + } + + /** + * DOCUMENTME Method + * + * @return DOCUMENTME Description of the Return Value + */ + public Iterator<Listener> iterator() { + return new ReferenceIterator<Listener>(listeners.iterator()); + } + + /** + * DOCUMENTME Method + * + * @param l DOCUMENTME Description of the Parameter + */ + public void remove(Listener l) { + TransparenteWeakReference<Listener> ref = new TransparenteWeakReference<Listener>(l); + listeners.remove(ref); + } + + /** + * DOCUMENTME Method + * + * @return DOCUMENTME Description of the Return Value + */ + public String toString() { + return "" + listeners; + } + + /** Iterator qui supprime les references vides lors du parcours */ + static class ReferenceIterator<T> implements Iterator<T> { + /** DOCUMENTME Description of the Field */ + protected Iterator<Reference<T>> iter = null; + /** DOCUMENTME Description of the Field */ + protected T nextObject = null; + + /** + * Un iterator contenant des References + * + * @param iter DOCUMENTME Description of the Parameter + */ + public ReferenceIterator(Iterator<Reference<T>> iter) { + this.iter = iter; + findNext(); + } + + /** DOCUMENTME Method */ + protected void findNext() { + while (iter.hasNext() && nextObject == null) { + Reference<T> ref = iter.next(); + T o = ref.get(); + if (o != null) { + nextObject = o; + } else { + iter.remove(); + } + } + } + + /** + * DOCUMENTME Method + * + * @return DOCUMENTME Description of the Return Value + */ + public boolean hasNext() { + return nextObject != null; + } + + /** + * DOCUMENTME Method + * + * @return DOCUMENTME Description of the Return Value + */ + public T next() { + T result = nextObject; + nextObject = null; + findNext(); + return result; + } + + /** DOCUMENTME Method */ + public void remove() { + iter.remove(); + } + } + +} // ListenerSet + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ListenerSet.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/Log.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/Log.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/Log.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/Log.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,284 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * Log.java + * + * Created: 12 août 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import java.util.EventListener; +import java.util.EventObject; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Cette classe permet de mettre en place un monitoring d'application simplement. + * Le développeur a chaque fois qu'il le souhaite ajoute dans son code un + * Log.logUserInfo("...", "....") qui indique un message que l'utilisateur est + * suceptible de vouloir, par exemple le résultat de la sauvegarde d'un fichier. + * Ou bien si l'application effectue un traitement, il peut utiliser + * Log.logTask("...", "...", max, value) pour indiquer qu'un traitement est + * en cours. + * <p/> + * Il suffit ensuite de creer un objet qui herite de {@link LogListener}, puis + * de l'enregistrer sur certaine category d'event il recevra alors les + * evenements de l'utilisateur. + * <p/> + * Une utilisation peut-être la bar de status qui afficherait le message. + * <p/> + * exemple de code + * <pre> + * LogListener l = new StatusBar(); + * Log.addLogListener(l); + * ... + * ... + * ... + * Log.logTask("SAVE", "Sauvegarde en cours", -1, 0); + * ... // sauvegarde + * Log.logUserInfo("SAVE", "Sauvegarde réussie"); + * Log.logTask("SAVE", "Sauvegarde terminée", 0, 0); + * </pre> + */ +public class Log { // Log + + static private Log LOG_INSTANCE = new Log(); + + /** L'interface que doivent respecter un listener */ + static public interface LogListener extends EventListener { + public void logMessage(LogEvent e); + + public void logTask(LogEvent e); + } + + /** Les events envoyes aux listeners */ + static public class LogEvent extends EventObject { + /** */ + private static final long serialVersionUID = 6597052732707368243L; + + protected String category; + protected Level level; + protected String message; + protected Throwable exception; + protected int taskMax = 0; + protected int taskValue = 0; + + public LogEvent(Object source, String category, Level level, String message, Throwable exception) { + super(source == null ? LOG_INSTANCE : source); + this.category = category; + this.level = level; + this.message = message; + this.exception = exception; + } + + public LogEvent(Object source, String category, String message, int taskMax, int taskValue) { + super(source == null ? LOG_INSTANCE : source); + this.category = category; + this.message = message; + this.taskMax = taskMax; + this.taskValue = taskValue; + } + + public String getCategory() { + return category; + } + + /** Retourne une valeur que si l'event est un sendMessage, sinon null; */ + public Level getLevel() { + return level; + } + + public String getMessage() { + return message; + } + + /** + * L'exception envoyé dans le log, si le log ne contient pas d'exception + * alors null est retourne. + */ + public Throwable getException() { + return exception; + } + + public int getTaskMax() { + return taskMax; + } + + public int getTaskValue() { + return taskValue; + } + + } + + /** Le Level pour les log utilisateur */ + static private class UserLevel extends Level { + /** */ + private static final long serialVersionUID = -9075227788352473733L; + + public UserLevel(String name, int value) { + super(name, value); + } + } + + /** Tous les listeners */ + static protected CategorisedListenerSet<LogListener> listeners = new CategorisedListenerSet<LogListener>(); + + /** Level.INFO = 700 Level.FINE=500 * */ + public static final Level USER_INFO = new UserLevel("USERINFO", 600); + + /** Ajoute un listener sur tous les logs envoye */ + static public void addLogListener(LogListener l) { + listeners.add(LOG_INSTANCE, l); + } + + /** enleve un listener sur tous les logs envoye */ + static public void removeLogListener(LogListener l) { + listeners.remove(LOG_INSTANCE, l); + } + + /** Ajoute un listener sur une certaine category de log */ + static public void addLogListener(LogListener l, String category) { + listeners.add(category, l); + } + + /** enleve un listener sur une certaine category de log */ + static public void removeLogListener(LogListener l, String category) { + listeners.remove(category, l); + } + + static protected void fire(String category, Level level, String message, Throwable exception) { + LogEvent e = new LogEvent(null, category, level, message, exception); + try { + logDevFinest("org.codelutin.util.Log.fire", "Category: " + category + " listeners enregistrés: " + listeners); + listeners.fire(category, "logMessage", e); + listeners.fire(LOG_INSTANCE, "logMessage", e); + } catch (Exception eee) { + Logger.getLogger(Log.class.getName() + ".fire").log(Level.WARNING, "Error during send log event", eee); + } + } + + static protected void fire(String category, String message, int max, int value) { + LogEvent e = new LogEvent(null, category, message, max, value); + try { + log("org.codelutin.util.Log.fire", Level.FINEST, "Category: " + category + " listeners enregistrés: " + listeners, null); + listeners.fire(category, "logTask", e); + listeners.fire(LOG_INSTANCE, "logTask", e); + } catch (Exception eee) { + Logger.getLogger(Log.class.getName() + ".fire").log(Level.WARNING, "Error during send log event", eee); + } + } + + /** + * Ajoute un message dans le USER_LEVEL. + * + * @param category la category du message, souvent un nom de module d'une + * application. + * @param message le message a envoyer + */ + static public void logUserInfo(String category, String message) { + logUserInfo(category, message, null); + } + + static public void logUserInfo(String category, String message, Throwable e) { + log(category, USER_INFO, message, e); + fire(category, USER_INFO, message, e); + } + + /** + * Permet d'indiquer l'avancement d'une tache. Si l'on ne connait pas la + * longueur de la tache il suffit d'indiquer -1 dans max, pour indiquer + * une tache en cours dont on ne connait pas la fin. + * lorsque la tache est termine, il suffit d'appeler cette methode avec max + * valant 0. + * + * @param category la category de la tache + * @param message le message a afficher, le message peut-etre null + * @param max l'entier qui indique la fin de la tache. La tache commence a + * 0 et fini lorsque l'on arrive a max. Si max vaut -1 cela veut dire + * que la tache debute mais qu'on ne connait pas sa longueur + * @param current la valeur courante de la tache. + */ + static public void logTask(String category, String message, int max, int current) { + log(category, USER_INFO, "task: " + message + "[" + current + "/" + max + "]", null); + fire(category, message, max, current); + } + + static public void log(String category, Level level, String message, Throwable e) { + if (e == null) { + Logger.getLogger(category).log(level, message); + } else { + Logger.getLogger(category).log(level, message, e); + } + } + + static public void logDevFinest(String category, String message) { + logDevFinest(category, message, null); + } + + static public void logDevFinest(String category, String message, Throwable e) { + log(category, Level.FINEST, message, e); + } + + static public void logDevFiner(String category, String message) { + logDevFiner(category, message, null); + } + + static public void logDevFiner(String category, String message, Throwable e) { + log(category, Level.FINER, message, e); + } + + static public void logDevFine(String category, String message) { + logDevFine(category, message, null); + } + + static public void logDevFine(String category, String message, Throwable e) { + log(category, Level.FINE, message, e); + } + + static public void logDevInfo(String category, String message) { + logDevInfo(category, message, null); + } + + static public void logDevInfo(String category, String message, Throwable e) { + log(category, Level.INFO, message, e); + } + + static public void logDevWarn(String category, String message) { + logDevInfo(category, message, null); + } + + static public void logDevWarn(String category, String message, Throwable e) { + log(category, Level.WARNING, message, e); + } + + static public void logDevSevere(String category, String message) { + logDevSevere(category, message, null); + } + + static public void logDevSevere(String category, String message, Throwable e) { + log(category, Level.SEVERE, message, e); + } + +} // Log Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/Log.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingException.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/LoggingException.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingException.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingException.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,46 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/** + * LogException.java + * + * Created: Sat Apr 20 2002 + * + * @author POUSSIN Benjamin <bpoussin@free.fr> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +public class LoggingException extends RuntimeException { // LogException + + /** */ + private static final long serialVersionUID = 3495450140612716283L; + + public LoggingException(String msg) { + super(msg); + } + + public LoggingException(String msg, Throwable e) { + super(msg, e); + } + +} // LogException Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingException.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingPatternFormatter.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/LoggingPatternFormatter.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingPatternFormatter.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingPatternFormatter.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,486 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/** +* PatternFormatter.java +* +* Created: Sat Apr 20 2002 +* +* @author POUSSIN Benjamin <bpoussin@free.fr> +* Copyright Code Lutin +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.nuiton.util; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.logging.Formatter; +import java.util.logging.LogRecord; +import java.util.logging.LogManager; +import java.util.Date; +import java.text.SimpleDateFormat; +import java.util.HashMap; +import java.util.Iterator; +import java.util.ArrayList; + +/** +* Classe org.codelutin.logging.PatternFormatter. +* +* <ul> +* <li>n: new line</li> +* <li>%: %</li> +* <li>{: {</li> +* </ul> +* +* <ul> +* <li>d: date</li> +* </ul> +* +* Date follow the same pattern as DateFormat. +* +* <ul> Sized +* <li>o: free memory</li> +* <li>O: total memory</li> +* <li>t: thread id</li> +* <li>p: priority level</li> +* <li>c: class name</li> +* <li>m: message</li> +* <li>a: argument</li> +* <li>e: exception</li> +* </ul> +* +* Sized element support justify pattern. +* {[+|-]<size>[:<maxPos>]}. +* '+' is +* left justify, '-' rigth justify, size the prefered size for the element if it is not bigger. +* If maxPos option is present blanc is not add if it go up to maxPos. +* +* <ul> SubString +* <li>M: method name</li> +* </ul> +* +* L'element SubString a les memes possibilites que le pattern justify, +* et permet en plus de suprimer une sous chaine, +* cela permet de supprimer le debut du nom d'une classe. +* Syntaxe : +* {*<substring>|[+|-]<size>[:<maxPos>]} +* {<substring>*|[+|-]<size>[:<maxPos>]} +* L'etoile represente le texte qui restera. +*/ +public class LoggingPatternFormatter extends Formatter { // PatternFormatter + + private static final String DEFAULT_PATTERN = "%d{yyyy-MM-dd HH:mm:ss} [free:%o{-7}|total:%O{-7}][%t][%p{7}] %c{org.codelutin.*|25} %M{15:105}: %m%n%e"; + + protected HashMap<String, Class<?>> arguments = null; + protected ArrayList<Argument> compile = null; + protected String pattern = null; + + public LoggingPatternFormatter() { + try { + arguments = new HashMap<String, Class<?>>(); + initArguments(); + LogManager manager = LogManager.getLogManager(); + String cname = this.getClass().getName(); + pattern = manager.getProperty(cname + ".pattern"); + if (pattern == null) + pattern = DEFAULT_PATTERN; + compilePattern(pattern); + } catch (Exception eee) { + System.err.println("Impossible d'utiliser le PatternFormatter"); + eee.printStackTrace(); + throw new LoggingException( + "Exception durant l'initialisation du PatternFormatter", + eee); + } + } + + /** + * Methode qui formate le record + */ + public String format(LogRecord record) { + StringBuffer result = new StringBuffer(); + for (Iterator i = compile.iterator(); i.hasNext();) { + ((Argument) i.next()).toString(record, result); + } + return result.toString(); + } + + /** + * Si vous souhaitez ajouter des type d'argument + * Surcharger cette methode et a la fin fait un super.initArguments() + */ + protected void initArguments() { + arguments.put("d", DateArgument.class); + arguments.put("o", FreeMemoryArgument.class); + arguments.put("O", TotalMemoryArgument.class); + arguments.put("t", ThreadArgument.class); + arguments.put("p", PriorityLevelArgument.class); + arguments.put("c", ClassNameArgument.class); + arguments.put("M", MethodNameArgument.class); + arguments.put("m", MessageArgument.class); + arguments.put("e", ExceptionArgument.class); + } + + /** + * Genere a partir de la chaine la liste des objet Argument. + */ + protected void compilePattern(String pattern) { + compile = new ArrayList<Argument>(); + String[] match = findNextPattern(pattern); + while (!match[1].equals("")) { + compile.add(new StringArgument(match[0])); + compile.add(patternToArgument(match[1])); + match = findNextPattern(match[2]); + } + compile.add(new StringArgument(match[0])); + } + + /** + * Recherche dans la chaine le prochaine pattern. + * @return un tableau de 3 chaines, [0] ce qu'il y a avant le + * parttern, [1] le parttern, [2] ce qu'il y a apres le pattern. + */ + protected String[] findNextPattern(String s) { + String[] result = new String[] { "", "", "" }; + if (s == null) { + return result; + } + + int d = s.indexOf("%"); + + if (d != -1) { // il y a un % + if (d + 2 < s.length() && s.charAt(d + 2) == '{') { + int f = s.indexOf("}", d); + if (f != -1) { // il y a une pattern %c{pattern} + result[0] = s.substring(0, d); + result[1] = s.substring(d + 1, f); + result[2] = s.substring(f + 1); + } else { + throw new LoggingException("Error, { at position " + + (d + 2) + " not terminated in :" + s); + } + } else { //pas de pattern + result[0] = s.substring(0, d); + result[1] = s.substring(d + 1, d + 2); + result[2] = s.substring(d + 2); + } + } else { + result[0] = s; + } + + return result; + } + + /** + * Converti un pattern en un objet Argument + */ + protected Argument patternToArgument(String s) { + if (s.charAt(0) == 'n') { // new ligne + return new StringArgument("\n"); + + } else if (s.charAt(0) == '%') { // le caractere % + return new StringArgument("%"); + + } else if (s.charAt(0) == '{') { // le caractere { + return new StringArgument("{"); + + } else { + String code = s.substring(0, 1); + Class argumentClass = (Class) arguments.get(code); + if (argumentClass == null) + throw new LoggingException("Erreur dans le pattern '" + code + + "' inconnu"); + Argument argument = null; + try { + argument = (Argument) argumentClass.newInstance(); + } catch (InstantiationException eee) { + throw new LoggingException( + "Erreur lors de l'instanciation de l'objet Argument: " + + argumentClass.getName(), eee); + } catch (IllegalAccessException eee) { + throw new LoggingException( + "Erreur lors de l'instanciation de l'objet Argument: " + + argumentClass.getName(), eee); + } + if (s.length() > 1) { // on a un pattern + argument.setPattern(s.substring(2)); + } + + return argument; + } + } + + /////////////////////////////////////////////////////////////////////////////// + //////////////////////////// Les Classes Argument ///////////////////////////// + /////////////////////////////////////////////////////////////////////////////// + + static protected abstract class Argument { + protected String pattern; + + public Argument() { + } + + public void setPattern(String pattern) { + this.pattern = pattern; + } + + abstract public StringBuffer toString(LogRecord record, + StringBuffer toAppendTo); + } + + static protected class StringArgument extends Argument { + protected String s = null; + + public StringArgument(String s) { + super(); + this.s = s; + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + toAppendTo.append(s); + return toAppendTo; + } + } + + static protected class DateArgument extends Argument { + protected SimpleDateFormat dateFormat = null; + + public DateArgument() { + super(); + } + + public void setPattern(String pattern) { + super.setPattern(pattern); + dateFormat = new SimpleDateFormat(pattern); + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + toAppendTo.append(dateFormat.format(new Date(record.getMillis()))); + return toAppendTo; + } + } + + static abstract protected class SizedArgument extends Argument { + protected boolean left = true; + protected int width = 0; + protected int maxPos = -1; + + public SizedArgument() { + super(); + } + + public void setPattern(String pattern) { + super.setPattern(pattern); + if (pattern.length() > 0) { + String[] subpattern = pattern.split(":"); + pattern = subpattern[0]; + char op = pattern.charAt(0); + if (pattern.charAt(0) == '+' || pattern.charAt(0) == '-') { + pattern = pattern.substring(1); + } + width = Integer.parseInt(pattern); + left = op != '-'; + if (subpattern.length > 1) { + maxPos = Integer.parseInt(subpattern[1]); + } + } + } + + protected StringBuffer justify(String s, StringBuffer toAppendTo) { + int blanc = width - s.length(); + if (left) { + toAppendTo.append(s); + while (0 < blanc-- + && (maxPos == -1 || toAppendTo.length() < maxPos)) { + toAppendTo.append(" "); + } + } else { + while (0 < blanc-- + && (maxPos == -1 || toAppendTo.length() < maxPos)) { + toAppendTo.append(" "); + } + toAppendTo.append(s); + } + return toAppendTo; + } + } + + static abstract protected class SubStringArgument extends SizedArgument { + /** la chaine qui doit etre supprimee */ + protected String removeString = null; + /** vrai si la chaine doit etre retiree du debut, faux pour la fin */ + protected boolean atBeginning = true; + + public SubStringArgument() { + super(); + } + + public void setPattern(String pattern) { + String[] subpattern = pattern.split("\\|"); + for (int i = 0; i < subpattern.length; i++) { + try { //on essai de voir si le pattern convient au SizedArgument + super.setPattern(subpattern[i]); + } catch (NumberFormatException eee) { + // il ne convient pas au SizedArgument + // c pour le substring + atBeginning = subpattern[i].charAt(0) != '*'; + if (subpattern[i].charAt(0) == '*') { + removeString = subpattern[i].substring(1); + } else if (subpattern[i].endsWith("*")) { + removeString = subpattern[i].substring(0, subpattern[i] + .length() - 1); + } + } + } + } + + protected String substring(String s) { + if (atBeginning) { + if (s.startsWith(removeString)) + return s.substring(removeString.length()); + } else { + if (s.endsWith(removeString)) + return s.substring(0, s.length() - removeString.length()); + } + return s; + } + } + + static abstract protected class OctetArgument extends SizedArgument { + protected static final String[] UNITE = { "o", "Ko", "Mo", "Go", "To", + "Po" }; + protected int diviseur = 1024; + + public OctetArgument() { + super(); + } + + /** + * Methode permettant l'affichage d'un taille avec une representation + * humainement lisible. + * @param size la taille rendre lisible + * @param unit les unites a utiliser (les petits en premier) + * @param diviseur le diviseur entre unite (ex: 1000 ou 1024) + * @return la representation + */ + protected String toReadableSize(long size, String[] unit, int diviseur) { + int unitIndex = 0; + while (size > 99999 && unitIndex < unit.length) { + size /= diviseur; + unitIndex++; + } + String result = size + unit[unitIndex]; + return result; + } + } + + static protected class FreeMemoryArgument extends OctetArgument { + public FreeMemoryArgument() { + super(); + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + return justify(toReadableSize(Runtime.getRuntime().freeMemory(), + UNITE, diviseur), toAppendTo); + } + } + + static protected class TotalMemoryArgument extends OctetArgument { + public TotalMemoryArgument() { + super(); + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + return justify(toReadableSize(Runtime.getRuntime().totalMemory(), + UNITE, diviseur), toAppendTo); + } + } + + static protected class ThreadArgument extends SizedArgument { + public ThreadArgument() { + super(); + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + return justify(Thread.currentThread().getName(), toAppendTo); + } + } + + static protected class PriorityLevelArgument extends SizedArgument { + public PriorityLevelArgument() { + super(); + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + return justify(record.getLevel().toString(), toAppendTo); + } + } + + static protected class ClassNameArgument extends SubStringArgument { + public ClassNameArgument() { + super(); + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + return justify(substring(record.getSourceClassName()), toAppendTo); + } + } + + static protected class MethodNameArgument extends SizedArgument { + public MethodNameArgument() { + super(); + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + return justify(record.getSourceMethodName(), toAppendTo); + } + } + + static protected class MessageArgument extends SizedArgument { + public MessageArgument() { + super(); + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + return justify(record.getMessage(), toAppendTo); + } + } + + static protected class ExceptionArgument extends Argument { + public ExceptionArgument() { + super(); + } + + public StringBuffer toString(LogRecord record, StringBuffer toAppendTo) { + Throwable e = record.getThrown(); + if (e != null) { + toAppendTo.append(e.getMessage()); + toAppendTo.append("\n"); + StringWriter st = new StringWriter(); + e.printStackTrace(new PrintWriter(st)); + toAppendTo.append(st.toString()); + toAppendTo.append("\n"); + } + return toAppendTo; + } + } + +} // PatternFormatter Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/LoggingPatternFormatter.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/MD5.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/MD5.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/MD5.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/MD5.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,826 @@ +package org.nuiton.util; + +import java.io.*; + +/** + * Fast implementation of RSA's MD5 hash generator in Java JDK Beta-2 or higher. + * <p> + * Originally written by Santeri Paavolainen, Helsinki Finland 1996.<br> + * (c) Santeri Paavolainen, Helsinki Finland 1996<br> + * Many changes Copyright (c) 2002 - 2008 Timothy W Macinta<br> + * <p> + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * <p> + * This library 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 + * Library General Public License for more details. + * <p> + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * <p> + * See http://www.twmacinta.com/myjava/fast_md5.php for more information + * on this file and the related files. + * <p> + * This was originally a rather straight re-implementation of the + * reference implementation given in RFC1321 by RSA. It passes the MD5 + * test suite as defined in RFC1321. + * <p> + * Many optimizations made by Timothy W Macinta. Reduced time to checksum a + * test file in Java alone to roughly half the time taken compared with + * java.security.MessageDigest (within an intepretter). Also added an + * optional native method to reduce the time even further. + * See http://www.twmacinta.com/myjava/fast_md5.php for further information + * on the time improvements achieved. + * <p> + * Some bug fixes also made by Timothy W Macinta. + * <p> + * Please note: I (Timothy Macinta) have put this code in the + * com.twmacinta.util package only because it came without a package. I + * was not the the original author of the code, although I did + * optimize it (substantially) and fix some bugs. + * <p> + * This Java class has been derived from the RSA Data Security, Inc. MD5 + * Message-Digest Algorithm and its reference implementation. + * <p> + * This class will attempt to use a native method to quickly compute + * checksums when the appropriate native library is available. On Linux, + * this library should be named "MD5.so" and on Windows it should be + * named "MD5.dll". The code will attempt to locate the library in the + * following locations in the order given: + * + * <ol> + * <li>The path specified by the system property + * "com.twmacinta.util.MD5.NATIVE_LIB_FILE" + * (be sure to include "MD5.so" or "MD5.dll" + * as appropriate at the end of the path). + * <li>A platform specific directory beneath the "lib/arch/" directory. + * On Linux for x86, this is "lib/arch/linux_x86/". On Windows for + * x86, this is "lib/arch/win32_x86/". + * <li>Within the "lib/" directory. + * <li>Within the current directory. + * </ol> + * + * <p> + * If the library is not found, the code will fall back to the default + * (slower) Java code. + * <p> + * As a side effect of having the code search for the native library, + * SecurityExceptions might be thrown on JVMs that have a restrictive + * SecurityManager. The initialization code attempts to silently discard + * these exceptions and continue, but many SecurityManagers will + * attempt to notify the user directly of all SecurityExceptions thrown. + * Consequently, the code has provisions for skipping the search for + * the native library. Any of these provisions may be used to skip the + * search as long as they are performed <i>before</i> the first + * instance of a com.twmacinta.util.MD5 object is constructed (note that + * the convenience stream objects will implicitly create an MD5 object). + * <p> + * The first option is to set the system property + * "com.twmacinta.util.MD5.NO_NATIVE_LIB" to "true" or "1". + * Unfortunately, SecurityManagers may also choose to disallow system + * property setting, so this won't be of use in all cases. + * <p> + * The second option is to call + * com.twmacinta.util.MD5.initNativeLibrary(true) before any MD5 objects + * are constructed. + * + * @author Santeri Paavolainen <sjpaavol@cc.helsinki.fi> + * @author Timothy W Macinta (twm@alum.mit.edu) (optimizations and bug fixes) + */ + +public class MD5 { + + /** + * MD5 state + **/ + MD5State state; + + /** + * If Final() has been called, finals is set to the current finals + * state. Any Update() causes this to be set to null. + **/ + MD5State finals; + + /** + * Padding for Final() + **/ + static byte padding[] = { + (byte) 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + }; + + private static boolean native_lib_loaded = false; + private static boolean native_lib_init_pending = true; + + /** + * Initialize MD5 internal state (object can be reused just by + * calling Init() after every Final() + **/ + public synchronized void Init () { + state = new MD5State(); + finals = null; + } + + /** + * Class constructor + **/ + public MD5 () { + if (native_lib_init_pending) _initNativeLibrary(); + this.Init(); + } + + /** + * Initialize class, and update hash with ob.toString() + * + * @param ob Object, ob.toString() is used to update hash + * after initialization + **/ + public MD5 (Object ob) { + this(); + Update(ob.toString()); + } + + private void Decode (byte buffer[], int shift, int[] out) { + /*len += shift; + for (int i = 0; shift < len; i++, shift += 4) { + out[i] = ((int) (buffer[shift] & 0xff)) | + (((int) (buffer[shift + 1] & 0xff)) << 8) | + (((int) (buffer[shift + 2] & 0xff)) << 16) | + (((int) buffer[shift + 3]) << 24); + }*/ + + // unrolled loop (original loop shown above) + + out[0] = ((int) (buffer[shift] & 0xff)) | + (((int) (buffer[shift + 1] & 0xff)) << 8) | + (((int) (buffer[shift + 2] & 0xff)) << 16) | + (((int) buffer[shift + 3]) << 24); + out[1] = ((int) (buffer[shift + 4] & 0xff)) | + (((int) (buffer[shift + 5] & 0xff)) << 8) | + (((int) (buffer[shift + 6] & 0xff)) << 16) | + (((int) buffer[shift + 7]) << 24); + out[2] = ((int) (buffer[shift + 8] & 0xff)) | + (((int) (buffer[shift + 9] & 0xff)) << 8) | + (((int) (buffer[shift + 10] & 0xff)) << 16) | + (((int) buffer[shift + 11]) << 24); + out[3] = ((int) (buffer[shift + 12] & 0xff)) | + (((int) (buffer[shift + 13] & 0xff)) << 8) | + (((int) (buffer[shift + 14] & 0xff)) << 16) | + (((int) buffer[shift + 15]) << 24); + out[4] = ((int) (buffer[shift + 16] & 0xff)) | + (((int) (buffer[shift + 17] & 0xff)) << 8) | + (((int) (buffer[shift + 18] & 0xff)) << 16) | + (((int) buffer[shift + 19]) << 24); + out[5] = ((int) (buffer[shift + 20] & 0xff)) | + (((int) (buffer[shift + 21] & 0xff)) << 8) | + (((int) (buffer[shift + 22] & 0xff)) << 16) | + (((int) buffer[shift + 23]) << 24); + out[6] = ((int) (buffer[shift + 24] & 0xff)) | + (((int) (buffer[shift + 25] & 0xff)) << 8) | + (((int) (buffer[shift + 26] & 0xff)) << 16) | + (((int) buffer[shift + 27]) << 24); + out[7] = ((int) (buffer[shift + 28] & 0xff)) | + (((int) (buffer[shift + 29] & 0xff)) << 8) | + (((int) (buffer[shift + 30] & 0xff)) << 16) | + (((int) buffer[shift + 31]) << 24); + out[8] = ((int) (buffer[shift + 32] & 0xff)) | + (((int) (buffer[shift + 33] & 0xff)) << 8) | + (((int) (buffer[shift + 34] & 0xff)) << 16) | + (((int) buffer[shift + 35]) << 24); + out[9] = ((int) (buffer[shift + 36] & 0xff)) | + (((int) (buffer[shift + 37] & 0xff)) << 8) | + (((int) (buffer[shift + 38] & 0xff)) << 16) | + (((int) buffer[shift + 39]) << 24); + out[10] = ((int) (buffer[shift + 40] & 0xff)) | + (((int) (buffer[shift + 41] & 0xff)) << 8) | + (((int) (buffer[shift + 42] & 0xff)) << 16) | + (((int) buffer[shift + 43]) << 24); + out[11] = ((int) (buffer[shift + 44] & 0xff)) | + (((int) (buffer[shift + 45] & 0xff)) << 8) | + (((int) (buffer[shift + 46] & 0xff)) << 16) | + (((int) buffer[shift + 47]) << 24); + out[12] = ((int) (buffer[shift + 48] & 0xff)) | + (((int) (buffer[shift + 49] & 0xff)) << 8) | + (((int) (buffer[shift + 50] & 0xff)) << 16) | + (((int) buffer[shift + 51]) << 24); + out[13] = ((int) (buffer[shift + 52] & 0xff)) | + (((int) (buffer[shift + 53] & 0xff)) << 8) | + (((int) (buffer[shift + 54] & 0xff)) << 16) | + (((int) buffer[shift + 55]) << 24); + out[14] = ((int) (buffer[shift + 56] & 0xff)) | + (((int) (buffer[shift + 57] & 0xff)) << 8) | + (((int) (buffer[shift + 58] & 0xff)) << 16) | + (((int) buffer[shift + 59]) << 24); + out[15] = ((int) (buffer[shift + 60] & 0xff)) | + (((int) (buffer[shift + 61] & 0xff)) << 8) | + (((int) (buffer[shift + 62] & 0xff)) << 16) | + (((int) buffer[shift + 63]) << 24); + } + + private native void Transform_native (int[] state, byte buffer[], int shift, int length); + + private void Transform (MD5State state, byte buffer[], int shift, int[] decode_buf) { + int + a = state.state[0], + b = state.state[1], + c = state.state[2], + d = state.state[3], + x[] = decode_buf; + + Decode(buffer, shift, decode_buf); + + /* Round 1 */ + a += ((b & c) | (~b & d)) + x[ 0] + 0xd76aa478; /* 1 */ + a = ((a << 7) | (a >>> 25)) + b; + d += ((a & b) | (~a & c)) + x[ 1] + 0xe8c7b756; /* 2 */ + d = ((d << 12) | (d >>> 20)) + a; + c += ((d & a) | (~d & b)) + x[ 2] + 0x242070db; /* 3 */ + c = ((c << 17) | (c >>> 15)) + d; + b += ((c & d) | (~c & a)) + x[ 3] + 0xc1bdceee; /* 4 */ + b = ((b << 22) | (b >>> 10)) + c; + + a += ((b & c) | (~b & d)) + x[ 4] + 0xf57c0faf; /* 5 */ + a = ((a << 7) | (a >>> 25)) + b; + d += ((a & b) | (~a & c)) + x[ 5] + 0x4787c62a; /* 6 */ + d = ((d << 12) | (d >>> 20)) + a; + c += ((d & a) | (~d & b)) + x[ 6] + 0xa8304613; /* 7 */ + c = ((c << 17) | (c >>> 15)) + d; + b += ((c & d) | (~c & a)) + x[ 7] + 0xfd469501; /* 8 */ + b = ((b << 22) | (b >>> 10)) + c; + + a += ((b & c) | (~b & d)) + x[ 8] + 0x698098d8; /* 9 */ + a = ((a << 7) | (a >>> 25)) + b; + d += ((a & b) | (~a & c)) + x[ 9] + 0x8b44f7af; /* 10 */ + d = ((d << 12) | (d >>> 20)) + a; + c += ((d & a) | (~d & b)) + x[10] + 0xffff5bb1; /* 11 */ + c = ((c << 17) | (c >>> 15)) + d; + b += ((c & d) | (~c & a)) + x[11] + 0x895cd7be; /* 12 */ + b = ((b << 22) | (b >>> 10)) + c; + + a += ((b & c) | (~b & d)) + x[12] + 0x6b901122; /* 13 */ + a = ((a << 7) | (a >>> 25)) + b; + d += ((a & b) | (~a & c)) + x[13] + 0xfd987193; /* 14 */ + d = ((d << 12) | (d >>> 20)) + a; + c += ((d & a) | (~d & b)) + x[14] + 0xa679438e; /* 15 */ + c = ((c << 17) | (c >>> 15)) + d; + b += ((c & d) | (~c & a)) + x[15] + 0x49b40821; /* 16 */ + b = ((b << 22) | (b >>> 10)) + c; + + + /* Round 2 */ + a += ((b & d) | (c & ~d)) + x[ 1] + 0xf61e2562; /* 17 */ + a = ((a << 5) | (a >>> 27)) + b; + d += ((a & c) | (b & ~c)) + x[ 6] + 0xc040b340; /* 18 */ + d = ((d << 9) | (d >>> 23)) + a; + c += ((d & b) | (a & ~b)) + x[11] + 0x265e5a51; /* 19 */ + c = ((c << 14) | (c >>> 18)) + d; + b += ((c & a) | (d & ~a)) + x[ 0] + 0xe9b6c7aa; /* 20 */ + b = ((b << 20) | (b >>> 12)) + c; + + a += ((b & d) | (c & ~d)) + x[ 5] + 0xd62f105d; /* 21 */ + a = ((a << 5) | (a >>> 27)) + b; + d += ((a & c) | (b & ~c)) + x[10] + 0x02441453; /* 22 */ + d = ((d << 9) | (d >>> 23)) + a; + c += ((d & b) | (a & ~b)) + x[15] + 0xd8a1e681; /* 23 */ + c = ((c << 14) | (c >>> 18)) + d; + b += ((c & a) | (d & ~a)) + x[ 4] + 0xe7d3fbc8; /* 24 */ + b = ((b << 20) | (b >>> 12)) + c; + + a += ((b & d) | (c & ~d)) + x[ 9] + 0x21e1cde6; /* 25 */ + a = ((a << 5) | (a >>> 27)) + b; + d += ((a & c) | (b & ~c)) + x[14] + 0xc33707d6; /* 26 */ + d = ((d << 9) | (d >>> 23)) + a; + c += ((d & b) | (a & ~b)) + x[ 3] + 0xf4d50d87; /* 27 */ + c = ((c << 14) | (c >>> 18)) + d; + b += ((c & a) | (d & ~a)) + x[ 8] + 0x455a14ed; /* 28 */ + b = ((b << 20) | (b >>> 12)) + c; + + a += ((b & d) | (c & ~d)) + x[13] + 0xa9e3e905; /* 29 */ + a = ((a << 5) | (a >>> 27)) + b; + d += ((a & c) | (b & ~c)) + x[ 2] + 0xfcefa3f8; /* 30 */ + d = ((d << 9) | (d >>> 23)) + a; + c += ((d & b) | (a & ~b)) + x[ 7] + 0x676f02d9; /* 31 */ + c = ((c << 14) | (c >>> 18)) + d; + b += ((c & a) | (d & ~a)) + x[12] + 0x8d2a4c8a; /* 32 */ + b = ((b << 20) | (b >>> 12)) + c; + + + /* Round 3 */ + a += (b ^ c ^ d) + x[ 5] + 0xfffa3942; /* 33 */ + a = ((a << 4) | (a >>> 28)) + b; + d += (a ^ b ^ c) + x[ 8] + 0x8771f681; /* 34 */ + d = ((d << 11) | (d >>> 21)) + a; + c += (d ^ a ^ b) + x[11] + 0x6d9d6122; /* 35 */ + c = ((c << 16) | (c >>> 16)) + d; + b += (c ^ d ^ a) + x[14] + 0xfde5380c; /* 36 */ + b = ((b << 23) | (b >>> 9)) + c; + + a += (b ^ c ^ d) + x[ 1] + 0xa4beea44; /* 37 */ + a = ((a << 4) | (a >>> 28)) + b; + d += (a ^ b ^ c) + x[ 4] + 0x4bdecfa9; /* 38 */ + d = ((d << 11) | (d >>> 21)) + a; + c += (d ^ a ^ b) + x[ 7] + 0xf6bb4b60; /* 39 */ + c = ((c << 16) | (c >>> 16)) + d; + b += (c ^ d ^ a) + x[10] + 0xbebfbc70; /* 40 */ + b = ((b << 23) | (b >>> 9)) + c; + + a += (b ^ c ^ d) + x[13] + 0x289b7ec6; /* 41 */ + a = ((a << 4) | (a >>> 28)) + b; + d += (a ^ b ^ c) + x[ 0] + 0xeaa127fa; /* 42 */ + d = ((d << 11) | (d >>> 21)) + a; + c += (d ^ a ^ b) + x[ 3] + 0xd4ef3085; /* 43 */ + c = ((c << 16) | (c >>> 16)) + d; + b += (c ^ d ^ a) + x[ 6] + 0x04881d05; /* 44 */ + b = ((b << 23) | (b >>> 9)) + c; + + a += (b ^ c ^ d) + x[ 9] + 0xd9d4d039; /* 33 */ + a = ((a << 4) | (a >>> 28)) + b; + d += (a ^ b ^ c) + x[12] + 0xe6db99e5; /* 34 */ + d = ((d << 11) | (d >>> 21)) + a; + c += (d ^ a ^ b) + x[15] + 0x1fa27cf8; /* 35 */ + c = ((c << 16) | (c >>> 16)) + d; + b += (c ^ d ^ a) + x[ 2] + 0xc4ac5665; /* 36 */ + b = ((b << 23) | (b >>> 9)) + c; + + + /* Round 4 */ + a += (c ^ (b | ~d)) + x[ 0] + 0xf4292244; /* 49 */ + a = ((a << 6) | (a >>> 26)) + b; + d += (b ^ (a | ~c)) + x[ 7] + 0x432aff97; /* 50 */ + d = ((d << 10) | (d >>> 22)) + a; + c += (a ^ (d | ~b)) + x[14] + 0xab9423a7; /* 51 */ + c = ((c << 15) | (c >>> 17)) + d; + b += (d ^ (c | ~a)) + x[ 5] + 0xfc93a039; /* 52 */ + b = ((b << 21) | (b >>> 11)) + c; + + a += (c ^ (b | ~d)) + x[12] + 0x655b59c3; /* 53 */ + a = ((a << 6) | (a >>> 26)) + b; + d += (b ^ (a | ~c)) + x[ 3] + 0x8f0ccc92; /* 54 */ + d = ((d << 10) | (d >>> 22)) + a; + c += (a ^ (d | ~b)) + x[10] + 0xffeff47d; /* 55 */ + c = ((c << 15) | (c >>> 17)) + d; + b += (d ^ (c | ~a)) + x[ 1] + 0x85845dd1; /* 56 */ + b = ((b << 21) | (b >>> 11)) + c; + + a += (c ^ (b | ~d)) + x[ 8] + 0x6fa87e4f; /* 57 */ + a = ((a << 6) | (a >>> 26)) + b; + d += (b ^ (a | ~c)) + x[15] + 0xfe2ce6e0; /* 58 */ + d = ((d << 10) | (d >>> 22)) + a; + c += (a ^ (d | ~b)) + x[ 6] + 0xa3014314; /* 59 */ + c = ((c << 15) | (c >>> 17)) + d; + b += (d ^ (c | ~a)) + x[13] + 0x4e0811a1; /* 60 */ + b = ((b << 21) | (b >>> 11)) + c; + + a += (c ^ (b | ~d)) + x[ 4] + 0xf7537e82; /* 61 */ + a = ((a << 6) | (a >>> 26)) + b; + d += (b ^ (a | ~c)) + x[11] + 0xbd3af235; /* 62 */ + d = ((d << 10) | (d >>> 22)) + a; + c += (a ^ (d | ~b)) + x[ 2] + 0x2ad7d2bb; /* 63 */ + c = ((c << 15) | (c >>> 17)) + d; + b += (d ^ (c | ~a)) + x[ 9] + 0xeb86d391; /* 64 */ + b = ((b << 21) | (b >>> 11)) + c; + + state.state[0] += a; + state.state[1] += b; + state.state[2] += c; + state.state[3] += d; + } + + /** + * Updates hash with the bytebuffer given (using at maximum length bytes from + * that buffer) + * + * @param stat Which state is updated + * @param buffer Array of bytes to be hashed + * @param offset Offset to buffer array + * @param length Use at maximum `length' bytes (absolute + * maximum is buffer.length) + */ + public void Update (MD5State stat, byte buffer[], int offset, int length) { + int index, partlen, i, start; + finals = null; + + /* Length can be told to be shorter, but not inter */ + if ((length - offset)> buffer.length) + length = buffer.length - offset; + + /* compute number of bytes mod 64 */ + + index = (int) (stat.count & 0x3f); + stat.count += length; + + partlen = 64 - index; + + if (length >= partlen) { + + // update state (using native method) to reflect input + + if (native_lib_loaded) { + if (partlen == 64) { + partlen = 0; + } else { + for (i = 0; i < partlen; i++) + stat.buffer[i + index] = buffer[i + offset]; + Transform_native(stat.state, stat.buffer, 0, 64); + } + i = partlen + ((length - partlen) / 64) * 64; + + // break into chunks to guard against stack overflow in JNI + + int transformLength = length - partlen; + int transformOffset = partlen + offset; + final int MAX_LENGTH = 65536; // prevent stack overflow in JNI + while (true) { + if (transformLength > MAX_LENGTH) { + Transform_native(stat.state, buffer, transformOffset, MAX_LENGTH); + transformLength -= MAX_LENGTH; + transformOffset += MAX_LENGTH; + } else { + Transform_native(stat.state, buffer, transformOffset, transformLength); + break; + } + } + } + + // update state (using only Java) to reflect input + + else { + int[] decode_buf = new int[16]; + if (partlen == 64) { + partlen = 0; + } else { + for (i = 0; i < partlen; i++) + stat.buffer[i + index] = buffer[i + offset]; + Transform(stat, stat.buffer, 0, decode_buf); + } + for (i = partlen; (i + 63) < length; i+= 64) { + Transform(stat, buffer, i + offset, decode_buf); + } + } + index = 0; + } else { + i = 0; + } + + /* buffer remaining input */ + if (i < length) { + start = i; + for (; i < length; i++) { + stat.buffer[index + i - start] = buffer[i + offset]; + } + } + } + + /* + * Update()s for other datatypes than byte[] also. Update(byte[], int) + * is only the main driver. + */ + + /** + * Plain update, updates this object + **/ + public void Update (byte buffer[], int offset, int length) { + Update(this.state, buffer, offset, length); + } + + public void Update (byte buffer[], int length) { + Update(this.state, buffer, 0, length); + } + + /** + * Updates hash with given array of bytes + * + * @param buffer Array of bytes to use for updating the hash + **/ + public void Update (byte buffer[]) { + Update(buffer, 0, buffer.length); + } + + /** + * Updates hash with a single byte + * + * @param b Single byte to update the hash + **/ + public void Update (byte b) { + byte buffer[] = new byte[1]; + buffer[0] = b; + + Update(buffer, 1); + } + + /** + * Update buffer with given string. Note that because the version of + * the s.getBytes() method without parameters is used to convert the + * string to a byte array, the results of this method may be different + * on different platforms. The s.getBytes() method converts the string + * into a byte array using the current platform's default character set + * and may therefore have different results on platforms with different + * default character sets. If a version that works consistently + * across platforms with different default character sets is desired, + * use the overloaded version of the Update() method which takes a + * string and a character encoding. + * + * @param s String to be update to hash (is used as s.getBytes()) + **/ + public void Update (String s) { + byte chars[] = s.getBytes(); + Update(chars, chars.length); + } + + /** + * Update buffer with given string using the given encoding. If the + * given encoding is null, the encoding "ISO8859_1" is used. + * + * @param s String to be update to hash (is used as + * s.getBytes(charset_name)) + * @param charset_name The character set to use to convert s to a + * byte array, or null if the "ISO8859_1" + * character set is desired. + * @exception java.io.UnsupportedEncodingException If the named + * charset is not supported. + **/ + public void Update (String s, String charset_name) throws java.io.UnsupportedEncodingException { + if (charset_name == null) charset_name = "ISO8859_1"; + byte chars[] = s.getBytes(charset_name); + Update(chars, chars.length); + } + + /** + * Update buffer with a single integer (only & 0xff part is used, + * as a byte) + * + * @param i Integer value, which is then converted to byte as i & 0xff + **/ + public void Update (int i) { + Update((byte) (i & 0xff)); + } + + private byte[] Encode (int input[], int len) { + int i, j; + byte out[]; + + out = new byte[len]; + + for (i = j = 0; j < len; i++, j += 4) { + out[j] = (byte) (input[i] & 0xff); + out[j + 1] = (byte) ((input[i] >>> 8) & 0xff); + out[j + 2] = (byte) ((input[i] >>> 16) & 0xff); + out[j + 3] = (byte) ((input[i] >>> 24) & 0xff); + } + + return out; + } + + /** + * Returns array of bytes (16 bytes) representing hash as of the + * current state of this object. Note: getting a hash does not + * invalidate the hash object, it only creates a copy of the real + * state which is finalized. + * + * @return Array of 16 bytes, the hash of all updated bytes + **/ + public synchronized byte[] Final () { + byte bits[]; + int index, padlen; + MD5State fin; + + if (finals == null) { + fin = new MD5State(state); + + int[] count_ints = {(int) (fin.count << 3), (int) (fin.count >> 29)}; + bits = Encode(count_ints, 8); + + index = (int) (fin.count & 0x3f); + padlen = (index < 56) ? (56 - index) : (120 - index); + + Update(fin, padding, 0, padlen); + Update(fin, bits, 0, 8); + + /* Update() sets finals to null */ + finals = fin; + } + + return Encode(finals.state, 16); + } + + private static final char[] HEX_CHARS = {'0', '1', '2', '3', + '4', '5', '6', '7', + '8', '9', 'a', 'b', + 'c', 'd', 'e', 'f',}; + + /** + * Turns array of bytes into string representing each byte as + * unsigned hex number. + * + * @param hash Array of bytes to convert to hex-string + * @return Generated hex string + */ + public static String asHex (byte hash[]) { + char buf[] = new char[hash.length * 2]; + for (int i = 0, x = 0; i < hash.length; i++) { + buf[x++] = HEX_CHARS[(hash[i] >>> 4) & 0xf]; + buf[x++] = HEX_CHARS[hash[i] & 0xf]; + } + return new String(buf); + } + + /** + * Returns 32-character hex representation of this objects hash + * + * @return String of this object's hash + */ + public String asHex () { + return asHex(this.Final()); + } + + public static synchronized final void initNativeLibrary (boolean disallow_lib_loading) { + if (disallow_lib_loading) { + native_lib_init_pending = false; + } else { + _initNativeLibrary(); + } + } + + private static synchronized final void _initNativeLibrary () { + if (!native_lib_init_pending) return; + native_lib_loaded = _loadNativeLibrary(); + native_lib_init_pending = false; + } + + private static synchronized final boolean _loadNativeLibrary () { + try { + + // don't try to load if the right property is set + + String prop = System.getProperty("com.twmacinta.util.MD5.NO_NATIVE_LIB"); + if (prop != null) { + prop = prop.trim(); + if (prop.equalsIgnoreCase("true") || prop.equals("1")) return false; + } + + // the library to load can be specified as a property + + File f; + prop = System.getProperty("com.twmacinta.util.MD5.NATIVE_LIB_FILE"); + if (prop != null) { + f = new File(prop); + if (f.canRead()) { + System.load(f.getAbsolutePath()); + return true; + } + } + + // determine the operating system and architecture + + String os_name = System.getProperty("os.name"); + String os_arch = System.getProperty("os.arch"); + if (os_name == null || os_arch == null) return false; + os_name = os_name.toLowerCase(); + os_arch = os_arch.toLowerCase(); + + // define settings which are OS arch architecture independent + + File arch_lib_path = null; + String arch_libfile_suffix = null; + + // fill in settings for Linux on x86 + + if (os_name.equals("linux") && + (os_arch.equals("x86") || + os_arch.equals("i386") || + os_arch.equals("i486") || + os_arch.equals("i586") || + os_arch.equals("i686"))) { + arch_lib_path = new File(new File(new File("lib"), "arch"), "linux_x86"); + arch_libfile_suffix = ".so"; + } + + // fill in settings for Windows on x86 + + else if (os_name.startsWith("windows ") && + (os_arch.equals("x86") || + os_arch.equals("i386") || + os_arch.equals("i486") || + os_arch.equals("i586") || + os_arch.equals("i686"))) { + arch_lib_path = new File(new File(new File("lib"), "arch"), "win32_x86"); + arch_libfile_suffix = ".dll"; + } + + // fill in settings for Mac OS X on PPC + + else if (os_name.startsWith("mac os x") && + (os_arch.equals("ppc"))) { + arch_lib_path = new File(new File(new File("lib"), "arch"), "darwin_ppc"); + arch_libfile_suffix = ".jnilib"; + } + + // fill in settings for Mac OS X on x86 + + else if (os_name.startsWith("mac os x") && + (os_arch.equals("x86") || + os_arch.equals("i386") || + os_arch.equals("i486") || + os_arch.equals("i586") || + os_arch.equals("i686"))) { + arch_lib_path = new File(new File(new File("lib"), "arch"), "darwin_x86"); + arch_libfile_suffix = ".jnilib"; + } + + // default to .so files with no architecture specific subdirectory + + else { + arch_libfile_suffix = ".so"; + } + + // build the required filename + + String fname = "MD5" + arch_libfile_suffix; + + // try the architecture specific directory + + if (arch_lib_path != null) { + f = new File(arch_lib_path, fname); + if (f.canRead()) { + System.load(f.getAbsolutePath()); + return true; + } + } + + // try the "lib" subdirectory + + f = new File(new File("lib"), fname); + if (f.canRead()) { + System.load(f.getAbsolutePath()); + return true; + } + + // try the working directory + + f = new File(fname); + if (f.canRead()) { + System.load(f.getAbsolutePath()); + return true; + } + } + + // discard SecurityExceptions + + catch (SecurityException e) {} + + // unable to load + + return false; + } + + /** + * Calculates and returns the hash of the contents of the given file. + **/ + public static byte[] getHash (File f) throws IOException { + if (!f.exists()) throw new FileNotFoundException(f.toString()); + InputStream close_me = null; + try { + long buf_size = f.length(); + if (buf_size < 512) buf_size = 512; + if (buf_size > 65536) buf_size = 65536; + byte[] buf = new byte[(int) buf_size]; + MD5InputStream in = new MD5InputStream(new FileInputStream(f)); + close_me = in; + while (in.read(buf) != -1); + in.close(); + return in.hash(); + } catch (IOException e) { + if (close_me != null) try { close_me.close(); } catch (Exception e2) {} + throw e; + } + } + + /** + * @return true iff the first 16 bytes of both hash1 and hash2 are + * equal; both hash1 and hash2 are null; or either hash + * array is less than 16 bytes in length and their lengths and + * all of their bytes are equal. + **/ + public static boolean hashesEqual (byte[] hash1, byte[] hash2) { + if (hash1 == null) return hash2 == null; + if (hash2 == null) return false; + int targ = 16; + if (hash1.length < 16) { + if (hash2.length != hash1.length) return false; + targ = hash1.length; + } else if (hash2.length < 16) { + return false; + } + for (int i = 0; i < targ; i++) { + if (hash1[i] != hash2[i]) return false; + } + return true; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/MD5.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/MD5InputStream.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/MD5InputStream.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/MD5InputStream.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/MD5InputStream.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,169 @@ +package org.nuiton.util; + +import java.io.*; + +/** + * MD5InputStream, a subclass of FilterInputStream implementing MD5 + * functionality on a stream. + * <p> + * Originally written by Santeri Paavolainen, Helsinki Finland 1996 <br> + * (c) Santeri Paavolainen, Helsinki Finland 1996 <br> + * Some changes Copyright (c) 2002 Timothy W Macinta <br> + * <p> + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * <p> + * This library 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 + * Library General Public License for more details. + * <p> + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * <p> + * See http://www.twmacinta.com/myjava/fast_md5.php for more information + * on this file. + * <p> + * Please note: I (Timothy Macinta) have put this code in the + * com.twmacinta.util package only because it came without a package. I + * was not the the original author of the code, although I did + * optimize it (substantially) and fix some bugs. + * + * @author Santeri Paavolainen <santtu@cs.hut.fi> + * @author Timothy W Macinta (twm@alum.mit.edu) (added main() method) + **/ + + +public class MD5InputStream extends FilterInputStream { + /** + * MD5 context + */ + private MD5 md5; + + /** + * Creates a MD5InputStream + * @param in The input stream + */ + public MD5InputStream (InputStream in) { + super(in); + + md5 = new MD5(); + } + + /** + * Read a byte of data. + * @see java.io.FilterInputStream + */ + public int read() throws IOException { + int c = in.read(); + + if (c == -1) + return -1; + + if ((c & ~0xff) != 0) { + System.out.println("MD5InputStream.read() got character with (c & ~0xff) != 0)!"); + } else { + md5.Update(c); + } + + return c; + } + + /** + * Reads into an array of bytes. + * + * @see java.io.FilterInputStream + */ + public int read (byte bytes[], int offset, int length) throws IOException { + int r; + + if ((r = in.read(bytes, offset, length)) == -1) + return r; + + md5.Update(bytes, offset, r); + + return r; + } + + /** + * Returns array of bytes representing hash of the stream as + * finalized for the current state. + * @see MD5#Final + */ + public byte[] hash () { + return md5.Final(); + } + + public MD5 getMD5() { + return md5; + } + + /** + * This method is here for testing purposes only - do not rely + * on it being here. + **/ + public static void main(String[] arg) { + try { + + //////////////////////////////////////////////////////////////// + // + // usage: java com.twmacinta.util.MD5InputStream [--use-default-md5] [--no-native-lib] filename + // + ///////// + + // determine the filename to use and the MD5 impelementation to use + + String filename = arg[arg.length-1]; + boolean use_default_md5 = false; + boolean use_native_lib = true; + for (int i = 0; i < arg.length-1; i++) { + if (arg[i].equals("--use-default-md5")) { + use_default_md5 = true; + } else if (arg[i].equals("--no-native-lib")) { + use_native_lib = false; + } + } + + // initialize common variables + + byte[] buf = new byte[65536]; + int num_read; + + // Use the default MD5 implementation that comes with Java + + if (use_default_md5) { + InputStream in = new BufferedInputStream(new FileInputStream(filename)); + java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); + while ((num_read = in.read(buf)) != -1) { + digest.update(buf, 0, num_read); + } + System.out.println(MD5.asHex(digest.digest())+" "+filename); + in.close(); + + // Use the optimized MD5 implementation + + } else { + + // disable the native library search, if requested + + if (!use_native_lib) { + MD5.initNativeLibrary(true); + } + + // calculate the checksum + + MD5InputStream in = new MD5InputStream(new BufferedInputStream(new FileInputStream(filename))); + while ((num_read = in.read(buf)) != -1); + System.out.println(MD5.asHex(in.hash())+" "+filename); + in.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + +} + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/MD5InputStream.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/MD5OutputStream.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/MD5OutputStream.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/MD5OutputStream.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/MD5OutputStream.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,117 @@ +package org.nuiton.util; + +import java.io.*; + +/** + * MD5OutputStream is a subclass of FilterOutputStream adding MD5 + * hashing of the output. + * <p> + * Originally written by Santeri Paavolainen, Helsinki Finland 1996 <br> + * (c) Santeri Paavolainen, Helsinki Finland 1996 <br> + * Some changes Copyright (c) 2002 Timothy W Macinta <br> + * <p> + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * <p> + * This library 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 + * Library General Public License for more details. + * <p> + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * <p> + * See http://www.twmacinta.com/myjava/fast_md5.php for more information + * on this file. + * <p> + * Please note: I (Timothy Macinta) have put this code in the + * com.twmacinta.util package only because it came without a package. I + * was not the the original author of the code, although I did + * optimize it (substantially) and fix some bugs. + * + * @author Santeri Paavolainen <santtu@cs.hut.fi> + * @author Timothy W Macinta (twm@alum.mit.edu) (added main() method) + **/ + +public class MD5OutputStream extends FilterOutputStream { + /** + * MD5 context + */ + private MD5 md5; + + /** + * Creates MD5OutputStream + * @param out The output stream + */ + + public MD5OutputStream (OutputStream out) { + super(out); + + md5 = new MD5(); + } + + /** + * Writes a byte. + * + * @see java.io.FilterOutputStream + */ + + public void write (int b) throws IOException { + out.write(b); + md5.Update((byte) b); + } + + /** + * Writes a sub array of bytes. + * + * @see java.io.FilterOutputStream + */ + + public void write (byte b[], int off, int len) throws IOException { + out.write(b, off, len); + md5.Update(b, off, len); + } + + /** + * Returns array of bytes representing hash of the stream as finalized + * for the current state. + * @see MD5#Final + */ + + public byte[] hash () { + return md5.Final(); + } + + public MD5 getMD5() { + return md5; + } + + /* + * This method is here for testing purposes only - do not rely + * on it being here. + * + public static void main(String[] arg) { + try { + MD5OutputStream out = new MD5OutputStream(new com.twmacinta.io.NullOutputStream()); + InputStream in = new BufferedInputStream(new FileInputStream(arg[0])); + byte[] buf = new byte[65536]; + int num_read; + long total_read = 0; + while ((num_read = in.read(buf)) != -1) { + total_read += num_read; + out.write(buf, 0, num_read); + } + System.out.println(MD5.asHex(out.hash())+" "+arg[0]); + in.close(); + out.close(); + } catch (Exception e) { + e.printStackTrace(); + } + }*/ + + +} + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/MD5OutputStream.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/MD5State.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/MD5State.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/MD5State.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/MD5State.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,79 @@ +package org.nuiton.util; + +/** + * Fast implementation of RSA's MD5 hash generator in Java JDK Beta-2 or higher<br> + * Originally written by Santeri Paavolainen, Helsinki Finland 1996 <br> + * (c) Santeri Paavolainen, Helsinki Finland 1996 <br> + * Some changes Copyright (c) 2002 Timothy W Macinta <br> + * <p> + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * <p> + * This library 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 + * Library General Public License for more details. + * <p> + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the Free + * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * <p> + * See http://www.twmacinta.com/myjava/fast_md5.php for more information + * on this file. + * <p> + * Contains internal state of the MD5 class + * <p> + * Please note: I (Timothy Macinta) have put this code in the + * com.twmacinta.util package only because it came without a package. I + * was not the the original author of the code, although I did + * optimize it (substantially) and fix some bugs. + * + * @author Santeri Paavolainen <sjpaavol@cc.helsinki.fi> + * @author Timothy W Macinta (twm@alum.mit.edu) (optimizations and bug fixes) + **/ + +class MD5State { + /** + * 128-bit state + */ + int state[]; + + /** + * 64-bit character count + */ + long count; + + /** + * 64-byte buffer (512 bits) for storing to-be-hashed characters + */ + byte buffer[]; + + public MD5State() { + buffer = new byte[64]; + count = 0; + state = new int[4]; + + state[0] = 0x67452301; + state[1] = 0xefcdab89; + state[2] = 0x98badcfe; + state[3] = 0x10325476; + + } + + /** Create this State as a copy of another state */ + public MD5State (MD5State from) { + this(); + + int i; + + for (i = 0; i < buffer.length; i++) + this.buffer[i] = from.buffer[i]; + + for (i = 0; i < state.length; i++) + this.state[i] = from.state[i]; + + this.count = from.count; + } +}; Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/MD5State.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/MonthEnum.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/MonthEnum.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/MonthEnum.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/MonthEnum.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,70 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import static org.nuiton.i18n.I18n._; + +/** + * Une énumération pour représenter les mois d'une année. + * + * @author chemit + */ + +public enum MonthEnum { + JANUARY(_("lutinutil.month.january")), + FEBRUARY(_("lutinutil.month.february")), + MARCH(_("lutinutil.month.march")), + APRIL(_("lutinutil.month.april")), + MAY(_("lutinutil.month.may")), + JUNE(_("lutinutil.month.june")), + JULY(_("lutinutil.month.july")), + AUGUST(_("lutinutil.month.august")), + SEPTEMBER(_("lutinutil.month.september")), + OCTOBER(_("lutinutil.month.october")), + NOVEMBER(_("lutinutil.month.november")), + DECEMBER(_("lutinutil.month.december")); + + private final String libelle; + + MonthEnum(String libelle) { + this.libelle = libelle; + } + + public String getLibelle() { + return libelle; + } + + public static MonthEnum valueOf(String month, MonthEnum defaultValue) { + MonthEnum monthEnum = null; + try { + monthEnum = MonthEnum.valueOf(month.toUpperCase()); + } catch (IllegalArgumentException e) { + System.err.println(_("lutinutil.error.unfound.month", month, defaultValue)); + } catch (NullPointerException e) { + System.err.println(_("lutinutil.error.unfound.month", month, defaultValue)); + } + return monthEnum == null ? defaultValue : monthEnum; + } + + @Override + public String toString() { + // on force la traduction (au cas où i18n n'était pas ini au moment + // du chargement de l'enum...) + return _(libelle); + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/MonthEnum.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ObjectUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ObjectUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ObjectUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ObjectUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,402 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * ObjectUtil.java + * + * Created: 2 nov. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import java.lang.reflect.Array; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; + +import static org.nuiton.i18n.I18n._; + +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 + * can make an instance of this class + */ + private ObjectUtil() {} + + /** + * Create new object from string like org.codelutin.Toto(name=machine, int=10) + * where machine and int is properties on org.codelutin.Toto object. + * Conversion between 10 in string and 10 as integer as automaticaly done + * + * For String property you can use ex: + * <li> name="my string with , in string" + * <li> name='my string with , in string' + * + * @param classnameAndProperties + * @return the instanciated object + * @throws ClassNotFoundException + * @throws IllegalAccessException + * @throws InstantiationException + * @throws NoSuchMethodException + * @throws InvocationTargetException + */ + public static Object create(String classnameAndProperties) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { + int p = classnameAndProperties.indexOf('('); + int l = classnameAndProperties.lastIndexOf(')'); + String [] properties = null; + String classname = null; + if (p != -1) { + String tmp = classnameAndProperties.substring(p + 1, l); + properties = StringUtil.split(tmp, ","); + classname = classnameAndProperties.substring(0, p); + } else { + classname = classnameAndProperties; + } + Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(classname); + Object o = clazz.newInstance(); + if (properties != null) { + for (String prop : properties) { + int e = prop.indexOf('='); + String propName = prop.substring(0, e).trim(); + String propValue = prop.substring(e+1).trim(); + if (propValue.charAt(0) == '"' && propValue.charAt(propValue.length()-1) == '"') { + propValue = propValue.substring(1, propValue.length()-1); + } else if (propValue.charAt(0) == '\'' && propValue.charAt(propValue.length()-1) == '\'') { + propValue = propValue.substring(1, propValue.length()-1); + } + BeanUtils.setProperty(o, propName, propValue); + } + } + 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 + * @param o object where method must be call + * @param m method to call + * @param params parameters for method call + * @return returned method's value + * @throws IllegalAccessException + * @throws IllegalArgumentException + * @throws InvocationTargetException + * @throws InstantiationException + */ + public static Object call(Object o, Method m, String ... params) + throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException { + Class<?>[] types = m.getParameterTypes(); + 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<last; i++) { + String v = params[i]; + Class<?> clazz = types[i]; + 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<Object> tmp = new ArrayList<Object>(); + 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(_("lutinutil.debug.objectutil.invoke", m, Arrays.toString(parameters))); + } + Object result = m.invoke(o, parameters); + return result; + } + + /** + * Get all methods with name given in argument without check parameters + * @param clazz + * @param methodName method name to search + * @param ignoreCase if true, ignore difference in method name case + * @return list of detected methods + */ + public static List<Method> getMethod(Class<?> clazz, String methodName, boolean ignoreCase) { + List<Method> result = new ArrayList<Method>(); + + Method[] methods = clazz.getMethods(); + for (Method m : methods) { + if(ignoreCase && methodName.equalsIgnoreCase(m.getName()) || + methodName.equals(m.getName())) { + result.add(m); + } + } + + return result; + } + + public static Object newInstance(String constructorWithParams) throws ClassNotFoundException { + int p = constructorWithParams.indexOf('('); + int l = constructorWithParams.lastIndexOf(')'); + String [] params = null; + String classname = null; + if (p != -1) { + String tmp = constructorWithParams.substring(p + 1, l); + params = StringUtil.split(tmp, ","); + classname = constructorWithParams.substring(0, p); + } else { + classname = constructorWithParams; + } + Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(classname); + Object result = newInstance(clazz, params); + return result; + } + /** + * Create new instance of clazz, call constructor with params as String. + * Each param is converted to required type for + * constructor with beanutils converter, first constructor that permit + * instanciation is used + * + * @param <T> type to instanciate + * @param clazz class to instanciate + * @param params parameters for constructor call + * @return new instance of clazz + * @throws IllegalArgumentException + */ + public static <T> T newInstance(Class<T> clazz, String ... params) + throws IllegalArgumentException { + if (params == null) { + params = new String[0]; + } + List<Constructor<T>> constructors = getConstructor(clazz, params.length); + + for (Constructor<T> c : constructors) { + try { + Class<?>[] types = c.getParameterTypes(); + + int last = types.length; + if (c.isVarArgs()) { + // on traite le dernier differement + last--; + } + + Object[] parameters = new Object[types.length]; + for (int i = 0; i < last; i++) { + String v = params[i]; + Class<?> argClazz = types[i]; + Object t = convert(v, argClazz); + parameters[i] = t; + } + + if (c.isVarArgs()) { + Class<?> argClazz = types[last]; // get var args type + argClazz = argClazz.getComponentType(); // get array component type + List<Object> tmp = new ArrayList<Object>(); + for (int i = last; i < params.length; i++) { + String v = params[i]; + Object t = convert(v, argClazz); + tmp.add(t); + } + parameters[last] = tmp.toArray((Object[]) Array.newInstance(argClazz, tmp.size())); + } + + if (log.isDebugEnabled()) { + log.debug(_("lutinutil.debug.objectutil.create", clazz, Arrays.toString(parameters))); + } + T result = c.newInstance(parameters); + + return result; + } catch(Exception eee) { + // this constructors don't work, try next + if (log.isDebugEnabled()) { + log.debug("Creation failed try with next constructor"); + } + } + } + throw new IllegalArgumentException(_("lutinutil.debug.objectutil.instantiate", + clazz, Arrays.toString(params))); + } + + /** + * Get all constructors that support paramNumber as parameters numbers. + * Varargs is supported + * + * @param <T> le type de la classe a inspecter + * @param clazz la classe sur lequel rechercher le constructeur + * @param paramNumber le nombre de parametre souhaite pour le constructeur, + * -1 indique que tous les constructeur sont souhaite. + * @return list of constructors + */ + @SuppressWarnings("unchecked") + public static <T> List<Constructor<T>> getConstructor(Class<T> clazz, int paramNumber) { + List<Constructor<T>> result = new ArrayList<Constructor<T>>(); + Constructor<T>[] constructors = (Constructor<T>[])clazz.getConstructors(); + for (Constructor<T> c : constructors) { + if (paramNumber < 0 || + (c.isVarArgs() && c.getParameterTypes().length <= paramNumber - 1) || + c.getParameterTypes().length == paramNumber) { + result.add(c); + } + } + + return result; + } + + /** + * Method toObject + * + * @param o Object to transform + * @return the same object + */ + public static Object toObject(Object o){ + return o; + } + + /** + * Method toObject + * + * transform a char to a Character Object + * @param c the char to transform + * @return the Charactere object corresponding + */ + public static Object toObject(char c){ + return new Character(c); + } + + /** + * Method toObject + * + * transform a byte to a Byte Object + * @param b the byte to transform + * @return the byte object corresponding + */ + public static Object toObject(byte b){ + return new Byte(b); + } + + /** + * Method toObject + * + * transform a short to a Short object + * @param s the short to transform + * @return the Short object corresponding + */ + public static Object toObject(short s){ + return new Short(s); + } + + /** + * Method toObject + * + * transform an int to an Integer object + * @param i the int to transform + * @return the Integer Object corresponding + */ + public static Object toObject(int i){ + return new Integer(i); + } + + /** + * Method toObject + * + * transform a long to a Long object + * @param l the long to transform + * @return the Long Object corresponding + */ + public static Object toObject(long l){ + return new Long(l); + } + + /** + * Method toObject + * + * transform a float to a Float Object + * @param f the float to transform + * @return the Float Object corresponding + */ + public static Object toObject(float f){ + return new Float(f); + } + + /** + * Method toObject + * + * transform a double to a Double object + * @param d the double to transform + * @return the Double object corresponding + */ + public static Object toObject(double d){ + return new Double(d); + } + + /** + * Method toObject + * + * transform a boolean to a Boolean object + * @param b the boolean to transform + * @return the Boolean object corresponding + */ + public static Object toObject(boolean b){ + return b?Boolean.TRUE:Boolean.FALSE; + } + +} // ObjectUtil + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ObjectUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/PropertiesDateRemoveFilterStream.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,48 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.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 = System.getProperty("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); + } + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/RecursiveProperties.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/RecursiveProperties.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/RecursiveProperties.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/RecursiveProperties.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,95 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * RecursiveProperties.java + * + * Created: 28 juil. 2005 + * + * @author Arnaud Thimel <thimel@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import java.util.Properties; + +/** + * Surcharge java.util.Properties de manière à aller chercher dans les + * properties la valeur de la propriété si celle ci est encadrée par "${...}". + * <p/> + * Exemple : + * myFirstName=Arnaud + * myName=Thimel + * org.codelutin.topia.userInfo.fullName=${fullName} + * fullName=${myFirstName} ${myName} + * namePhrase=My name is ${myName}. + * instruction=Placez votre texte comme ceci : ${monTexte} + * <p/> + * Dans ce cas, + * getProperty("org.codelutin.topia.userInfo.fullName") renverra "Arnaud Thimel" + * getProperty("namePhrase") renverra "My name is Thimel." + * getProperty("instruction") renverra "Placez votre texte comme ceci : ${monTexte}" + * + * @author thimel + */ +public class RecursiveProperties extends Properties { + + private static final long serialVersionUID = -5012939272780929116L; + + public RecursiveProperties() { + super(); + } + + public RecursiveProperties(Properties defaults) { + super(defaults); + } + + @Override + public String getProperty(String key) { + String result = super.getProperty(key); + if (result == null) + return null; + //Ex : result="My name is ${myName}." + int pos = result.indexOf("${", 0); + //Ex : pos=11 + while (pos != -1) { + int posEnd = result.indexOf("}", pos + 1); + //Ex : posEnd=19 + if (posEnd != -1) { + String value = getProperty(result.substring(pos + 2, posEnd)); + // Ex : getProperty("myName"); + if (value != null) { + // Ex : value="Thimel" + result = result.substring(0, pos) + value + result.substring(posEnd + 1); + // Ex : result="My name is " + "Thimel" + "." + pos = result.indexOf("${", pos + value.length()); + // Ex : pos=-1 + } else + // Ex : value=null + pos = result.indexOf("${", posEnd + 1); + // Ex : pos=-1 + } + } + return result; + } + +} //RecursiveProperties Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/RecursiveProperties.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ReflectUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ReflectUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ReflectUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ReflectUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,113 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; + +/** + * Des méthodes utiles d'introspection + * + * @author tony + */ +public class ReflectUtil { + /** + * Pour déterminer si un champ d'une classe est une constante + * (modifiers sont static, final et public) + * + * @param field le champs à tester + * @return <code>true</code> si les modifiers sont final, static et public + */ + public static boolean isConstantField(Field field) { + int modifiers = field.getModifiers(); + return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers); + } + + /** + * Recherche dans une classe donnée <code>klazz</code>, les constantes d'un + * certain type <code>searchingClass</code> et les retourne. + * <p/> + * L'algorithme parcourt aussi les superclasses. + * + * @param klass la classe contenant les constantes + * @param searchingClass le type des champs constants à récupérer + * @return la liste des champs du type requis dans + * @throws RuntimeException si problème lors de la récupération + */ + @SuppressWarnings({"unchecked"}) + public static <T> List<T> getConstants(Class<?> klass, Class<T> searchingClass) { + List<T> result = new ArrayList<T>(); + for (Field field : klass.getDeclaredFields()) { + if (!field.isAccessible()) { + field.setAccessible(true); + } + if (searchingClass.isAssignableFrom(field.getType()) && isConstantField(field)) { + try { + result.add((T) field.get(null)); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + } + Class<?> superClass = klass.getSuperclass(); + if (superClass != null) { + result.addAll(getConstants(superClass, searchingClass)); + } + return result; + } + + /** + * @param klass the required class + * @param fieldName the required constant name + * @return the constant value + */ + @SuppressWarnings({"unchecked"}) + public static <T> T getConstant(Class<?> klass, String fieldName) { + try { + T result = null; + Field f = klass.getDeclaredField(fieldName); + if (isConstantField(f)) { + f.setAccessible(true); + result = (T) f.get(null); + } + return result; + } catch (NoSuchFieldException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + /** + * Convertit une classe non typée, en une classe d'enum + * + * @param type la classe à type + * @return la classe typée + * @throws IllegalArgumentException si le type est null ou non une extension + * de la classe Enum. + */ + @SuppressWarnings({"unchecked"}) + protected static <T extends Enum<T>> Class<T> getEnumClass(Class<?> type) throws IllegalArgumentException { + if (type == null || !type.isEnum()) { + throw new IllegalArgumentException(type + " should not be null, nor a non Enum "); + } + return (Class<T>) type; + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ReflectUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/Resource.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/Resource.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/Resource.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/Resource.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,668 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/** + * Resource.java + * + * Created: Sun Apr 14 2002 + * + * @author POUSSIN Benjamin <bpoussin@free.fr> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import static org.nuiton.i18n.I18n._; + +import javax.swing.ImageIcon; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.jar.Attributes; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; + +/** + * Cette class permet de rechercher un fichier en indiquant son nom avec son + * chemin. Cette librairie ira ensuite chercher ce fichier sur le système de + * fichier, et s'il n'est pas trouvé dans le classpath. Le fichier peut donc + * être dans un fichier .jar ou .zip. + */ +public class Resource { // Resource + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static final Log log = LogFactory.getLog(Resource.class); + + protected Resource() { + + } + + /** + * Permet d'ajouter dans le classloader par defaut une nouvelle URL dans + * lequel il faut rechercher les fichiers. + * + * @param url l'url a ajouter + */ + static public void addDefaultClassLoader(URL url) { + ClassLoader classLoader = ClassLoader.getSystemClassLoader(); + addClassLoader(classLoader, url); + } + + /** + * Permet d'ajouter dans un classloader une nouvelle URL dans + * lequel il faut rechercher les fichiers. + * + * @param classLoader le classloader a modifier + * @param url l'url a ajouter + */ + static public void addClassLoader(ClassLoader classLoader, URL url) { + try { + Method method = URLClassLoader.class.getDeclaredMethod("addURL", + new Class[]{URL.class}); + method.setAccessible(true); + method.invoke(classLoader, url); + } catch (Exception eee) { + throw new RuntimeException(_("lutinutil.error.add.url.in.classloader", classLoader, eee)); + //throw new RuntimeException("Can't add url in classloader " + classLoader,eee); + } + } + + /** + * Recherche la ressource nom. + * + * @param name nom de la ressource + * @return l'url de la ressource + * @throws ResourceNotFoundException si la resource n'a pas ete trouvee + */ + static public URL getURL(String name) { + URL url = getURLOrNull(name); + if (url != null) { + return url; + } + + throw new ResourceNotFoundException(_("lutinutil.error.resource.not.found", name)); + } + + /** + * Recherche la ressource nom. + * + * @param name le nom de la ressource + * @return l'url de la ressource ou null + */ + static public URL getURLOrNull(String name) { + // on recherche d'abord sur le filesystem + File file = new File(name); + if (file.exists()) { + try { + return file.toURI().toURL(); + } catch (MalformedURLException eee) { + log.warn(_("lutinutil.error.convert.file.to.url", file, eee.getMessage())); + } + } + + // on ne l'a pas trouve on recherche dans le classpath + + // on supprime le / devant le nom de la ressource, sinon elle + // n'est pas trouve (pas de recherche dans les differents + // element du classpath. + if (name.length() > 1 && name.startsWith("/")) { + name = name.substring(1); + } + URL url = ClassLoader.getSystemClassLoader().getResource(name); + if (url != null) { + return url; + } + + ClassLoader cl = Resource.class.getClassLoader(); + url = cl.getResource(name); + return url; + } + + /** + * Retourne l'icone demandee. + * + * @param name le nom de l'icone + * @return Retourne l'icon demande ou null s'il n'est pas trouvé + */ + static public ImageIcon getIcon(String name) { + try { + return new ImageIcon(getURL(name)); + } catch (Exception eee) { + log.warn("Can't find icon: " + name, eee); + return null; + } + } + + /** + * Recherche et retourne l'objet properties de configuration à utiliser. + * <p/> + * Les différents fichiers trouvé sont chainé. L'ordre de recherche est le + * classpath, le fichier dans /etc et enfin le chemin sur le filesystem. + * + * @param filename le nom du fichier à rechercher + * @return l'objet Properties de configuration + * @throws IOException si une erreur est survenue + */ + static public Properties getConfigProperties(String filename) + throws IOException { + Properties result; + result = getConfigProperties(filename, null); + return result; + } + + /** + * Recherche et retourne l'objet properties de configuration à utiliser. + * <p/> + * Les différents fichiers trouvé sont chainé. L'ordre de recherche est le + * classpath, le fichier dans /etc et enfin le chemin sur le filesystem. + * + * @param filename le nom du fichier à rechercher + * @param parent les proprietes parent a surcharger + * @return l'objet Properties de configuration + * @throws IOException si une erreur est survenue + */ + static public Properties getConfigProperties(String filename, + Properties parent) throws IOException { + Properties result; + if (parent != null) { + result = new Properties(parent); + } else { + result = new Properties(); + } + + URL inClasspath = ClassLoader.getSystemClassLoader().getResource( + filename); + if (inClasspath == null) { + inClasspath = Resource.class.getResource(filename); + } + if (inClasspath == null) { + inClasspath = getURLOrNull(filename); + } + if (inClasspath != null) { + log.info("Chargement du fichier de config: " + inClasspath); + result.load(inClasspath.openStream()); + result = new Properties(result); + } + + File etcConfig = new File("/etc/" + filename); + if (etcConfig.exists()) { + log.info("Chargement du fichier de config: " + etcConfig); + result.load(etcConfig.toURI().toURL().openStream()); + result = new Properties(result); + } + + File config = new File(filename); + if (config.exists()) { + log.info("Chargement du fichier de config: " + config); + result.load(config.toURI().toURL().openStream()); + result = new Properties(result); + } + + return result; + } + + /** + * Retourner la liste des fichiers du classLoader. Ces fichiers doivent + * correspondre au pattern donne. + * + * @param pattern le nom du fichier a extraire du fichier compressé ou + * du repertoire doit correspondre au pattern (repertoire + nom + * compris). + * @return la liste des urls correspondant au pattern + */ + static public List<URL> getURLs(String pattern) { + return getURLs(pattern, (URLClassLoader) null); + } + + /** + * Recupere la liste des urls d'un {@link java.net.URLClassLoader}. + * <p/> + * Note : Un cas particulier est positionné pour JBoss qui utilise la method getAllURLs. + * + * @param classLoader le class loader a scanner + * @return les urls du classloade. + * @deprecated should use now {@link org.codelutin.util.ClassLoaderUtil#getURLs(java.net.URLClassLoader)} + */ + static public URL[] getURLs(URLClassLoader classLoader) { + return ClassLoaderUtil.getURLs(classLoader); + } + + /** + * Retourner la liste des fichiers du classLoader. Ces fichiers doivent + * correspondre au pattern donne. + * + * @param classLoader le classLoader + * @param pattern le nom du fichier a extraire du fichier compressé ou + * du repertoire doit correspondre au pattern (repertoire + nom + * compris). + * @return la liste des urls correspondant au pattern + */ + static public List<URL> getURLs(String pattern, URLClassLoader classLoader) { + if (classLoader == null) { + classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader(); + } + URL[] arrayURL = ClassLoaderUtil.getURLs(classLoader); + return getURLs(pattern, arrayURL); + } + + /** + * Retourner la liste des fichiers du classLoader. Ces fichiers doivent + * correspondre au pattern donne. + * + * @param arrayURL les urls ou chercher + * @param pattern le nom du fichier a extraire du fichier compressé ou + * durepertoire doit correspondre au pattern (repertoire + nom + * compris). + * @return la liste des urls correspondant au pattern + */ + static public List<URL> getURLs(String pattern, URL... arrayURL) { + long t0 = System.nanoTime(); + + HashList<URL> urlList = new HashList<URL>(); + + if (arrayURL.length == 1) { + URL jarURL = arrayURL[0]; + if (isJar(jarURL.toString())) { + // jar invocation + try { + arrayURL = getClassPathURLsFromJarManifest(jarURL); + } catch (Exception e) { + log.warn(e); + arrayURL = new URL[]{jarURL}; + } + } + } + if (log.isDebugEnabled()) { + for (URL url : arrayURL) { + log.debug("found url " + url); + } + } + + for (URL urlFile : arrayURL) { + String fileName = urlFile.getFile(); + // TODO deal with encoding in windows, this is very durty, but it + // works... + File file = new File(fileName.replaceAll("%20", " ")); + if (!file.exists()) { + // this case should not appear + continue; + } + if (isJar(fileName)) { + // cas ou le ichier du classLoader est un fichier jar + if (log.isDebugEnabled()) { + log.debug("jar to search " + file); + } + urlList.addAll(Resource.getURLsFromJar(file, pattern)); + continue; + } + if (file.isDirectory()) { + // cas ou le ichier du classLoader est un repertoire + if (log.isDebugEnabled()) { + log.debug("directory to search " + file); + } + // on traite le cas ou il peut y avoir des repertoire dans ce + // repertoire + urlList.addAll(Resource.getURLsFromDirectory(file, pattern)); + continue; + } + + if (isZip(fileName)) { + // cas ou le ichier du classLoader est un fichier zip + if (log.isDebugEnabled()) { + log.debug("zip to search " + file); + } + urlList.addAll(Resource.getURLsFromZip(file, pattern)); + } + + } + if (log.isInfoEnabled()) { + log.info("search URLs pattern: " + pattern + " in " + + arrayURL.length + " urls in " + + StringUtil.convertTime(System.nanoTime() - t0)); + } + return urlList; + } + + static public URL[] getClassPathURLsFromJarManifest(URL jarURL) + throws IOException, URISyntaxException { + JarFile jar = null; + URL[] result; + try { + String jarPath = jarURL.toURI().getPath(); + File jarFile = new File(jarPath); + if (log.isDebugEnabled()) { + log.debug("class-path jar to scan " + jarPath); + } + jar = new JarFile(jarFile); + File container = jarFile.getParentFile(); + Manifest mf = jar.getManifest(); + String classPath = null; + if (mf != null && mf.getMainAttributes() != null) { + classPath = mf.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); + } + String[] paths; + if (classPath != null) { + paths = classPath.split(" "); + } else { + paths = new String[0]; + } + result = new URL[paths.length + 1]; + result[0] = jarURL; + File path; + for (int i = 0; i < paths.length; i++) { + String s = paths[i]; + // test de l'existence d'un protocole dans le path (genre file:...) + if (s.indexOf(':') != -1) { + result[i + 1] = new URL(s); + continue; + } + + if (s.startsWith(".") || !s.startsWith("/")) { + // relative url + path = new File(container, s); + } else { + path = new File(s); + } + if (log.isDebugEnabled()) { + log.debug(path); + } + result[i + 1] = path.toURI().toURL(); + } + jar.close(); + } finally { + if (jar != null) { + jar.close(); + } + } + return result; + } + + static public List<URL> getURLsFromZip(File zipFile, String pattern) { + try { + if (log.isTraceEnabled()) { + log.trace("search '" + pattern + "' in " + zipFile); + } + + ArrayList<URL> result = new ArrayList<URL>(); + InputStream in = new FileInputStream(zipFile); + ZipInputStream zis = new ZipInputStream(in); + while (zis.available() != 0) { + ZipEntry entry = zis.getNextEntry(); + + if (entry == null) { + break; + } + + String name = entry.getName(); + if (log.isTraceEnabled()) { + log.trace("zipFile: " + zipFile + " name: " + name); + } + if (pattern == null || name.matches(pattern)) { + // on recupere le fichier correspondant au pattern dans le + // classloader + URL url = Resource.getURL(name); + // on ajoute le fichier correspondant au pattern dans la + // liste + if (log.isTraceEnabled()) { + log.trace("zipFile: " + zipFile + " url: " + url); + } + result.add(url); + } + } + if (log.isTraceEnabled()) { + log.trace("found with pattern '" + pattern + "' : " + result); + } + return result; + } catch (IOException eee) { + throw new ResourceException(_("lutinutil.error.get.url.from.zip", zipFile.getAbsolutePath(), eee.getMessage())); + } + } + + static public List<URL> getURLsFromJar(File jarfile, String pattern) { + try { + if (log.isTraceEnabled()) { + log.trace("search '" + pattern + "' in " + jarfile); + } + + ArrayList<URL> result = new ArrayList<URL>(); + InputStream in = new FileInputStream(jarfile); + ZipInputStream zis = new ZipInputStream(in); + while (zis.available() != 0) { + ZipEntry entry = zis.getNextEntry(); + + if (entry == null) { + break; + } + + String name = entry.getName(); + if (log.isTraceEnabled()) { + log.trace("jarfile: " + jarfile + " name: " + name); + } + if (pattern == null || name.matches(pattern)) { + // on recupere le fichier correspondant au pattern dans le + // classloader + URL url = Resource.getURL(name); + // on ajoute le fichier correspondant au pattern dans la + // liste + if (log.isTraceEnabled()) { + log.trace("jarfile: " + jarfile + " url: " + url); + } + result.add(url); + } + } + if (log.isTraceEnabled()) { + log.trace("found with pattern '" + pattern + "' : " + result); + } + return result; + } catch (IOException eee) { + throw new ResourceException(_("lutinutil.error.get.url.from.zip", jarfile.getAbsolutePath(), eee.getMessage())); + } + } + + /** + * Retourne la liste des fichiers correspondant au pattern donne, aucun + * ordre ne doit être supposé sur les fichiers. + * + * @param repository repertoire dans lequel on recherche les fichiers + * @param pattern le nom du fichier a extraire du fichier du repertoire doit + * correspondre au pattern (repertoire + nom compris). si le + * pattern est null, tous les fichiers trouvé sont retourné. + * @return la liste des urls correspondant au pattern + */ + static public List<URL> getURLsFromDirectory(File repository, String pattern) { + try { + if (log.isTraceEnabled()) { + log.trace("search '" + pattern + "' in " + repository); + } + + HashList<URL> urlList = new HashList<URL>(); + File[] filesList = repository.listFiles(); + + if (filesList != null) { + + for (File file : filesList) { + + String name = file.getAbsolutePath(); + + if (log.isTraceEnabled()) { + log.trace("directory: " + repository + " name: " + + name); + } + + // cas de recursivite : repertoire dans un repertoire + if (file.exists() && file.isDirectory()) { + urlList.addAll(Resource.getURLsFromDirectory(file, + pattern)); + // si le fichier du repertoire n'est pas un repertoire + // on verifie s'il correspond au pattern + } else if (pattern == null || name.matches(pattern)) { + URL url = file.toURI().toURL(); + if (log.isTraceEnabled()) { + log.trace("directory: " + repository + " url: " + + url); + } + urlList.add(url); + } + } + } + if (log.isTraceEnabled()) { + log.trace("found with pattern '" + pattern + "' : " + urlList); + } + return urlList; + } catch (MalformedURLException eee) { + throw new ResourceException(_("lutinutil.error.convert.file.to.url", repository + " (pattern " + pattern + ") ", eee.getMessage())); + //throw new ResourceException("Le fichier n'a pu être converti en URL", eee); + } + } + + /** + * Verifie si le fichier est un fichier jar. + * + * @param name nom du fichier a tester + * @return vrai si le fichier se termine par .jar faux sinon + */ + static public boolean isJar(String name) { + if (name != null && name.length() > 4) { + String ext = name.substring(name.length() - 4, name.length()); + return ".jar".equalsIgnoreCase(ext); + } + return false; + } + + /** + * Verifie si le fichier est un fichier zip + * + * @param name nom du fichier a tester + * @return vrai si le fichier se termine par .zip faux sinon + */ + static public boolean isZip(String name) { + if (name != null && name.length() > 4) { + String ext = name.substring(name.length() - 4, name.length()); + return ".zip".equalsIgnoreCase(ext); + } + return false; + } + + /** + * Verifie si la classe est de type primitif. + * + * @param clazz nom de la classe a tester + * @return vrai si le classe est de type primitif faux sinon + */ + static public boolean isPrimitive(Class clazz) { + return clazz.isPrimitive() || clazz == Boolean.class + || clazz == Byte.class || clazz == Character.class + || clazz == Short.class || clazz == Integer.class + || clazz == Long.class || clazz == Float.class + || clazz == Double.class; + } + + /** + * Retourne la classe du type primitf associé avec la classe de de l'objet + * passé en parametre. Par exemple si la classe passée en paramètre est + * Integer alors le resultat sera la classe de int. + * + * @param clazz la classe dont on souhaite le type primitf + * @return le type primitif associé a la classe en paramètre, ou null s'il + * n'y a pas de type primitif associé. + */ + static public Class getPrimitiveClass(Class clazz) { + if (clazz == Boolean.class) { + return Boolean.TYPE; + } + if (clazz == Byte.class) { + return Byte.TYPE; + } + if (clazz == Character.class) { + return Character.TYPE; + } + if (clazz == Short.class) { + return Short.TYPE; + } + if (clazz == Integer.class) { + return Integer.TYPE; + } + if (clazz == Long.class) { + return Long.TYPE; + } + if (clazz == Float.class) { + return Float.TYPE; + } + if (clazz == Double.class) { + return Double.TYPE; + } + if (clazz == Void.class) { + return Void.TYPE; + } + return null; + } + + + /** + * Test if an url contains the given directory with no recurse seeking. + * + * @param url the url to seek + * @param directory the directory to find + * @return <code>true</code> if directory was found, <code>false</code> otherwise. + * @throws java.io.IOException if any io pb + */ + public static boolean containsDirectDirectory(URL url, String directory) throws IOException { + String fileName = url.getFile(); + // TODO deal with encoding in windows, this is very durty, but it works... + File file = new File(fileName.replaceAll("%20", " ")); + if (!file.exists()) { + return false; + } + if (isJar(fileName) || isZip(fileName)) { + // cas ou le fichier du classLoader est un fichier jar ou zip + if (log.isTraceEnabled()) { + log.trace("zip to search " + file); + } + return new ZipFile(file).getEntry(directory + "/") != null; + } + if (file.isDirectory()) { + // cas ou le ichier du classLoader est un repertoire + if (log.isTraceEnabled()) { + log.trace("directory to search " + file); + } + return new File(file, directory).exists(); + } + + if (log.isWarnEnabled()) { + log.warn(_("lutinutil.error.unknown.url.type", url)); + } + return false; + } +} // Resource Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/Resource.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceException.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ResourceException.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceException.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceException.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,46 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * ResourceException.java + * + * Created: 6 nov. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +public class ResourceException extends RuntimeException { // ResourceException + + /** */ + private static final long serialVersionUID = -5490688835958083084L; + + public ResourceException(String msg) { + super(msg); + } + + public ResourceException(String msg, Throwable e) { + super(msg, e); + } + +} // ResourceException + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceException.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceNotFoundException.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ResourceNotFoundException.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceNotFoundException.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceNotFoundException.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,46 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/** + * ResourceNotFoundException.java + * + * Created: Sun Apr 14 2002 + * + * @author POUSSIN Benjamin <bpoussin@free.fr> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +public class ResourceNotFoundException extends ResourceException { // ResourceNotFoundException + + /** */ + private static final long serialVersionUID = 623160949107461992L; + + public ResourceNotFoundException(String msg) { + super(msg); + } + + public ResourceNotFoundException(String msg, Throwable e) { + super(msg, e); + } + +} // ResourceNotFoundException Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ResourceNotFoundException.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/SimplePaginationEnum.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/SimplePaginationEnum.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/SimplePaginationEnum.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/SimplePaginationEnum.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,47 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +/** + * Une enumration pour definir les tailles de liste + * + * @author chemit + */ +public enum SimplePaginationEnum { + _5, + _10, + _20, + _50, + _100; + + int intValue; + + SimplePaginationEnum() { + intValue = Integer.valueOf(toString()); + } + + @Override + public String toString() { + return super.toString().substring(1); + } + + public int intValue() { + return intValue; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/SimplePaginationEnum.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/SortedProperties.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/SortedProperties.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/SortedProperties.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/SortedProperties.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,60 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +package org.nuiton.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: nuitonutil/trunk/src/main/java/org/nuiton/util/SortedProperties.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/StreamKeywordTokenizer.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/StreamKeywordTokenizer.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/StreamKeywordTokenizer.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/StreamKeywordTokenizer.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,88 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * StreamKeywordTokenizer.java + * + * Created: 27 mai 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import java.io.StreamTokenizer; +import java.util.HashSet; +import java.io.IOException; +import java.io.Reader; + +public class StreamKeywordTokenizer extends StreamTokenizer { // StreamKeywordTokenizer + + public static final int TT_KEYWORD = -101; + public static final int TT_VARIABLE = -102; + protected HashSet<String> keywords = new HashSet<String>(); + protected boolean lowerCaseKeyword = false; + protected int quoteCharVariable = -1; + + public StreamKeywordTokenizer(Reader in){ + super(in); + } + + public int nextToken() throws IOException { + super.nextToken(); + if(ttype == TT_WORD){ + String keyword = sval; + if(lowerCaseKeyword){ + keyword = keyword.toLowerCase(); + } + if(keywords.contains(keyword)){ + sval = keyword; + ttype = TT_KEYWORD; + } + }else if(ttype == quoteCharVariable){ + ttype = TT_VARIABLE; + } + return ttype; + } + + public void addKeyword(String keyword){ + if(lowerCaseKeyword){ + keywords.add(keyword.toLowerCase()); + }else{ + keywords.add(keyword); + } + } + + /** + * This method must be call before addKeyword. + */ + public void lowerCaseKeyword(boolean fl){ + lowerCaseKeyword = fl; + } + + public void quoteCharVariable(int c){ + quoteChar(c); + this.quoteCharVariable = c; + } + +} // StreamKeywordTokenizer + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/StreamKeywordTokenizer.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/StringUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,576 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +/* * + * StringUtil.java + * + * Created: Sun Apr 14 2002 + * + * @author POUSSIN Benjamin <bpoussin@free.fr> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +package org.nuiton.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"}; + + /** + * @param value + * @return the memory representation of the given value + * @see #convert(long, double[], String[]) + */ + static public String convertTime(long value) { + return convert(value, timeFactors, timeUnites); + } + + /** + * @param value + * @param value2 + * @return the time representation of the given value + * @see #convert(long, double[], String[]) + */ + 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"}; + + /** + * @param value + * @return the memory representation of the given value + * @see #convert(long, double[], String[]) + */ + static public String convertMemory(long value) { + return convert(value, memoryFactors, memoryUnites); + } + + /** + * Note: this method use the current locale (the {@link java.util.Locale#getDefault()}) in + * the method {@link MessageFormat#MessageFormat(String)}. + * + * @param value + * @param factors + * @param unites + * @return the converted representation of the given 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; + } + + /** + * 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: nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtilException.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/StringUtilException.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtilException.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtilException.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,33 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +package org.nuiton.util; + +/** + * @author pineau + */ +public class StringUtilException extends RuntimeException { + + /** */ + private static final long serialVersionUID = 6148795384335489591L; + + public StringUtilException(String message, Exception e) { + super(message, e); + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/StringUtilException.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/Tbz2Util.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/Tbz2Util.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/Tbz2Util.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/Tbz2Util.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,332 @@ +/* *##% Lutin utilities library + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +package org.nuiton.util; + +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.OutputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.apache.commons.compress.archivers.ArchiveEntry; +import org.apache.commons.compress.archivers.ArchiveException; +import org.apache.commons.compress.archivers.ArchiveInputStream; +import org.apache.commons.compress.archivers.ArchiveStreamFactory; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.apache.commons.compress.compressors.CompressorException; +import org.apache.commons.compress.compressors.CompressorInputStream; +import org.apache.commons.compress.compressors.CompressorStreamFactory; +import org.apache.commons.compress.utils.IOUtils; +import org.apache.commons.logging.LogFactory; + +/** + * Utility class for tar.bzip2 compression and md5 creation. + * + * @author chatellier + * @version $Revision: 1456 $ + * + * Last update: $Date: 2009-04-30 14:26:16 +0200 (jeu. 30 avril 2009) $ + * by : $Author: chatellier $ + * + * @since 1.0.5 + */ +public class Tbz2Util { + + /** Class logger. */ + private static org.apache.commons.logging.Log log = LogFactory + .getLog(Tbz2Util.class); + + /** Le séparateur de fichier en local. */ + private static final String LOCAL_SEP = File.separator; + + private static final String LOCAL_SEP_PATTERN = "\\".equals(LOCAL_SEP) ? LOCAL_SEP + + LOCAL_SEP + : LOCAL_SEP; + + /** Le séparateur zip. */ + private static final String TBZ2_SEP = "/"; + + private static final String TBZ2_SEP_PATTERN = "/"; + + /** Accept all file pattern. */ + protected static FileFilter ALL_FILE_FILTER = new FileFilter() { + public boolean accept(File pathname) { + return true; + } + }; + + /** + * Uncompress tbz2 file in targetDir. + * + * @param tbz2File the tbz2 source file + * @param targetDir the destination directory + * @return return last entry name + * @throws IOException if any problem while uncompressing + */ + public static String uncompress(File tbz2File, File targetDir) + throws IOException { + String result = uncompressAndRename(tbz2File, targetDir, null, null); + return result; + } + + /** + * Uncompress tbz2 file in targetDir, and rename uncompressed file if + * necessary. If renameFrom or renameTo is null no renaming is done + * <p/> + * file in tbz2 use / to separate directory and not begin with / + * each directory ended with / + * + * @param tbz2File the tbz2 source file + * @param targetDir the destination directory + * @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 + * @return return last entry name + * @throws IOException if any problem while uncompressing + */ + public static String uncompressAndRename(File tbz2File, File targetDir, + String renameFrom, String renameTo) throws IOException { + String result = null; + try { + InputStream is = new FileInputStream(tbz2File); + CompressorInputStream cis = new CompressorStreamFactory() + .createCompressorInputStream("bzip2", is); + ArchiveInputStream in = new ArchiveStreamFactory() + .createArchiveInputStream("tar", cis); + TarArchiveEntry entry; + while ((entry = (TarArchiveEntry) in.getNextEntry()) != null) { + String name = entry.getName(); + if (renameFrom != null && renameTo != null) { + name = name.replaceAll(renameFrom, renameTo); + if (log.isDebugEnabled()) { + log.debug("rename " + entry.getName() + " -> " + name); + } + } + result = name; + File target = new File(targetDir, name); + if (entry.isDirectory()) { + target.mkdirs(); + } else { + target.getParentFile().mkdirs(); + OutputStream out = new FileOutputStream(target); + try { + IOUtils.copy(in, out); + } finally { + out.close(); + } + } + } + in.close(); + } catch (CompressorException e) { + throw new IOException("Compression exception (not a bzip2 file ?)", + e); + } catch (ArchiveException e) { + throw new IOException("Archive exception (not a tar file ?)", e); + } + return result; + } + + /** + * Compress 'includes' files in tbz2 file. If file in includes is directory + * only the directory is put in tbz2 file, not the file contained in directory + * + * @param tbz2File the destination tbz2 file + * @param root for all file in includes that is in this directory, then we + * remove this directory in tar entry name (aka -C for tar), can be null; + * @param includes the files to include in tbz2File + * @throws IOException if any problem while compressing + */ + public static void compressFiles(File tbz2File, File root, + Collection<File> includes) throws IOException { + compressFiles(tbz2File, root, includes, false); + } + + /** + * Compress 'includes' files in tbz2. If file in includes is directory + * only the directory is put in tbz2, not the file contained in directory + * + * @param tbz2File the destination tbz2 file + * @param root for all file in includes that is in this directory, then we + * remove this directory in tar entry name (aka -C for tar), can be null; + * @param includes the files to include in tbz2File + * @param createMD5 also create a MD5 file (tbz2 name + .md5). MD5 file is created after tbz2File. + * @throws IOException if any problem while compressing + */ + public static void compressFiles(File tbz2File, File root, + Collection<File> includes, boolean createMD5) throws IOException { + OutputStream tbz2os = new FileOutputStream(tbz2File); + + try { + + // if md5 creation flag + if (createMD5) { + tbz2os = new MD5OutputStream(tbz2os); + } + + OutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", tbz2os); + + TarArchiveOutputStream os = (TarArchiveOutputStream)new ArchiveStreamFactory() + .createArchiveOutputStream("tar", cos); + // fix error file name 'xxx' is too long ( > 100 bytes) + os.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); + + for (File file : includes) { + if (file.isFile() && file.canRead()) { + String entryName = toArchiveEntryName(root, file); + ArchiveEntry entry = os.createArchiveEntry(file, entryName); + os.putArchiveEntry(entry); + InputStream is = new FileInputStream(file); + try { + IOUtils.copy(is, os); + } finally { + is.close(); + } + os.closeArchiveEntry(); + } + + } + os.finish(); + os.close(); + cos.close(); + + // if md5 creation flag + if (createMD5) { + String md5hash = MD5.asHex(((MD5OutputStream) tbz2os).hash()); + File md5File = new File(tbz2File.getAbsoluteFile() + ".md5"); + FileUtil.writeString(md5File, md5hash); + } + + } catch (ArchiveException e) { + throw new IOException("Can't archive as tar", e); + } catch (CompressorException e) { + throw new IOException("Can't compress as bzip2", e); + } + finally { + tbz2os.close(); + } + } + + /** + * If fileOrDirectory is directory Compress recursively all file in this + * directory, else if is just file compress one file. + * <p/> + * Entry result name in tbz2 start at fileOrDirectory. + * example: if we compress /etc/apache, entry will be apache/http.conf, ... + * + * @param tbz2File the source tbz2 file + * @param fileOrDirectory the file or directory to compress + * @throws IOException if any problem while compressing + */ + public static void compress(File tbz2File, File fileOrDirectory) + throws IOException { + compress(tbz2File, fileOrDirectory, null, false); + } + + /** + * If fileOrDirectory is directory Compress recursively all file in this + * directory, else if is just file compress one file. + * <p/> + * Entry result name in tbz2 start at fileOrDirectory. + * example: if we compress /etc/apache, entry will be apache/http.conf, ... + * + * @param tbz2File the source tbz2 file + * @param fileOrDirectory the file or directory to compress + * @param filter used to accept file, if null, all file is accepted + * @throws IOException if any problem while compressing + */ + public static void compress(File tbz2File, File fileOrDirectory, + FileFilter filter) throws IOException { + compress(tbz2File, fileOrDirectory, filter, false); + } + + /** + * If fileOrDirectory is directory Compress recursively all file in this + * directory, else if is just file compress one file. + * <p/> + * Entry result name in tbz2 start at fileOrDirectory. + * example: if we compress /etc/apache, entry will be apache/http.conf, ... + * + * @param tbz2File the source tbz2 file + * @param fileOrDirectory the file or directory to compress + * @param filter used to accept file, if null, all file is accepted + * @param createMD5 also create a MD5 file (zip name + .md5). MD5 file is created after zip. + * @throws IOException if any problem while compressing + */ + public static void compress(File tbz2File, File fileOrDirectory, + FileFilter filter, boolean createMD5) throws IOException { + FileFilter localFilter = filter; + if (localFilter == null) { + localFilter = ALL_FILE_FILTER; + } + List<File> files = new ArrayList<File>(); + if (fileOrDirectory.isDirectory()) { + files = FileUtil.getFilteredElements(fileOrDirectory, localFilter, + true); + } else if (localFilter.accept(fileOrDirectory)) { + files.add(fileOrDirectory); + } + + compressFiles(tbz2File, fileOrDirectory.getParentFile(), files, + createMD5); + } + + /** + * <li> supprime le root du fichier + * <li> Converti les '\' en '/' car les archives entry utilise des '/' + * <li> ajoute un '/' a la fin pour les repertoires + * <li> supprime le premier '/' si la chaine commence par un '/' + * + * @param root the root directory + * @param file the file to treate + * @return the archive entry name corresponding to the given <code>file</code> + * from <code>root</code> dir. + */ + protected static String toArchiveEntryName(File root, File file) { + String result = file.getPath(); + + if (root != null) { + String rootPath = root.getPath(); + if (result.startsWith(rootPath)) { + result = result.substring(rootPath.length()); + } + } + + result = result.replace('\\', '/'); + if (file.isDirectory()) { + result += '/'; + } + while (result.startsWith("/")) { + result = result.substring(1); + } + return result; + } + + protected static String convertToLocalEntryName(String txt) { + String s = txt.replaceAll(TBZ2_SEP_PATTERN, LOCAL_SEP_PATTERN); + if (s.endsWith(TBZ2_SEP)) { + s = s.substring(0, s.length() - 1); + } + return s; + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/Tbz2Util.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/TransformedList.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/TransformedList.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/TransformedList.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/TransformedList.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,105 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * TransformedList.java + * + * Created: 2 août 2005 02:12:42 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.Serializable; +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +public class TransformedList<E> extends AbstractList<E> implements Serializable { // TransformedList + + /** */ + private static final long serialVersionUID = 2354881761407900789L; + + protected Transformer<E, Object> transformer = null; + protected List<Object> inner = null; + + public TransformedList(Transformer<E, Object> transformer) { + if (transformer == null) { + throw new IllegalArgumentException("Transformer must not be null"); + } else { + this.transformer = transformer; + this.inner = new ArrayList<Object>(); + } + } + + public TransformedList(Transformer<E, Object> transformer, Collection<? extends E> c) { + this(transformer); + addAll(c); + } + + public int size() { + return inner.size(); + } + + public E get(int index) { + Object f = inner.get(index); + E result = transformer.untransform(f); + return result; + } + + public E set(int index, E element) { + Object f = transformer.transform(element); + f = inner.set(index, f); + E result = transformer.untransform(f); + return result; + } + + public void add(int index, E element) { + Object f = transformer.transform(element); + inner.add(index, f); + } + + public E remove(int index) { + Object f = inner.remove(index); + E result = transformer.untransform(f); + return result; + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + out.writeObject(transformer); + out.writeObject(inner); + } + + @SuppressWarnings("unchecked") + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + transformer = (Transformer<E, Object>) in.readObject(); + inner = (List<Object>) in.readObject(); + } + +} // TransformedList + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/TransformedList.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/Transformer.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/Transformer.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/Transformer.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/Transformer.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,42 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * Transformer.java + * + * Created: 2 août 2005 02:55:41 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import java.io.Serializable; + +/** Permet de transformer un objet en un autre et inversement */ +public interface Transformer<E, F> extends Serializable { // Transformer + + public F transform(E e); + + public E untransform(F f); + +} // Transformer + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/Transformer.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteSoftReference.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/TransparenteSoftReference.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteSoftReference.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteSoftReference.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,126 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +/* * +* TransparenteSoftReference.java +* +* Created: 10 mai 2004 +* +* @author Benjamin Poussin <poussin@codelutin.com> +* Copyright Code Lutin +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ +package org.nuiton.util; + +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.SoftReference; + +/** + * Cette classe etant SoftReference et surcharge les méthodes equals et + * hashCode pour que ces méthodes retournes les mêmes résultat que les objets + * contenu. + */ +public class TransparenteSoftReference<T> extends SoftReference<T> { + + protected int hash = 0; + protected String toString = null; + + /** + * DOCUMENTME Constructor for the TransparenteSoftReference object + * + * @param o DOCUMENTME Description of the Parameter + */ + public TransparenteSoftReference(T o) { + this(o, true); + } + + public TransparenteSoftReference(T o, ReferenceQueue<? super T> queue) { + this(o, queue, true); + } + + public TransparenteSoftReference(T o, boolean objectToStringUsed) { + super(o); + init(o, objectToStringUsed); + } + + public TransparenteSoftReference(T o, ReferenceQueue<? super T> queue, boolean objectToStringUsed) { + super(o, queue); + init(o, objectToStringUsed); + } + + /** + * On conserve le hash pour que la Reference puisse encore se faire + * passer pour l'objet alors que celui-ci a disparu de la memoire + */ + protected void init(T o, boolean objectToStringUsed) { + if (o == null) { + hash = 0; + } else { + hash = o.hashCode(); + if (objectToStringUsed) { + toString = o.toString(); + } + if (toString == null) { + toString = o.getClass().getName() + '@' + Integer.toHexString(hash); + } + if (toString.length() > 100) { + toString = toString.substring(0, 100) + "..."; + } + } + } + + /** + * DOCUMENTME Method + * + * @param o DOCUMENTME Description of the Parameter + * @return DOCUMENTME Description of the Return Value + */ + public boolean equals(Object o) { + if (o == this) { + return true; + } + // on travail avec un variable local pour ne pas etre obligé de + // synchroniser la méthode + Object local = get(); + if (o instanceof Reference) { + o = ((Reference) o).get(); + } + + boolean result = + (o == null && local == null) + || (o != null && o.equals(local)); + + return result; + } + + /** + * DOCUMENTME Method + * + * @return DOCUMENTME Description of the Return Value + */ + public int hashCode() { + return hash; + } + + public String toString() { + return toString; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteSoftReference.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteWeakReference.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/TransparenteWeakReference.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteWeakReference.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteWeakReference.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,119 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +/* * +* TransparenteWeakReference.java +* +* Created: 10 mai 2004 +* +* @author Benjamin Poussin <poussin@codelutin.com> +* Copyright Code Lutin +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ +package org.nuiton.util; + +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; +import java.lang.ref.WeakReference; + +/** + * Cette classe etant WeakReference et surcharge les méthodes equals et + * hashCode pour que ces méthodes retournes les mêmes résultat que les objets + * contenu. + */ +public class TransparenteWeakReference<T> extends WeakReference<T> { + + protected int hash = 0; + protected String toString = null; + protected boolean objectToStringUsed = true; + + public TransparenteWeakReference(T o) { + this(o, true); + } + + public TransparenteWeakReference(T o, ReferenceQueue<? super T> queue) { + this(o, queue, true); + } + + /** + * @param objectToStringUsed if true, this ref used toString method of + * encapsulated object otherwize used default Object toString + */ + public TransparenteWeakReference(T o, boolean objectToStringUsed) { + super(o); + init(o, objectToStringUsed); + } + + public TransparenteWeakReference(T o, ReferenceQueue<? super T> queue, boolean objectToStringUsed) { + super(o, queue); + init(o, objectToStringUsed); + } + + /** + * On conserve le hash pour que la Reference puisse encore se faire + * passer pour l'objet alors que celui-ci a disparu de la memoire + */ + protected void init(T o, boolean objectToStringUsed) { + if (o == null) { + hash = 0; + } else { + hash = o.hashCode(); + if (objectToStringUsed) { + toString = o.toString(); + } + if (toString == null) { + toString = o.getClass().getName() + '@' + Integer.toHexString(hash); + } + if (toString.length() > 100) { + toString = toString.substring(0, 100) + "..."; + } + } + } + + /** Equals si meme reference memoire on les objets references sont egauxs */ + public boolean equals(Object o) { + if (o == this) { + return true; + } + // on travail avec un variable local pour ne pas etre obligé de + // synchroniser la méthode + Object local = get(); + Object other = o; + if (o instanceof Reference) { + other = ((Reference) o).get(); + + if (other == null) { + // on fait l'egalite sur les hash car on a perdu les objets + return o.hashCode() == hashCode(); + } + } + + return (other == null && local == null) || + (other != null && other.equals(local)); + } + + public int hashCode() { + return hash; + } + + public String toString() { + return toString; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/TransparenteWeakReference.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/URIConverter.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/URIConverter.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/URIConverter.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/URIConverter.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,76 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +package org.nuiton.util; + +import org.apache.commons.beanutils.ConversionException; +import org.apache.commons.beanutils.Converter; +import static org.apache.commons.logging.LogFactory.getLog; +import static org.nuiton.i18n.I18n._; + +import java.net.URI; +import java.net.URISyntaxException; + +/** + * classe pour convertir une chaine en un objet URI. + * + * @author chemit + */ +public class URIConverter implements Converter { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static org.apache.commons.logging.Log log = getLog(URIConverter.class); + + public Object convert(Class aClass, Object value) { + if (value == null) { + throw new ConversionException(_("lutinutil.error.convertor.noValue", this)); + } + if (isEnabled(aClass)) { + Object result; + if (isEnabled(value.getClass())) { + result = value; + return result; + } + if (value instanceof String) { + result = valueOf((String) value); + return result; + } + } + throw new ConversionException(_("lutinutil.error.no.convertor", aClass.getName(), value)); + } + + protected URI valueOf(String value) { + try { + URI result; + result = new URI(value); + return result; + } catch (URISyntaxException e) { + throw new ConversionException(_("lutinutil.error.url.convertor", value, this, e.getMessage())); + } + } + + public URIConverter() { + if (log.isDebugEnabled()) { + log.debug(this); + } + } + + protected boolean isEnabled(Class aClass) { + return aClass == URI.class; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/URIConverter.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/URLConverter.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/URLConverter.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/URLConverter.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/URLConverter.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,75 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import org.apache.commons.beanutils.ConversionException; +import org.apache.commons.beanutils.Converter; +import static org.apache.commons.logging.LogFactory.getLog; +import static org.nuiton.i18n.I18n._; + +import java.net.MalformedURLException; +import java.net.URL; + +/** + * classe pour convertir une chaine en un objet URL. + * + * @author chemit + */ + +public class URLConverter implements Converter { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static org.apache.commons.logging.Log log = getLog(URLConverter.class); + + public Object convert(Class aClass, Object value) { + if (value == null) { + throw new ConversionException(_("lutinutil.error.convertor.noValue", this)); + } + if (isEnabled(aClass)) { + Object result; + if (isEnabled(value.getClass())) { + result = value; + return result; + } + if (value instanceof String) { + result = valueOf((String) value); + return result; + } + } + throw new ConversionException(_("lutinutil.error.no.convertor", aClass.getName(), value)); + } + + protected URL valueOf(String value) { + try { + URL result; + result = new URL(value); + return result; + } catch (MalformedURLException e) { + throw new ConversionException(_("lutinutil.error.url.convertor", value, this, e.getMessage())); + } + } + + public URLConverter() { + log.info(this); + } + + protected boolean isEnabled(Class aClass) { + return aClass == URL.class; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/URLConverter.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumber.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/VersionNumber.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumber.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumber.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,85 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import java.util.Arrays; + +/** + * A class to represent an application version + * + * @author chemit + */ +public class VersionNumber implements Comparable<VersionNumber> { + protected int[] numbers; + + public VersionNumber() { + this.numbers = new int[]{0}; + } + + public VersionNumber(int... numbers) { + this.numbers = numbers; + } + + public int[] getNumbers() { + return numbers; + } + + public int getNumber(int level) { + if (level<0 || level>=numbers.length) { + throw new IllegalArgumentException("not a valid level "+level+ " for the VersionNumber "+this); + } + return numbers[level]; + } + + public int getNbComponents() { + return numbers.length; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + for (int number : numbers) { + sb.append('.').append(number); + } + return sb.toString().substring(1); + } + + public int compareTo(VersionNumber o) { + String str = toString(); + String ostr = o.toString(); + if (str.equals(ostr)) { + return 0; + } + return VersionNumberUtil.greaterThan(str, ostr) ? 1 : -1; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof VersionNumber)) return false; + + VersionNumber that = (VersionNumber) o; + return Arrays.equals(numbers, that.numbers); + + } + + @Override + public int hashCode() { + return Arrays.hashCode(numbers); + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumber.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberConverter.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/VersionNumberConverter.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberConverter.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberConverter.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,84 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import org.apache.commons.beanutils.ConversionException; +import org.apache.commons.beanutils.Converter; +import static org.apache.commons.logging.LogFactory.getLog; +import static org.nuiton.i18n.I18n._; + +/** + * classe pour convertir une chaine en un objet VersionNumber. + * + * @author chemit + * @see VersionNumber + */ + +public class VersionNumberConverter implements Converter { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static org.apache.commons.logging.Log log = getLog(VersionNumberConverter.class); + + public Object convert(Class aClass, Object value) { + if (value == null) { + throw new ConversionException(_("lutinutil.error.convertor.noValue", this)); + } + if (isEnabled(aClass)) { + Object result; + if (isEnabled(value.getClass())) { + result = value; + return result; + } + if (value instanceof String) { + result = valueOf((String) value); + return result; + } + } + throw new ConversionException(_("lutinutil.error.no.convertor", aClass.getName(), value)); + } + + public VersionNumberConverter() { + if (log.isDebugEnabled()) { + log.debug(this); + } + } + + protected VersionNumber valueOf(String value) { + try { + VersionNumber result; + String[] str = value.split("\\."); + if (str.length == 0) { + return new VersionNumber(); + } + int[] numbers = new int[str.length]; + for (int i = 0; i < str.length; i++) { + String number = str[i]; + numbers[i] = Integer.valueOf(number); + } + result = new VersionNumber(numbers); + return result; + } catch (IllegalArgumentException e) { + throw new ConversionException(_("lutinutil.error.url.convertor", value, this, e.getMessage())); + } + } + + protected boolean isEnabled(Class aClass) { + return aClass == VersionNumber.class; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberConverter.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/VersionNumberUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,99 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * NumberVersionUtil.java + * + * Created: 4 déc. 2003 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +public class VersionNumberUtil { // VersionNumberUtil + + protected static String normalize(String version) { + if (version == null) { + version = "0"; + } + return version; + } + + public static boolean greaterThan(String v1, String v2) { + String[] v1s = normalize(v1).split("\\."); + String[] v2s = normalize(v2).split("\\."); + int minlen = Math.min(v1s.length, v2s.length); + for (int i = 0; i < minlen; i++) { + if (!v1s[i].equals(v2s[i])) + return Integer.parseInt(v1s[i]) > Integer.parseInt(v2s[i]); + } + // si on est ici c que tout les nombres sont v1[i] = v2[i] + return v1s.length > v2s.length; + } + + /** + * Regarde l'egalité entre 2 numeros de version + * 1.2.0 et 1.2 ne sont pas egaux + */ + public static boolean equals(String v1, String v2) { + return normalize(v1).equals(normalize(v2)); + } + + public static boolean smallerThan(String v1, String v2) { + String[] v1s = normalize(v1).split("\\."); + String[] v2s = normalize(v2).split("\\."); + int minlen = Math.min(v1s.length, v2s.length); + for (int i = 0; i < minlen; i++) { + if (!v1s[i].equals(v2s[i])) + return Integer.parseInt(v1s[i]) < Integer.parseInt(v2s[i]); + } + // si on est ici c que tout les nombres sont v1[i] = v2[i] + return v1s.length < v2s.length; + } + + /** + * Incremente le numero de version, seul le dernier constituant est + * incremente: 1.2.3.4 -> 1.2.3.5; null -> 1; 0 -> 1 + */ + public static String inc(String v) { + if (v == null) { + return "1"; + } else { + v = v.trim(); + } + + String result = null; + int i = v.lastIndexOf('.'); + if (i == -1) { + int n = Integer.parseInt(v) + 1; + result = "" + n; + } else { + String num = v.substring(i + 1); + int n = Integer.parseInt(num) + 1; + result = v.substring(0, i + 1) + n; + } + return result; + } + +} // VersionNumberUtil + Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/VersionNumberUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ZipStreamEncoder.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ZipStreamEncoder.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ZipStreamEncoder.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ZipStreamEncoder.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,97 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Map; +import java.util.zip.Deflater; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +import org.apache.commons.logging.LogFactory; + +/** + * The Class ZipStreamEncoder. + */ +public class ZipStreamEncoder extends Thread { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private org.apache.commons.logging.Log log = LogFactory.getLog(ZipStreamEncoder.class); + + /** The Constant BUFFER. */ + static final int BUFFER = 2048; + + /** The files. */ + private Map<String, InputStream> files; + + /** The zos. */ + private ZipOutputStream zos; + + /** + * Instantiates a new zip stream encoder. + * + * @param files + * the files + * @param os + * the os + */ + public ZipStreamEncoder(Map<String, InputStream> files, OutputStream os) { + super(); + this.files = files; + + zos = new ZipOutputStream(os); + zos.setMethod(ZipOutputStream.DEFLATED); + zos.setLevel(Deflater.BEST_COMPRESSION); + } + + /* (non-Javadoc) + * @see java.lang.Thread#run() + */ + @Override + public void run() { + byte data[] = new byte[BUFFER]; + try { + for (Map.Entry<String, InputStream> kv : files.entrySet()) { + ZipEntry entry = new ZipEntry(kv.getKey()); + InputStream origin = kv.getValue(); + zos.putNextEntry(entry); + int count; + while ((count = origin.read(data, 0, BUFFER)) != -1) { + zos.write(data, 0, count); + } + origin.close(); + } + + zos.close(); + } catch (IOException e) { + for (Map.Entry<String, InputStream> kv : files.entrySet()) { + InputStream origin = kv.getValue(); + try { + origin.close(); + } catch (IOException ioe) { + log.error("Impossible to close " + kv.getKey()); + } + } + log.error("Impossible to compress in stream"); + throw new RuntimeException("Impossible to compress in stream"); + } + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ZipStreamEncoder.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/ZipUtil.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/ZipUtil.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/ZipUtil.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/ZipUtil.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,445 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +package org.nuiton.util; + +import org.apache.commons.logging.LogFactory; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +/** + * ZipUtil.java + * + * Created: 24 août 2006 10:13:35 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ +public class ZipUtil { + + /** Class logger. */ + private static org.apache.commons.logging.Log log = LogFactory.getLog(ZipUtil.class); + + /** Taille du buffer pour les lectures/écritures. */ + private static final int BUFFER_SIZE = 8 * 1024; + + /** Le séparateur de fichier en local. */ + private static final String LOCAL_SEP = File.separator; + + private static final String LOCAL_SEP_PATTERN = "\\".equals(LOCAL_SEP) ? + LOCAL_SEP + LOCAL_SEP : LOCAL_SEP; + + /** Le séparateur zip. */ + private static final String ZIP_SEP = "/"; + + private static final String ZIP_SEP_PATTERN = "/"; + + /** Accept all file pattern. */ + protected static FileFilter ALL_FILE_FILTER = new FileFilter() { + public boolean accept(File pathname) { + return true; + } + }; + + /** + * Uncompress zipped file in targetDir. + * + * @param file the zip source file + * @param targetDir the destination directory + * @return return last entry name + * @throws IOException if any problem while uncompressing + */ + public static String uncompress(File file, File targetDir) throws IOException { + String result; + result = uncompressAndRename(file, targetDir, null, null); + return result; + } + + /** + * Uncompress zipped file in targetDir, and rename uncompressed file if + * necessary. If renameFrom or renameTo is null no renaming is done + * <p/> + * file in zip use / to separate directory and not begin with / + * each directory ended with / + * + * @param file the zip source file + * @param targetDir the destination directory + * @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 + * @return return last entry name + * @throws IOException if any problem while uncompressing + */ + public static String uncompressAndRename(File file, File targetDir, String renameFrom, String renameTo) throws IOException { + String result = ""; + ZipInputStream in = new ZipInputStream(new FileInputStream(file)); + ZipEntry entry; + while ((entry = in.getNextEntry()) != null) { + String name = entry.getName(); + if (renameFrom != null && renameTo != null) { + name = name.replaceAll(renameFrom, renameTo); + if (log.isDebugEnabled()) { + log.debug("rename " + entry.getName() + " -> " + name); + } + } + result = name; + File target = new File(targetDir, name); + if (entry.isDirectory()) { + target.mkdirs(); + } else { + target.getParentFile().mkdirs(); + OutputStream out = new BufferedOutputStream(new FileOutputStream(target)); + byte[] buffer = new byte[BUFFER_SIZE]; + int len; + while ((len = in.read(buffer, 0, BUFFER_SIZE)) != -1) { + out.write(buffer, 0, len); + } + out.close(); + } + } + in.close(); + return result; + } + + /** + * Compress 'includes' files in zipFile. If file in includes is directory + * only the directory is put in zipFile, not the file contained in directory + * + * @param zipFile the destination zip file + * @param root for all file in includes that is in this directory, then we + * remove this directory in zip entry name (aka -C for tar), can be null; + * @param includes the files to include in zip + * @throws java.io.IOException if any problem while compressing + */ + public static void compressFiles(File zipFile, File root, Collection<File> includes) throws IOException { + compressFiles(zipFile, root, includes, false); + } + + /** + * Compress 'includes' files in zipFile. If file in includes is directory + * only the directory is put in zipFile, not the file contained in directory + * + * @param zipFile the destination zip file + * @param root for all file in includes that is in this directory, then we + * remove this directory in zip entry name (aka -C for tar), can be null; + * @param includes the files to include in zip + * @param createMD5 also create a MD5 file (zip name + .md5). MD5 file is created after zip. + * @throws IOException if any problem while compressing + */ + public static void compressFiles(File zipFile, File root, Collection<File> includes, boolean createMD5) throws IOException { + OutputStream oStream = new FileOutputStream(zipFile); + + // if md5 creation flag + if (createMD5) { + oStream = new MD5OutputStream(oStream); + } + try { + ZipOutputStream zipOStream = new ZipOutputStream(oStream); + + for (File file : includes) { + String entryName = toZipEntryName(root, file); + + // Création d'une nouvelle entrée dans le zip + ZipEntry entry = new ZipEntry(entryName); + entry.setTime(file.lastModified()); + zipOStream.putNextEntry(entry); + + if (file.isFile() && file.canRead()) { + byte[] readBuffer = new byte[BUFFER_SIZE]; + int bytesIn; + BufferedInputStream bis = new BufferedInputStream( + new FileInputStream(file), BUFFER_SIZE); + while ((bytesIn = bis.read(readBuffer, 0, BUFFER_SIZE)) != -1) { + zipOStream.write(readBuffer, 0, bytesIn); + } + bis.close(); + } + zipOStream.closeEntry(); + } + zipOStream.close(); + + // if md5 creation flag + if (createMD5) { + String md5hash = MD5.asHex(((MD5OutputStream)oStream).hash()); + File md5File = new File(zipFile.getAbsoluteFile() + ".md5"); + FileUtil.writeString(md5File, md5hash); + } + } finally { + oStream.close(); + } + } + + /** + * If fileOrDirectory is directory Compress recursively all file in this + * directory, else if is just file compress one file. + * <p/> + * Entry result name in zip start at fileOrDirectory. + * example: if we compress /etc/apache, entry will be apache/http.conf, ... + * + * @param zipFile the source zip file + * @param fileOrDirectory the file or directory to compress + * @throws IOException if any problem while compressing + */ + public static void compress(File zipFile, File fileOrDirectory) throws IOException { + compress(zipFile, fileOrDirectory, null, false); + } + + /** + * If fileOrDirectory is directory Compress recursively all file in this + * directory, else if is just file compress one file. + * <p/> + * Entry result name in zip start at fileOrDirectory. + * example: if we compress /etc/apache, entry will be apache/http.conf, ... + * + * @param zipFile the source zip file + * @param fileOrDirectory the file or directory to compress + * @param filter used to accept file, if null, all file is accepted + * @throws IOException if any problem while compressing + */ + public static void compress(File zipFile, File fileOrDirectory, FileFilter filter) throws IOException { + compress(zipFile, fileOrDirectory, filter, false); + } + + /** + * If fileOrDirectory is directory Compress recursively all file in this + * directory, else if is just file compress one file. + * <p/> + * Entry result name in zip start at fileOrDirectory. + * example: if we compress /etc/apache, entry will be apache/http.conf, ... + * + * @param zipFile the source zip file + * @param fileOrDirectory the file or directory to compress + * @param filter used to accept file, if null, all file is accepted + * @param createMD5 also create a MD5 file (zip name + .md5). MD5 file is created after zip. + * @throws IOException if any problem while compressing + */ + public static void compress(File zipFile, File fileOrDirectory, FileFilter filter, boolean createMD5) throws IOException { + if (filter == null) { + filter = ALL_FILE_FILTER; + } + List<File> files = new ArrayList<File>(); + if (fileOrDirectory.isDirectory()) { + files = FileUtil.getFilteredElements(fileOrDirectory, filter, true); + } else if (filter.accept(fileOrDirectory)) { + files.add(fileOrDirectory); + } + + compressFiles(zipFile, fileOrDirectory.getParentFile(), files, createMD5); + } + + /** + * <li> supprime le root du fichier + * <li> Converti les '\' en '/' car les zip entry utilise des '/' + * <li> ajoute un '/' a la fin pour les repertoires + * <li> supprime le premier '/' si la chaine commence par un '/' + * + * @param root the root directory + * @param file the file to treate + * @return the zip entry name corresponding to the given <code>file</code> + * from <code>root</code> dir. + */ + private static String toZipEntryName(File root, File file) { + String result = file.getPath(); + + if (root != null) { + String rootPath = root.getPath(); + if (result.startsWith(rootPath)) { + result = result.substring(rootPath.length()); + } + } + + result = result.replace('\\', '/'); + if (file.isDirectory()) { + result += '/'; + } + while (result.startsWith("/")) { + result = result.substring(1); + } + return result; + } + + /** + * Scan a zipFile, and fill two lists of relative paths corresponding of + * zip entries. + * First list contains all entries to be added while a uncompress operation + * on the destination directory </code>targetDir</code>. + * Second list contains all entries to be overwritten while a uncompress + * operation on the destination directory <code>targetDir</code>. + * <br> + * If <code>targetDir</code> is <code>null</code> we don't fill + * <cide>existingFiles<code/> list. + * + * @param zipFile location of the zip to scanZip + * @param targetDir location of destination for a uncompress operation. + * If <code>null</code> we don't test to + * find overwritten files. + * @param newFiles list of files to be added while a uncompress + * @param existingFiles list of files to be overwritten while a uncompress + * if the <code>targetDir</code>, + * (only use if <code>targetDir</code> is not + * <code>null</code>) + * @param excludeFilter used to exclude some files + * @param renameFrom {@link #uncompressAndRename(java.io.File, java.io.File, String, String)} + * @param renameTo {@link #uncompressAndRename(java.io.File, java.io.File, String, String)} + * @throws IOException if any exception while dealing with zipfile + */ + public static void scan(File zipFile, File targetDir, List<String> newFiles, + List<String> existingFiles, FileFilter excludeFilter, String renameFrom, String renameTo) + throws IOException { + ZipFile zip = null; + try { + zip = new ZipFile(zipFile); + boolean findExisting = targetDir != null && targetDir.exists(); + boolean filter = findExisting && excludeFilter != null; + boolean rename = renameFrom != null && renameTo != null; + Enumeration<? extends ZipEntry> entries = zip.entries(); + while (entries.hasMoreElements()) { + String entryName = entries.nextElement().getName(); + if (rename) { + entryName = entryName.replaceAll(renameFrom, renameTo); + } + String name = convertToLocalEntryName(entryName); + if (findExisting || filter) { + File file = new File(targetDir, name); + if (filter && excludeFilter.accept(file)) continue; + if (file.exists()) { + existingFiles.add(name); + continue; + } + } + newFiles.add(name); + } + } finally { + if (zip != null) { + zip.close(); + } + } + } + + @SuppressWarnings({"unchecked"}) + public static List<String>[] scanAndExplodeZip(File source, File root, FileFilter excludeFilter) throws IOException { + + List<String> overwrittenFiles = new ArrayList<String>(); + List<String> newFiles = new ArrayList<String>(); + + // obtain list of relative paths (to add or overwrite) + scan(source, root, newFiles, overwrittenFiles, excludeFilter, null, null); + + return new List[]{newFiles, overwrittenFiles}; + } + + /** + * uncompress zipped file in targetDir. + * <p/> + * If <code>toTreate</code> if not null nor empty, we use it to filter + * entries to uncompress : it contains a list of relative local path of + * files to uncompress. + * Otherwise just delegate to {@link ZipUtil#uncompress(File,File)}. + * + * @param file location of zip file + * @param targetDir destination directory + * @param toTreate list of relative local path of entries to treate + * @param renameFrom {@link #uncompressAndRename(File, File, String, String)} + * @param renameTo {@link #uncompressAndRename(File, File, String, String)} + * @return return last entry name + * @throws IOException if nay exception while operation + */ + public static String uncompress(File file, File targetDir, List<String> toTreate, String renameFrom, String renameTo) throws IOException { + String result = ""; + ZipInputStream in = new ZipInputStream(new FileInputStream(file)); + ZipEntry entry; + if (toTreate == null || toTreate.isEmpty()) { + return ZipUtil.uncompressAndRename(file, targetDir, renameFrom, renameTo); + } + + boolean rename = renameFrom != null && renameTo != null; + + while ((entry = in.getNextEntry()) != null) { + String name = entry.getName(); + if (rename) { + result = convertToLocalEntryName(name.replaceAll(renameFrom, renameTo)); + } else { + result = convertToLocalEntryName(name); + } + + if (log.isDebugEnabled()) { + log.debug("open [" + name + "] : " + result); + } + if (!toTreate.contains(result)) { + continue; + } + + if (log.isDebugEnabled()) { + log.debug("copy [" + name + "] : " + result); + } + File target = new File(targetDir, result); + if (entry.isDirectory()) { + target.mkdirs(); + } else { + target.getParentFile().mkdirs(); + OutputStream out = + new BufferedOutputStream(new FileOutputStream(target)); + byte[] buffer = new byte[BUFFER_SIZE]; + int len; + while ((len = in.read(buffer, 0, BUFFER_SIZE)) != -1) { + out.write(buffer, 0, len); + } + out.close(); + } + } + in.close(); + return result; + } + + /** + * @deprecated unused/undocumented function + */ + public static String convertToZipEntryName(String txt, boolean isDir) { + String s = txt.replaceAll(LOCAL_SEP_PATTERN, ZIP_SEP); + while (s.startsWith(ZIP_SEP)) { + s = s.substring(1); + } + return s + (isDir ? ZIP_SEP : ""); + } + + + protected static String convertToLocalEntryName(String txt) { + String s = txt.replaceAll(ZIP_SEP_PATTERN, LOCAL_SEP_PATTERN); + if (s.endsWith(ZIP_SEP)) { + s = s.substring(0, s.length() - 1); + } + return s; + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/ZipUtil.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/config/Config.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/config/Config.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/config/Config.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/config/Config.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,50 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util.config; + +import java.util.EnumMap; +import java.util.EnumSet; + +/** + * config contract based on a Enum to obtain properties + * + * @author chemit + */ +public interface Config<E extends Enum<E>> { + + EnumMap<E, Object> getProperties(); + + Object getProperty(E key); + + EnumSet<E> getUniverse(); + + void setProperties(EnumMap<E, Object> properties); + + void setProperty(E key, Object value); + + void copyFrom(Object src); + + void copyFrom(Object src, EnumSet<E> keys); + + void copyTo(Object dst); + + void copyTo(Object dst, EnumSet<E> keys); + + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/config/Config.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfig.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/config/IdentityConfig.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfig.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfig.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,41 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util.config; + + +/** + * Definition of an identity + * + * @author chemit + */ +public interface IdentityConfig extends Config<IdentityConfigProperty> { + + String getFirstName(); + + String getLastName(); + + String getEmail(); + + void setFirstName(String firstName); + + void setLastName(String lastName); + + void setEmail(String email); + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfig.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfigProperty.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/config/IdentityConfigProperty.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfigProperty.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfigProperty.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,49 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util.config; + +/** + * Enumaration of properties to be used in a {@link org.codelutin.util.config.IdentityConfig} + * + * @author chemit + * @see IdentityConfig + */ +public enum IdentityConfigProperty implements Property{ + + /** property <code>name</code>, first name of user */ + firstName(String.class), + + /** property <code>type</code>, lastname of user */ + lastName(String.class), + + /** property <code>email</code>, email of user */ + email(String.class); + + private Class<?> type; + + //TODO add locale + encoding + + public Class<?> getType() { + return type; + } + + IdentityConfigProperty(Class<?> type) { + this.type = type; + } +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/config/IdentityConfigProperty.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/config/Property.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/config/Property.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/config/Property.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/config/Property.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,25 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util.config; + +/** @author chemit */ +public interface Property { + + Class<?> getType(); +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/config/Property.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleConfig.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/config/SimpleConfig.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleConfig.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleConfig.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,135 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util.config; + +import org.apache.commons.beanutils.BeanUtils; +import org.apache.commons.beanutils.BeanUtilsBean; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.Map; + +/** + * simple config implementation based on a Enum to obtain properties + * + * @author chemit + */ +public class SimpleConfig<E extends Enum<E>> implements Config<E> { + + static protected final Log log = LogFactory.getLog(Config.class); + + protected EnumMap<E, Object> properties; + + protected final EnumSet<E> universe; + + protected final Class<E> klass; + + public SimpleConfig(Class<E> klass) { + this.klass = klass; + this.properties = new EnumMap<E, Object>(klass); + this.universe = java.util.EnumSet.allOf(klass); + } + + public SimpleConfig(Class<E> klass, EnumMap<E, Object> properties) { + this(klass); + setProperties(properties); + } + + public EnumMap<E, Object> getProperties() { + return properties.clone(); + } + + public Object getProperty(E key) { + return properties.get(key); + } + + public EnumSet<E> getUniverse() { + return universe; + } + + public void setProperties(EnumMap<E, Object> properties) { + for (Map.Entry<E, Object> entry : properties.entrySet()) { + setProperty(entry.getKey(), entry.getValue()); + } + } + + public void setProperty(E key, Object value) { + if (value == null) { + if (properties.containsKey(key)) { + // never keep a reference on a null value property + properties.remove(key); + } + } else { + log.info("key:" + key + ", value:" + value + ", type:" + value.getClass().getSimpleName()); + properties.put(key, value); + } + } + + @SuppressWarnings({"unchecked"}) + public void copyFrom(Object src) { + copyFrom(src, getUniverse()); + } + + public void copyFrom(Object src, EnumSet<E> keys) { + for (E key : keys) { + Object value = null; + try { + value = BeanUtilsBean.getInstance().getPropertyUtils().getProperty(src, key.name()); + setProperty(key, value); + } catch (Exception e) { + //TODO + log.warn("could not retreave property <" + key + ":" + value + "> on object " + src, e); + } + } + } + + public void copyTo(Object dst) { + copyTo(dst, getUniverse()); + } + + + public void copyTo(Object dst, EnumSet<E> keys) { + for (E key : keys) { + Object value = properties.get(key); + try { + log.info("save " + key); + BeanUtils.setProperty(dst, key.name(), value); + } catch (Exception e) { + //TODO + log.warn("could not set property <" + key + ":" + value + "> to object " + dst, e); + } + } + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + if (properties.isEmpty()) { + sb.append(" empty"); + } else { + for (Map.Entry<E, Object> entry : properties.entrySet()) { + sb.append(", ").append(entry.getKey()).append(':').append(entry.getValue()); + } + } + return super.toString() + '<' + sb.toString().substring(2) + '>'; + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleConfig.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleIdentityConfig.java (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/config/SimpleIdentityConfig.java) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleIdentityConfig.java (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleIdentityConfig.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,69 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util.config; + +import static org.nuiton.util.config.IdentityConfigProperty.email; +import static org.nuiton.util.config.IdentityConfigProperty.firstName; +import static org.nuiton.util.config.IdentityConfigProperty.lastName; + +import java.util.EnumMap; + +/** @author chemit */ +public class SimpleIdentityConfig extends SimpleConfig<IdentityConfigProperty> implements IdentityConfig { + + public SimpleIdentityConfig() { + super(IdentityConfigProperty.class); + } + + public SimpleIdentityConfig(String firstName, String lastName, String email) { + this(); + setFirstName(firstName); + setLastName(lastName); + setEmail(email); + } + + public SimpleIdentityConfig(EnumMap<IdentityConfigProperty, Object> properties) { + super(IdentityConfigProperty.class, properties); + } + + public String getFirstName() { + return (String) properties.get(firstName); + } + + public String getLastName() { + return (String) properties.get(lastName); + } + + public String getEmail() { + return (String) properties.get(email); + } + + public void setFirstName(String newFirstName) { + setProperty(firstName, newFirstName); + } + + public void setLastName(String newLastName) { + setProperty(lastName, newLastName); + } + + public void setEmail(String newEmail) { + setProperty(email, newEmail); + } + +} Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/config/SimpleIdentityConfig.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/main/java/org/nuiton/util/package.html (from rev 1542, nuitonutil/trunk/src/main/java/org/codelutin/util/package.html) =================================================================== --- nuitonutil/trunk/src/main/java/org/nuiton/util/package.html (rev 0) +++ nuitonutil/trunk/src/main/java/org/nuiton/util/package.html 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,11 @@ +<html> + <body> + <h1>Lutin util</h1> +Ensemble de classe Java permettant de simplifier le développement en +factorisant des besoins que l'on retrouve dans tous les développement. +On y trouve de fontion de travail sur les chaînes de caractères. Des +fonctions de parsage des arguements de la ligne de commande. Des fonctions +permettant très simplement de rechercher une resource (images, fichier de +propriétés, ...) + </body> +</html> \ No newline at end of file Property changes on: nuitonutil/trunk/src/main/java/org/nuiton/util/package.html ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Modified: nuitonutil/trunk/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory =================================================================== --- nuitonutil/trunk/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/main/resources/META-INF/services/org.apache.commons.logging.LogFactory 2009-05-14 05:40:24 UTC (rev 1548) @@ -1 +1 @@ -org.codelutin.util.LutinLogFactory \ No newline at end of file +org.nuiton.util.LutinLogFactory \ No newline at end of file Copied: nuitonutil/trunk/src/test/java/org/nuiton/i18n/I18nLoaderTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/i18n/I18nLoaderTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/i18n/I18nLoaderTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/i18n/I18nLoaderTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,120 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.i18n; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Test; + +import java.util.Locale; + +/** + * LanguageManager Tester. + * + * @author chemit + * @version 1.0 + * @since <pre>02/10/2008</pre> + */ +public class I18nLoaderTest { + + String encoding; + Locale locale; + Language language; + I18nLoader loader; + + @AfterClass + public static void afterClass() throws Exception { + I18n.close(); + } + + @Test + public void testGetLoader() throws Exception { + + Assert.assertNull(I18n.loader); + + loader = I18n.getLoader(); + Assert.assertNotNull(loader); + //assertEquals(I18n.DEFAULT_ENCODING, loader.getEncoding()); + Assert.assertNull(loader.getLanguage()); + } + + @Test + public void testChangeLocale() throws Exception { + + locale = I18n.newLocale("fr_FR"); + encoding = I18n.ISO_8859_1_ENCONDING; + updateLanguage(); + assertNbLanguages(1); + updateLanguage(); + assertNbLanguages(1); + + locale = I18n.newLocale("en_GB"); + updateLanguage(); + assertLanguageChanged(); + assertNbLanguages(2); + + locale = I18n.newLocale("en_US"); + updateLanguage(); + assertLanguageChanged(); + assertNbLanguages(3); + + locale = I18n.newLocale("en"); + updateLanguage(); + assertLanguageChanged(); + assertNbLanguages(4); + } + + protected void assertLanguageChanged() { + Assert.assertNotSame(language, loader.getLanguage()); + } + + /*public void testChangeEncoding() throws Exception { + locale = I18n.newLocale("fr_FR"); + encoding = I18n.ISO_8859_1_ENCONDING; + updateLanguage(); + + locale = I18n.newLocale("en_GB"); + updateLanguage(); + + // language change (from his encoding) + assertLanguageChanged(); + // 2 language in cache + assertNbLanguages(2); + + encoding = I18n.UTF_8_ENCONDING; + updateLanguage(); + // language change (from his encoding) + assertLanguageChanged(); + // one language in cache + assertNbLanguages(1); + + }*/ + + protected void assertNbLanguages(int i) { + Assert.assertEquals(i, loader.getLanguages().size()); + } + + protected void updateLanguage() { + language = loader == null ? null : loader.getLanguage(); + loader = I18n.getLoader(); + loader.setLanguage(locale); + } + +} + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/i18n/I18nLoaderTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/i18n/bundle/I18nBundleManagerTest.java (from rev 1544, nuitonutil/trunk/src/test/java/org/codelutin/i18n/bundle/I18nBundleManagerTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/i18n/bundle/I18nBundleManagerTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/i18n/bundle/I18nBundleManagerTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,280 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.i18n.bundle; + +import org.nuiton.i18n.I18nLoader; +import org.nuiton.i18n.I18n; +import org.apache.commons.logging.LogFactory; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Locale; +import org.junit.Assert; + +/** + * I18nBundleFinder Tester. + * <p/> + * For this tests, we assume we have the correspondant bundles : + * <p/> + * verydummy + * dummy + * dummyOnlyfr + * dummyOnlyen + * <p/> + * dummy-fr + * dummyOnlyfr-fr + * dummyOnlyfr2-fr + * dummy-en + * dummyOnlyen-en + * <p/> + * dummy-fr_FR + * lutinutil-fr_FR + * dummy-en_GB + * lutinutil-en_GB + * dummy-en_US + * <p/> + * + * @author chemit + * @version 1.0 + * @since <pre>03/02/2008</pre> + * + * Redo tests for new i18n system + */ +public class I18nBundleManagerTest { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private org.apache.commons.logging.Log log = LogFactory.getLog(I18nBundleManagerTest.class); + Locale locale; + static URLClassLoader loader; + Integer nbURLs = null; + + static enum BundleTest { + + veryDummy(true, false, false, false, false, false), + dummy(true, true, true, true, true, true), + lutinutil(false, false, true, false, false, true), + onlyfr(true, true, false, false, false, false), + onylfr2(false, true, false, false, false, false), + onlyen(true, false, false, true, false, false); + boolean hasGene; + boolean hasFr; + boolean hasFrFR; + boolean hasEn; + boolean hasEnUS; + boolean hasEnUK; + + BundleTest(boolean hasGene, boolean hasFr, boolean hasFrFR, boolean hasEn, boolean hasEnUS, boolean hasEnUK) { + this.hasGene = hasGene; + this.hasFr = hasFr; + this.hasFrFR = hasFrFR; + this.hasEn = hasEn; + this.hasEnUS = hasEnUS; + this.hasEnUK = hasEnUK; + } + + static int getNbGeneralBundles() { + int result = 0; + for (BundleTest bundleTest : values()) { + if (bundleTest.hasGene) { + result++; + } + } + return result; + } + + static int getNbLanguageBundles(boolean fr, boolean en) { + int result = 0; + for (BundleTest bundleTest : values()) { + if (bundleTest.hasGene) { + continue; + } + if (fr && bundleTest.hasFr) { + result++; + } + if (en && bundleTest.hasEn) { + result++; + } + } + return result; + } + + static int gerNbFullBundles(boolean fr, boolean us, boolean uk) { + int result = 0; + for (BundleTest bundleTest : values()) { + if (bundleTest.hasGene || ((uk || us) && bundleTest.hasEn) || (fr && bundleTest.hasFr)) { + continue; + } + if (fr && bundleTest.hasFrFR) { + result++; + } + if (us && bundleTest.hasEnUS) { + result++; + } + if (uk && bundleTest.hasEnUK) { + result++; + } + } + return result; + } + + static int getNbLanguageEntries(boolean fr, boolean en) { + int result = 0; + for (BundleTest bundleTest : values()) { + if (bundleTest.hasGene) { + result++; + } + if (fr && bundleTest.hasFr) { + result++; + } + if (en && bundleTest.hasEn) { + result++; + } + } + return result; + } + + static int gerNbFullEntries(boolean fr, boolean us, boolean uk) { + int result = 0; + for (BundleTest bundleTest : values()) { + if (bundleTest.hasGene) { + result++; + } + if (((uk || us) && bundleTest.hasEn)) { + result++; + } + + if ((fr && bundleTest.hasFr)) { + result++; + } + + if (fr && bundleTest.hasFrFR) { + result++; + } + if (us && bundleTest.hasEnUS) { + result++; + } + if (uk && bundleTest.hasEnUK) { + result++; + } + } + return result; + } + } + + @BeforeClass + public static void beforeClass() throws MalformedURLException { + + loader = (URLClassLoader) I18nBundleManagerTest.class.getClassLoader(); + + URL[] urls = new URL[loader.getURLs().length + 2]; + + urls[0] = new File("target" + File.separator + "test-classes" + File.separator + "i18n").toURI().toURL(); + urls[1] = new File("target" + File.separator + "classes" + File.separator + "i18n").toURI().toURL(); + + int i = 2; + for (URL url : loader.getURLs()) { + urls[i++] = url; + } + loader = new URLClassLoader(urls, loader); + + log.info("use loader " + loader + " (nb urls : " + loader.getURLs().length + ")"); + for (URL url : loader.getURLs()) { + log.info("url found in classloader : " + url); + } + } + + @After + public void after() throws Exception { + locale = null; + } + + @Test + public void testGetURLs() throws Exception { + Assert.assertEquals(getNbURLs(), I18nLoader.getURLs(loader).length); + } + + @Test + public void testDetectBundles() throws Exception { + URL[] urls = I18nLoader.getURLs(loader); + Assert.assertEquals(BundleTest.values().length, I18nBundleFactory.detectBundles(urls).size()); + } + + @Test + public void testGetBundles() throws Exception { + updateLanguage(null); + updateLanguage(Locale.FRENCH); + updateLanguage(Locale.ENGLISH); + updateLanguage(Locale.FRANCE); + updateLanguage(Locale.US); + updateLanguage(Locale.UK); + } + + protected int getNbURLs() { + if (nbURLs == null) { + File f; + f = new File("target" + File.separator + "test-classes" + File.separator + "i18n"); + nbURLs = f.listFiles().length; + f = new File("target" + File.separator + "classes" + File.separator + "i18n"); + nbURLs += f.listFiles().length; + } + return nbURLs; + } + + protected void updateLanguage(Locale newLocale) { + locale = newLocale; + I18n.init(locale); + assertBundlesEntries(); + } + + protected void assertBundlesEntries() { + int nbGene = BundleTest.getNbGeneralBundles(); + boolean isFr = locale != null && "fr".equals(locale.getLanguage()); + boolean isEn = locale != null && "en".equals(locale.getLanguage()); + boolean isFrFR = isFr && locale != null && "FR".equals(locale.getCountry()); + boolean isEnUS = isEn && locale != null && "US".equals(locale.getCountry()); + boolean isEnGB = isEn && locale != null && "GB".equals(locale.getCountry()); + + int nbLang = BundleTest.getNbLanguageBundles(isFr, isEn); + int nbFull = BundleTest.gerNbFullBundles(isFrFR, isEnUS, isEnGB); + + int nbEntries = 0; + + if (locale == null) { + nbEntries = nbGene; + } + + if (isFrFR) { + } + + if (isFrFR || isEnUS || isEnGB) { + nbEntries += BundleTest.gerNbFullEntries(isFrFR, isEnUS, isEnGB); + } else if (isFr || isEn) { + nbEntries += BundleTest.getNbLanguageEntries(isFr, isEn); + } + I18nLoader i18nLoader = I18n.getLoader(); + Assert.assertEquals(nbGene + nbLang + nbFull, i18nLoader.getBundles(locale).length); +// //TODO make eact match with promute logic ! + Assert.assertTrue(nbEntries <= i18nLoader.getBundleEntries(locale).length); + } +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/i18n/bundle/I18nBundleManagerTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/log/LutinLogTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/log/LutinLogTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/log/LutinLogTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/log/LutinLogTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,151 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * LutinLogTest.java + * + * Created: 13 sept. 06 12:41:39 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.log; + +import junit.framework.TestCase; +import org.apache.log4j.Layout; + +import java.io.PrintWriter; +import java.io.StringWriter; + + +/** @author poussin */ + +class Toto { + + static public void stack() throws Exception { + LutinLog log = LutinLogFactory.getLutinLog(LutinLogTest.class); + log.info("Titi called"); + + Throwable t = new Throwable(); + String fqnOfCallingClass = LutinLogTest.class.getName(); + + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + +/* 99*/ + if (t == null) +/* 100*/ return; + String s; +/* 104*/ + synchronized (sw) { +/* 105*/ + t.printStackTrace(pw); +/* 106*/ + s = sw.toString(); +/* 107*/ + sw.getBuffer().setLength(0); + } + + System.err.println(s); + +/* 119*/ + int ibegin = s.lastIndexOf(fqnOfCallingClass); +/* 120*/ + if (ibegin == -1) +/* 121*/ return; +/* 124*/ + ibegin = s.indexOf(Layout.LINE_SEP, ibegin); +/* 125*/ + if (ibegin == -1) +/* 126*/ return; +/* 127*/ + ibegin += Layout.LINE_SEP_LEN; +/* 130*/ + int iend = s.indexOf(Layout.LINE_SEP, ibegin); +/* 131*/ + if (iend == -1) +/* 132*/ return; + String fullInfo = s.substring(ibegin, iend); + System.out.println(fullInfo); + } + +} + +public class LutinLogTest extends TestCase { + + public void testStack() throws Exception { + Toto.stack(); + } + + public void testMonitor() throws Exception { + LutinLog log = LutinLogFactory.getLutinLog(LutinLogTest.class); + + if (log.isTraceEnabled()) { + log.trace("Titi called"); + } + + log.setActivateProgressMonitorTime(1000); + log.user("task started"); + log.setMin(1); + log.setMax(100); + log.start(); + + for (int i = 1; i <= 100; i++) { + if (log.isAskStopTask()) { + break; + } + log.setValue(i); + Thread.sleep(50); + } + + log.user("task finished"); + log.end(); + } + + public void testTimeout() throws Exception { + LutinLog log = LutinLogFactory.getLutinLog(LutinLogTest.class); + + if (log.isTraceEnabled()) { + log.trace("Titi called"); + } + + log.setActivateProgressMonitorTime(1000); + log.setTimeout(3000); + log.user("task started"); + log.setMin(1); + log.setMax(100); + log.start(); + + for (int i = 1; i <= 100; i++) { + if (log.isAskStopTask()) { + break; + } + log.setValue(i); + Thread.sleep(50); + } + + log.user("task finished"); + log.end(); + } + +} + + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/log/LutinLogTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/ApplicationConfigTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/ApplicationConfigTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/ApplicationConfigTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/ApplicationConfigTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,247 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +/* + * 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.nuiton.util; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.ListIterator; +import java.util.Map; +import junit.framework.TestCase; +import org.nuiton.util.ApplicationConfig.Action; + +/** + * + * @author poussin + */ +public class ApplicationConfigTest extends TestCase { + + static int dummyActionCall = 0; + static public class DummyAction { + @Action.Step(1) + public void dummyAction(String s, int step) { + dummyActionCall++; + System.out.println(s + ":" + step); + } + } + + public ApplicationConfigTest(String testName) { + super(testName); + } + + /** + * Test of getUnparsed method, of class ApplicationConfig. + */ + public void testGetUnparsed() throws Exception { + System.out.println("getUnparsed"); + ApplicationConfig instance = new ApplicationConfig(); + List<String> expResult = new ArrayList<String>(); + List<String> result = instance.getUnparsed(); + assertEquals(expResult, result); + + expResult.add("toto"); + expResult.add("titi"); + expResult.add("tata"); + + instance.parse(new String[]{"toto", "titi", "tata"}); + result = instance.getUnparsed(); + assertEquals(expResult, result); + } + + /** + * Test of addAction method, of class ApplicationConfig. + */ + public void testAddAction() throws Exception { + System.out.println("addAction"); + Action action = null; + ApplicationConfig instance = new ApplicationConfig(); + + // test add null Action + instance.addAction(action); + + action = new Action(1, new DummyAction(), DummyAction.class.getMethod("dummyAction", String.class, Integer.TYPE), "coucou", "12"); + instance.addAction(action); + } + + /** + * Test of doAction method, of class ApplicationConfig. + */ + public void testDoAction() throws Exception { + System.out.println("doAction"); + ApplicationConfig instance = new ApplicationConfig(); + + Action action = new Action(1, new DummyAction(), DummyAction.class.getMethod("dummyAction", String.class, Integer.TYPE), "coucou", "12"); + instance.addAction(action); + + dummyActionCall = 0; + assertEquals(0, dummyActionCall); + instance.doAction(0); + assertEquals(0, dummyActionCall); + instance.doAction(1); + assertEquals(1, dummyActionCall); + instance.doAction(2); + assertEquals(1, dummyActionCall); + } + + /** + * Test of setUseOnlyAliases method, of class ApplicationConfig. + */ + public void testSetUseOnlyAliases() { + System.out.println("setUseOnlyAliases"); + ApplicationConfig instance = new ApplicationConfig(); + assertEquals(false, instance.isUseOnlyAliases()); + instance.setUseOnlyAliases(false); + assertEquals(false, instance.isUseOnlyAliases()); + instance.setUseOnlyAliases(true); + assertEquals(true, instance.isUseOnlyAliases()); + } + + /** + * Test of addAlias method, of class ApplicationConfig. + */ + public void testAddAlias() throws Exception { + System.out.println("addAlias"); + ApplicationConfig instance = new ApplicationConfig(); + instance.addAlias("toto", "totochange"); + instance.addAlias("titi", "titichange"); + + List<String> expResult = new ArrayList<String>(); + List<String> result = instance.getUnparsed(); + assertEquals(expResult, result); + + expResult.add("totochange"); + expResult.add("titichange"); + expResult.add("tata"); + + instance.parse(new String[]{"toto", "titi", "tata"}); + result = instance.getUnparsed(); + assertEquals(expResult, result); + } + + /** + * Test of setConfigFileName method, of class ApplicationConfig. + */ + public void testSetConfigFileName() { + System.out.println("setConfigFileName"); + ApplicationConfig instance = new ApplicationConfig(); + instance.setConfigFileName("bidulle"); + assertEquals("bidulle", instance.getConfigFileName()); + } + + /** + * Test of setOption method, of class ApplicationConfig. + */ + public void testSetOption() { + System.out.println("setOption"); + ApplicationConfig instance = new ApplicationConfig(); + assertEquals(null, instance.getOption("truc")); + instance.setOption("truc", "bidulle"); + assertEquals("bidulle", instance.getOption("truc")); + } + + /** + * Test of getMethods method, of class ApplicationConfig. + */ + public void testGetMethods() { + System.out.println("getMethods"); + ApplicationConfig instance = new ApplicationConfig(); + Map<String, Method> result = instance.getMethods(); + assertTrue(result.containsKey("option")); + } + + /** + * Test of getParams method, of class ApplicationConfig. + */ + public void testGetParams() throws Exception { + System.out.println("getParams"); + Method m = DummyAction.class.getMethod("dummyAction", String.class, Integer.TYPE); + List<String> list = new ArrayList<String>(Arrays.asList("toto", "10", "/tmp", "9")); + ListIterator<String> args = list.listIterator(); + + ApplicationConfig instance = new ApplicationConfig(); + String[] expResult = new String[]{"toto", "10"}; + String[] result = instance.getParams(m, args); + assertEquals(Arrays.asList(expResult), Arrays.asList(result)); + assertEquals(2, list.size()); + } + + /** + * Test of createAction method, of class ApplicationConfig. + */ + public void testCreateAction() throws Exception { + System.out.println("createAction"); + List<String> list = new ArrayList<String>(Arrays.asList("dummy", "toto", "10", "/tmp", "9")); + ListIterator<String> args = list.listIterator(); + args.next(); + ApplicationConfig instance = new ApplicationConfig(); + + Action result = instance.createAction( + DummyAction.class.getName() + "#dummyAction", args); + assertEquals(1, result.step); + dummyActionCall = 0; + result.doAction(); + assertEquals(1, dummyActionCall); +} + + /** + * Test of parse method, of class ApplicationConfig. + */ + public void testParse() throws Exception { + System.out.println("parse"); + String[] args = "-f file -v -d -o /tmp/file -m coucou 10 others args".split(" "); + ApplicationConfig instance = new ApplicationConfig(); + instance.addAlias("-f", "--option", "file"); + instance.addAlias("-v", "--option", "verbose", "true"); + instance.addAlias("-d", "--option", "debug", "true"); + instance.addAlias("-o", "--option", "output"); + instance.addAlias("-m", "--" + DummyAction.class.getName() + "#dummyAction"); + instance.parse(args); + + dummyActionCall = 0; + assertEquals("file", instance.getOption("file")); + assertEquals("true", instance.getOption("verbose")); + assertEquals("true", instance.getOption("debug")); + assertEquals("/tmp/file", instance.getOption("output")); + assertEquals(Arrays.asList("others", "args"), instance.getUnparsed()); + + instance.doAction(1); + assertEquals(1, dummyActionCall); + } + +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/ApplicationConfigTest.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/CallAnalyseTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/CallAnalyseTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/CallAnalyseTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/CallAnalyseTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,84 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * CallAnalyseTest.java + * + * Created: 25 août 2005 21:03:50 CEST + * + * @author Benjamin POUSSIN <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import junit.framework.TestCase; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.List; + +public class CallAnalyseTest extends TestCase { // CallAnalyseTest + + /** to use log facility, just put in your code: log.info(\"...\"); */ + static private Log log = LogFactory.getLog(CallAnalyseTest.class); + + protected List<List<?>> memoryConsume = new ArrayList<List<?>>(); + + public void testCall() throws Exception { + CallAnalyse.activate(); + for (int i = 0; i < 10; i++) { + eatMemory(); + freeMemory(); + } + + assertEquals(10, CallAnalyse.getThreadStatistics().get("eatMemory").getCalls()); + assertEquals(10, CallAnalyse.getThreadStatistics().get("freeMemory").getCalls()); + + log.debug(CallAnalyse.getThreadStatistics()); + } + + protected void eatMemory() { + CallAnalyse.enter("eatMemory"); + try { + for (int i = 0; i < 100; i++) { + memoryConsume.add(new ArrayList(100)); + } + } catch (Exception eee) { + // do nothing + } finally { + CallAnalyse.exit("eatMemory"); + } + } + + protected void freeMemory() { + CallAnalyse.enter("freeMemory"); + try { + memoryConsume.clear(); + } catch (Exception eee) { + // do nothing + } finally { + CallAnalyse.exit("freeMemory"); + } + } + +} // CallAnalyseTest + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/CallAnalyseTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/CardinalityHelperTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/CardinalityHelperTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/CardinalityHelperTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/CardinalityHelperTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,175 @@ +/* +* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ +package org.nuiton.util; + +import junit.framework.TestCase; + +/** + * CardinalityHelper Tester. + * + * @author chemit + * @version 1.0 + * @since <pre>12/17/2007</pre> + */ +public class CardinalityHelperTest extends TestCase { + + String txt; + Object[] result; + StringBuilder sb; + + public void testNoMaxParsing() { + txt = "*"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "", 0, -1); + + txt = "yo*"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 0, -1); + + txt = "yo+"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 1, -1); + + txt = "yo *"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 0, -1); + + txt = "yo +"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 1, -1); + } + + public void testExactlyParsing() { + txt = "{5}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "", 5, 5); + + txt = "yo{1}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 1, 1); + + txt = "yo {2}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 2, 2); + + txt = "yo {12}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 12, 12); + } + + public void testBoundedParsing() { + txt = "{1,2}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "", 1, 2); + + txt = "{2,*}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "", 2, -1); + + txt = "yo{1,2}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 1, 2); + + txt = "yo {10,20}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 10, 20); + + txt = "yo {10,*}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo", 10, -1); + } + + public void testDefaultParsing() { + txt = "yo {a}"; + result = CardinalityHelper.parseCardinalite(txt, false); + assertCardinalite(result, "yo {a}", 0, 1); + + txt = "yo {a}"; + result = CardinalityHelper.parseCardinalite(txt, true); + assertCardinalite(result, "yo {a}", 1, 1); + } + + public void testPrintCardinality() { + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,1,true,"<",">","[","]"); + assertPrint(sb,"[yo]"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,5,false,"<",">","[","]"); + assertPrint(sb,"[yo]{0,5}"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,-1,false,"<",">","[","]"); + assertPrint(sb,"[yo]*"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,1,true,"<",">","",""); + assertPrint(sb,"yo{0,1}"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,1,false,"<",">","",""); + assertPrint(sb,"yo"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,5,false,"<",">","",""); + assertPrint(sb,"yo{0,5}"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",0,-1,false,"<",">","",""); + assertPrint(sb,"yo*"); + + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,1,false,"<",">","[","]"); + assertPrint(sb,"<yo>"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",5,5,true,"<",">","[","]"); + assertPrint(sb,"<yo>{5}"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,5,true,"<",">","[","]"); + assertPrint(sb,"<yo>{1,5}"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,-1,true,"<",">","[","]"); + assertPrint(sb,"<yo>+"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",3,-1,true,"<",">","[","]"); + assertPrint(sb,"<yo>{3,*}"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,1,false,"","","[","]"); + assertPrint(sb,"yo{1}"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,1,true,"","","[","]"); + assertPrint(sb,"yo"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",5,5,true,"","","[","]"); + assertPrint(sb,"yo{5}"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,5,true,"","","[","]"); + assertPrint(sb,"yo{1,5}"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",1,-1,true,"","","[","]"); + assertPrint(sb,"yo+"); + + CardinalityHelper.printCardinalite(sb = new StringBuilder(),"yo",3,-1,true,"","","[","]"); + assertPrint(sb,"yo{3,*}"); + } + + private void assertPrint(StringBuilder sb, String expectedResult) { + assertEquals(expectedResult,sb.toString()); + } + + private void assertCardinalite(Object[] result, String key, Integer min, Integer max) { + assertEquals(key, (String) result[0]); + assertEquals(min, result[1]); + assertEquals(max, result[2]); + } + +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/CardinalityHelperTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/CategorisedListenerSetTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/CategorisedListenerSetTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/CategorisedListenerSetTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/CategorisedListenerSetTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,107 @@ +/* + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ + +/******************************************************************************* + * CategorisedListenerSetTest.java + * + * Created: 3 janv. 2006 23:27:42 + * + * @author poussin + * + * @version $Revision$ + * + * Last update: $Date$ by : $Author$ + */ + +package org.nuiton.util; + +import junit.framework.TestCase; + +/** @author poussin */ + +public class CategorisedListenerSetTest extends TestCase { + + /* + * Test method for + * 'org.codelutin.util.CategorisedListenerSet.getAllListeners(Object)' + */ + public void testGetAllListeners() { + + { + CategorisedListenerSet<Object> cls = new CategorisedListenerSet<Object>(); + + String[] ls = new String[]{"Double", "Long", "Number", "Object", + "LoggingException", "Throwable"}; + + cls.add(Double.class, ls[0]); + cls.add(Long.class, ls[1]); + cls.add(Number.class, ls[2]); + cls.add(Object.class, ls[3]); + + assertEquals(3, cls.getAllListeners(Double.class).size()); + assertEquals(3, cls.getAllListeners(Long.class).size()); + assertEquals(2, cls.getAllListeners(Number.class).size()); + assertEquals(1, cls.getAllListeners(Object.class).size()); + + cls.addCategory(LoggingException.class, Number.class); + + cls.add(LoggingException.class, ls[4]); + cls.add(Throwable.class, ls[5]); + + assertEquals(5, cls.getAllListeners(Double.class).size()); + assertEquals(5, cls.getAllListeners(Long.class).size()); + assertEquals(4, cls.getAllListeners(Number.class).size()); + assertEquals(1, cls.getAllListeners(Object.class).size()); + + assertEquals(3, cls.getAllListeners(LoggingException.class).size()); + assertEquals(2, cls.getAllListeners(Throwable.class).size()); + + } + { + CategorisedListenerSet<Object> cls = new CategorisedListenerSet<Object>(null, false); + + String[] ls = new String[]{"Double", "Long", "Number", "Object", + "LoggingException", "Throwable"}; + + cls.add(Double.class, ls[0]); + cls.add(Long.class, ls[1]); + cls.add(Number.class, ls[2]); + cls.add(Object.class, ls[3]); + + assertEquals(1, cls.getAllListeners(Double.class).size()); + assertEquals(1, cls.getAllListeners(Long.class).size()); + assertEquals(1, cls.getAllListeners(Number.class).size()); + assertEquals(1, cls.getAllListeners(Object.class).size()); + + cls.addCategory(LoggingException.class, Number.class); + + cls.add(LoggingException.class, ls[4]); + cls.add(Throwable.class, ls[5]); + + assertEquals(1, cls.getAllListeners(Double.class).size()); + assertEquals(1, cls.getAllListeners(Long.class).size()); + assertEquals(2, cls.getAllListeners(Number.class).size()); + assertEquals(1, cls.getAllListeners(Object.class).size()); + + assertEquals(1, cls.getAllListeners(LoggingException.class).size()); + assertEquals(1, cls.getAllListeners(Throwable.class).size()); + } + } + +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/CategorisedListenerSetTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/CollectionUtilTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/CollectionUtilTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/CollectionUtilTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/CollectionUtilTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,56 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util; + +import junit.framework.TestCase; + +import java.util.ArrayList; +import java.util.List; + +/** + * CollectionUtil Tester. + * + * @author chemit + * @version 1.0 + * @since <pre>02/04/2008</pre> + */ +public class CollectionUtilTest extends TestCase { + public CollectionUtilTest(String name) { + super(name); + } + + public void testToGenericList() throws Exception { + List<String> list = new ArrayList<String>(); + list.add("a"); + list.add("b"); + list.add("c"); + + assertEquals(CollectionUtil.toGenericList(list, String.class), list); + assertEquals(CollectionUtil.toGenericList(list, Object.class), list); + + try { + CollectionUtil.toGenericList(list, Integer.class); + fail(); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + } + +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/CollectionUtilTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/ConverterUtilTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/ConverterUtilTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/ConverterUtilTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/ConverterUtilTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,56 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util; + +import junit.framework.TestCase; + +/** + * ConverterUtil Tester. + * + * @author chemit + * @version 1.0 + * @since <pre>02/13/2008</pre> + */ +public class ConverterUtilTest extends TestCase { + + public ConverterUtilTest(String name) { + super(name); + } + + public void testConvert() throws Exception { + String s; + s = ""; + assertEquals(new String(s.getBytes()), new String(ConverterUtil.convert(s.toCharArray()))); + + s = "a"; + assertEquals(new String(s.getBytes()), new String(ConverterUtil.convert(s.toCharArray()))); + + s = "kZZFIOFEIOFEfdskdfmldsfjklsfjldfldfjdsfiosabcd4567'''`~teAZEst"; + assertEquals(new String(s.getBytes()), new String(ConverterUtil.convert(s.toCharArray()))); + + s = "]{}{}{{[#{[{#[#]{][{^#][^]#{^[]{#][#]{]@[{#][^#{][^]#{teAZEst"; + assertEquals(new String(s.getBytes()), new String(ConverterUtil.convert(s.toCharArray()))); + + // FIXME following test won't pass + //s = "éééééé]{}{}{{[#{[{#[#]{][{^#][^]#{^[]{#][#]{]@[{#][^#{][^]#{teAZEst"; + //assertEquals(new String(s.getBytes()), new String(ConverterUtil.convert(s.toCharArray()))); + + } + +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/ConverterUtilTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/FileCompletionTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/FileCompletionTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/FileCompletionTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/FileCompletionTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,60 @@ +/** + * *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* + */ +package org.nuiton.util; + +import org.junit.Ignore; +import org.junit.Test; + +/** + * FileCompletionTest. + * + * @author chatellier + * @version $Revision$ + * + * Last update : $Date$ + * By : $Author$ + */ +@Ignore +public class FileCompletionTest { + + /** + * FIXME test is keyboard interactive. + * + * @throws Exception + */ + @Test + public void testMe() throws Exception { + FileCompletion fc = new FileCompletion(true, true); + if (fc.consoleAvailable()) { + new Thread(new Runnable() { + + public void run() { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // do not care... + } finally { + System.console().readLine("!q"); + } + } + }).start(); + System.out.println(fc.read()); + } + } +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/FileCompletionTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/FileUtilTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/FileUtilTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/FileUtilTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/FileUtilTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,100 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +package org.nuiton.util; + +import java.io.File; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; + +/** + * FileUtilTest. + * + * Created: 22 nov. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class FileUtilTest { // FileUtilTest + + @Test + public void testFind() throws Exception { + List result = FileUtil.find(new File("."), ".*FileUtil.*", true); + Assert.assertTrue(result.size() != 0); + } + + @Test + public void testBasename() throws Exception { + String result = FileUtil.basename(new File("/tmp/toto.xml"), ".xml"); + Assert.assertEquals("toto", result); + } + + @Test + public void testExtension() throws Exception { + String result = FileUtil.extension(new File("/tmp/toto.xml")); + Assert.assertEquals("xml", result); + result = FileUtil.extension(new File("/tmp/toto.xml"), ".", "o"); + Assert.assertEquals("xml", result); + result = FileUtil.extension(new File("/tmp/toto.xml"), "t", "."); + Assert.assertEquals("o.xml", result); + } + + @Test + public void testCopyRecursively() throws Exception { + File srcDir = FileUtil.createTempDirectory("test-copyRecursively", ""); + File destDir1 = FileUtil.createTempDirectory("test-copyRecursively", ""); + File destDir2 = FileUtil.createTempDirectory("test-copyRecursively", ""); + + new File(srcDir, "toto").createNewFile(); + new File(srcDir, "titi").createNewFile(); + new File(srcDir, "tutu").createNewFile(); + new File(srcDir, "tata").createNewFile(); + File subdir = new File(srcDir, "subdir"); + subdir.mkdirs(); + new File(subdir, "tyty").createNewFile(); + new File(subdir, "titi").createNewFile(); + + FileUtil.copyRecursively(srcDir, destDir1); + FileUtil.copyRecursively(srcDir, destDir2, ".*titi$"); + + // remove created temp dirs : + FileUtil.deleteRecursively(srcDir); + FileUtil.deleteRecursively(destDir1); + FileUtil.deleteRecursively(destDir2); + } + + @Test + public void testFileToByteToFile() throws Exception { + String content = "testFileToByteToFile"; + File file = FileUtil.getTempFile(content); + + byte[] bytes = FileUtil.fileToByte(file); + File dest = File.createTempFile("testFileToByteToFile", ".txt"); + dest.deleteOnExit(); + FileUtil.byteToFile(bytes, dest); + + Assert.assertEquals(file.length(), dest.length()); + Assert.assertEquals(content, FileUtil.readAsString(dest)); + } + +} // FileUtilTest + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/FileUtilTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/LRUMapMultiKeyTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/LRUMapMultiKeyTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/LRUMapMultiKeyTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/LRUMapMultiKeyTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,112 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * LRUMapMultiKeyTest.java + * + * Created: 23 mai 2006 04:57:50 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import junit.framework.TestCase; + +import java.util.List; + + +/** @author poussin */ + +public class LRUMapMultiKeyTest extends TestCase { + + + /* + * Test method for 'org.codelutin.util.LRUMapMultiKey.clear()' + */ + public void testClear() { + System.out.println("testClear"); + LRUMapMultiKey map = new LRUMapMultiKey(10); + LRUMapMultiKey.Key key1 = map.createKey("testClear", "toto", "tyty", "tutu"); + LRUMapMultiKey.Key key2 = map.createKey("toto", "titi", "tutu"); + LRUMapMultiKey.Key key3 = map.createKey("toto", "titi", "tata"); + + map.put(key1, "value"); + map.put(key2, "value"); + map.put(key3, "value"); + + map.clear(); + + assertEquals(0, map.size()); + assertEquals(0, map.keys.size()); + } + + /* + * Test method for 'java.util.WeakHashMap.get(Object)' + */ + public void testGet() throws Exception { + System.out.println("testGet"); + LRUMapMultiKey map = new LRUMapMultiKey(1); + + LRUMapMultiKey.Key key1 = map.createKey("toto", "titi", "tutu"); + map.put(key1, "value1"); + + assertEquals("value1", map.get(map.createKey("toto", "titi", "tutu"))); + + + LRUMapMultiKey.Key key2 = map.createKey("tyty"); + map.put(key2, "value2"); + + assertEquals(null, map.get(key1)); + assertEquals("value2", map.get(key2)); + + assertEquals(1, map.size()); + assertEquals(1, map.keys.size()); + } + + /* + * Test method for 'java.util.WeakHashMap.remove(Object)' + */ + public void testRemoveObject() { + System.out.println("testRemoveObject"); + LRUMapMultiKey map = new LRUMapMultiKey(10); + LRUMapMultiKey.Key key1 = map.createKey("testRemoveObject", "toto", "tyty", "tutu"); + LRUMapMultiKey.Key key2 = map.createKey("toto", "titi", "tutu"); + LRUMapMultiKey.Key key3 = map.createKey("toto", "titi", "tata"); + + map.put(key1, "value"); + map.put(key2, "value"); + map.put(key3, "value"); + + Object l = map.remove("titi"); + + assertTrue(l instanceof List); + assertEquals(2, ((List) l).size()); + assertEquals(1, map.size()); + + map.remove(key1); + + assertEquals(0, map.size()); + } + +} + + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/LRUMapMultiKeyTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/ListenerSetTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/ListenerSetTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/ListenerSetTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/ListenerSetTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,156 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * ListenerSetTest.java + * + * Created: 10 mai 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import junit.framework.TestCase; + +public class ListenerSetTest extends TestCase { // ListenerSetTest + + int callCount; + + /** si la class n'est pas public fire ne retrouve pas les méthodes :( */ + public class Listener { + public void event1() { + callCount++; + } + + public void event2(Object o) { + callCount++; + } + } + + class PrivateListener { + public void event1() { + callCount++; + } + + public void event2(Object o) { + callCount++; + } + } + + public void testAdd() throws Exception { + ListenerSet<Object> set = new ListenerSet<Object>(); + Listener l = new Listener(); + + // ajout d'un listener + set.add(l); + + callCount = 0; + set.fire("event1"); + assertEquals(1, callCount); + + // ajout du meme listener + set.add(l); + callCount = 0; + set.fire("event1"); + assertEquals(1, callCount); + + // destruction de la reference sur le listener + l = null; + System.gc(); + + callCount = 0; + set.fire("event1"); + assertEquals(0, callCount); + } + + public void testAddContrained() throws Exception { + ListenerSet<Listener> set = new ListenerSet<Listener>(); + Listener l = new Listener(); + + // ajout d'un listener + set.add(l); + + callCount = 0; + set.fire("event1"); + assertEquals(1, callCount); + } + + public void testRemove() throws Exception { + ListenerSet<Object> set = new ListenerSet<Object>(); + Listener l = new Listener(); + set.add(l); + + callCount = 0; + set.fire("event1"); + assertEquals(1, callCount); + + set.remove(l); + + callCount = 0; + set.fire("event1"); + assertEquals(0, callCount); + } + + public void testFire() throws Exception { + ////////////////////////////////////////////////: + // avec le listener public + // + { + ListenerSet<Object> set = new ListenerSet<Object>(); + Listener l = new Listener(); + set.add(l); + + callCount = 0; + set.fire("event1"); + assertEquals(1, callCount); + + callCount = 0; + set.fire("event2", null); + assertEquals(1, callCount); + } + ////////////////////////////////////////////////: + // avec le listener privé + // + { + ListenerSet<Object> set = new ListenerSet<Object>(); + PrivateListener li = new PrivateListener(); + set.add(li); + + callCount = 0; + for (Object aSet : set) { + PrivateListener l = (PrivateListener) aSet; + l.event1(); + } + assertEquals(1, callCount); + + callCount = 0; + for (Object aSet : set) { + PrivateListener l = (PrivateListener) aSet; + l.event2(null); + } + assertEquals(1, callCount); + } + } + +} // ListenerSetTest + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/ListenerSetTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/LogTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/LogTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/LogTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/LogTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,125 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * LogTest.java + * + * Created: 12 août 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import junit.framework.TestCase; + +public class LogTest extends TestCase { // LogTest + + protected int callTest = 0; + protected int callAll = 0; + protected int taskMax = 0; + protected int taskValue = 0; + + public class LogListenerTest implements Log.LogListener { + boolean all = false; + + public LogListenerTest(boolean all) { + this.all = all; + } + + public void logMessage(Log.LogEvent e) { + if (all) callAll++; + else callTest++; + } + + public void logTask(Log.LogEvent e) { + taskMax = e.getTaskMax(); + taskValue = e.getTaskValue(); + } + } + + public void testLog() throws Exception { + LogListenerTest ltest = new LogListenerTest(false); + LogListenerTest lall = new LogListenerTest(true); + + Log.addLogListener(lall); + Log.addLogListener(ltest, "TEST"); + + assertEquals(callTest, 0); + assertEquals(callAll, 0); + + Log.logUserInfo("TEST", "coucou"); + + assertEquals(callTest, 1); + assertEquals(callAll, 1); + + Log.logUserInfo("OTHERTEST", "coucou"); + + assertEquals(callTest, 1); + assertEquals(callAll, 2); + + Log.removeLogListener(lall); + Log.logUserInfo("TEST", "coucou"); + + assertEquals(callTest, 2); + assertEquals(callAll, 2); + + Log.logUserInfo("OTHERTEST", "coucou"); + + assertEquals(callTest, 2); + assertEquals(callAll, 2); + + Log.removeLogListener(ltest, "TEST"); + Log.logUserInfo("TEST", "coucou"); + + assertEquals(callTest, 2); + assertEquals(callAll, 2); + + Log.addLogListener(lall); + Log.logUserInfo("TEST", "coucou"); + + assertEquals(callTest, 2); + assertEquals(callAll, 3); + + // test des task + + assertEquals(0, taskMax); + assertEquals(0, taskValue); + + Log.logTask("TEST", "on avance", -1, 0); + assertEquals(-1, taskMax); + assertEquals(0, taskValue); + + Log.logTask("TEST", "on avance", 0, 0); + assertEquals(0, taskMax); + assertEquals(0, taskValue); + + Log.logTask("TEST", "on avance", 10, 5); + assertEquals(10, taskMax); + assertEquals(5, taskValue); + + Log.logTask("TEST", "on avance", 10, 10); + assertEquals(10, taskMax); + assertEquals(10, taskValue); + } + +} // LogTest + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/LogTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/ObjectUtilTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/ObjectUtilTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/ObjectUtilTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/ObjectUtilTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,140 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * ObjectUtilTest.java + * + * Created: 19 nov. 07 12:39:28 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import java.io.File; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import junit.framework.TestCase; + + +/** + * @author poussin + * + */ +public class ObjectUtilTest extends TestCase { + + public void testCall() throws Exception { + Dummy dummy = new Dummy(); + + List<Method> methods = ObjectUtil.getMethod(Dummy.class, "setfile", true); + assertEquals(1, methods.size()); + ObjectUtil.call(dummy, methods.get(0), "/tmp"); + assertEquals(new File("/tmp"), dummy.getFile()); + + methods = ObjectUtil.getMethod(Dummy.class, "setAllFile", true); + assertEquals(1, methods.size()); + ObjectUtil.call(dummy, methods.get(0), "toto", "/tmp", "/tmp/titi"); + assertEquals("toto", dummy.getName()); + assertEquals(Arrays.asList(new File("/tmp"), new File("/tmp/titi")), + Arrays.asList(dummy.getAllFile())); + + ObjectUtil.call(dummy, methods.get(0), "toto"); + assertEquals("toto", dummy.getName()); + assertEquals(new ArrayList<File>(), + Arrays.asList(dummy.getAllFile())); +} + + public void testCreate() throws Exception { + Object o = ObjectUtil.create("java.lang.StringBuffer"); + assertTrue(o != null); + assertTrue(o instanceof StringBuffer); + + Dummy dummy = (Dummy)ObjectUtil.create( + "org.nuiton.util.ObjectUtilTest$Dummy(name=\"coucou le monde\", file=/tmp/fileTest, integer=50)"); + assertTrue(dummy != null); + assertEquals("coucou le monde", dummy.getName()); + assertEquals(50, dummy.getInteger()); + assertEquals(new File("/tmp/fileTest"), dummy.getFile()); + } + + + static public class Dummy { + + String name; + int integer; + File file; + File[] allFile; + + public File[] getAllFile() { + return allFile; + } + + public void setAllFile(String name, File ... allFile) { + this.name = name; + this.allFile = allFile; + } + + /** + * @return the file + */ + public File getFile() { + return this.file; + } + + /** + * @return the integer + */ + public int getInteger() { + return this.integer; + } + + /** + * @return the name + */ + public String getName() { + return this.name; + } + + /** + * @param file the file to set + */ + public void setFile(File file) { + this.file = file; + } + + /** + * @param integer the integer to set + */ + public void setInteger(int integer) { + this.integer = integer; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + } +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/ObjectUtilTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/RecursivePropertiesTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/RecursivePropertiesTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/RecursivePropertiesTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/RecursivePropertiesTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,64 @@ +/* *##% + * Copyright (C) 2009 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.nuiton.util; + +import java.io.FileInputStream; +import java.io.IOException; + +import org.junit.Assert; +import org.junit.Test; + +/** + * Test recursives properties class. + * + * @author chatellier + * @version $Revision: 1.0 $ + * + * Last update : $Date: 24 avr. 2009 $ + * By : $Author: chatellier $ + */ +public class RecursivePropertiesTest { + + /** + * Test string by \\ in value. + * + * @throws IOException + */ + @Test + public void testWindowsFile() throws IOException { + RecursiveProperties props = new RecursiveProperties(); + props.load(new FileInputStream("src/test/resources/properties/windows.properties")); + + Assert.assertEquals("C:\\Documents and Settings\\guest\\.ssh\\id_rsa", props.getProperty("vcs.ssh.keyFile")); + } + + /** + * Test with recursive properties. + * + * @throws IOException + */ + @Test + public void testRecursive() throws IOException { + RecursiveProperties props = new RecursiveProperties(); + props.load(new FileInputStream("src/test/resources/properties/recursive.properties")); + + Assert.assertEquals("World", props.getProperty("username")); + Assert.assertEquals("Hello World !", props.getProperty("helloWorld")); + } +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/RecursivePropertiesTest.java ___________________________________________________________________ Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/ResourceTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/ResourceTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/ResourceTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/ResourceTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,129 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * +* ResourceTest.java +* +* Created: Jul 29, 2004 +* +* @author Benjamin Poussin <poussin@codelutin.com> +* Copyright Code Lutin +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.nuiton.util; + +import java.io.File; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Assert; + +import org.junit.Test; + +public class ResourceTest { // ResourceTest + + @Test + public void testaddDefaultClassLoader() throws Exception { + Assert.assertNull(ResourceTest.class.getResource("/bin/java")); + + File repository = new File(System.getProperty("java.home")); + Resource.addDefaultClassLoader(repository.toURI().toURL()); + + File result = new File(repository, "bin" + File.separator + "java"); + Assert.assertTrue(result.exists()); + + URL resultURL = Resource.getURL("bin/java"); + Assert.assertEquals(result.toURI().toURL(),resultURL); + } + + @Test + public void testGetURL()throws Exception { + URL url; + + url = Resource.getURL("README.txt"); + Assert.assertNotNull(url); + + url = Resource.getURL("bin/java"); + Assert.assertNotNull(url); + } + + @Test + public void testGetURLsFromDirectory() throws Exception { + List<URL> list = new ArrayList<URL>(); + File repository = new File(System.getProperty("java.home")); + + // test lorsqu'aucun fichier du repertoire ne correspond au pattern + Assert.assertEquals(list, Resource.getURLsFromDirectory(repository, ".*.aucunFichierTrouve")); + + File file = new File(repository, "bin" + File.separator + "java"); + list.add(file.toURI().toURL()); + + // test qui prouve que la methode retourne le bon fichier + Assert.assertEquals(list, Resource.getURLsFromDirectory(new File(repository, "bin"), ".*" + File.separator + ".a.a$")); + + // test qui prouve la recursivite (va chercher en profondeur les fichiers) + Assert.assertEquals(list, Resource.getURLsFromDirectory(repository, ".*" + File.separator + "j.v.$")); + } + + @Test + public void testGetURLsFromJar() throws Exception { + File repository = new File(System.getProperty("java.home")); + File file = new File(repository, "lib" + File.separator + "rt.jar"); + + List<URL> result = Resource.getURLsFromJar(file, ".*OutOfMemoryError.*"); + Assert.assertEquals(1, result.size()); + } + + @Test + public void testGetURLs() throws Exception { + System.out.println(java.util.Arrays.asList(((URLClassLoader)ClassLoader.getSystemClassLoader()).getURLs())); + + List<URL> result; + + result = Resource.getURLs(".*bin/java"); + System.out.println(result); + + result = Resource.getURLs("META-INF/MANIFEST.MF"); + System.out.println(result); + } + + @Test + public void testIsJar() throws Exception { + Assert.assertTrue(Resource.isJar("toto.jar")); + Assert.assertTrue(Resource.isJar("toto.JaR")); + Assert.assertFalse(Resource.isJar("totojar")); + Assert.assertFalse(Resource.isJar("")); + Assert.assertFalse(Resource.isJar(null)); + } + + @Test + public void testIsZip() throws Exception { + Assert.assertTrue(Resource.isZip("toto.zip")); + Assert.assertTrue(Resource.isZip("toto.zIp")); + Assert.assertFalse(Resource.isZip("totojarzip")); + Assert.assertFalse(Resource.isZip("")); + Assert.assertFalse(Resource.isZip(null)); + } + +} // ResourceTest + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/ResourceTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/StreamKeywordTokenizerTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/StreamKeywordTokenizerTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/StreamKeywordTokenizerTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/StreamKeywordTokenizerTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,104 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * StreamKeywordTokenizer.java + * + * Created: 27 mai 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import junit.framework.TestCase; +import java.io.StringReader; + +public class StreamKeywordTokenizerTest extends TestCase { // StreamKeywordTokenizer + + public void testKeywordLower() throws Exception { + StringReader in = new StringReader("Coucou tOUt TouT lE MONDE"); + StreamKeywordTokenizer parser = new StreamKeywordTokenizer(in); + parser.resetSyntax(); + parser.commentChar('#'); + parser.eolIsSignificant(false); + parser.lowerCaseMode(false); + parser.parseNumbers(); + parser.quoteChar('"'); + parser.slashSlashComments(true); + parser.slashStarComments(true); + parser.whitespaceChars(0, ' '); + parser.wordChars('A', 'Z'); + parser.wordChars('a', 'z'); + + parser.lowerCaseKeyword(true); + parser.addKeyword("Coucou"); + parser.addKeyword("TouT"); + parser.addKeyword("mondE"); + + assertTrue(StreamKeywordTokenizer.TT_KEYWORD == parser.nextToken() + && parser.sval.equals("coucou")); + assertTrue(StreamKeywordTokenizer.TT_KEYWORD == parser.nextToken() + && parser.sval.equals("tout")); + assertTrue(StreamKeywordTokenizer.TT_KEYWORD == parser.nextToken() + && parser.sval.equals("tout")); + assertTrue(StreamKeywordTokenizer.TT_WORD == parser.nextToken() + && parser.sval.equals("lE")); + assertTrue(StreamKeywordTokenizer.TT_KEYWORD == parser.nextToken() + && parser.sval.equals("monde")); + + } + + public void testKeyword() throws Exception { + StringReader in = new StringReader("Coucou tOUt TouT lE MONDE"); + StreamKeywordTokenizer parser = new StreamKeywordTokenizer(in); + parser.resetSyntax(); + parser.commentChar('#'); + parser.eolIsSignificant(false); + parser.lowerCaseMode(false); + parser.parseNumbers(); + parser.quoteChar('"'); + parser.slashSlashComments(true); + parser.slashStarComments(true); + parser.whitespaceChars(0, ' '); + parser.wordChars('A', 'Z'); + parser.wordChars('a', 'z'); + + parser.lowerCaseKeyword(false); + parser.addKeyword("Coucou"); + parser.addKeyword("TouT"); + parser.addKeyword("mondE"); + + assertTrue(StreamKeywordTokenizer.TT_KEYWORD == parser.nextToken() + && parser.sval.equals("Coucou")); + assertTrue(StreamKeywordTokenizer.TT_WORD == parser.nextToken() + && parser.sval.equals("tOUt")); + assertTrue(StreamKeywordTokenizer.TT_KEYWORD == parser.nextToken() + && parser.sval.equals("TouT")); + assertTrue(StreamKeywordTokenizer.TT_WORD == parser.nextToken() + && parser.sval.equals("lE")); + assertTrue(StreamKeywordTokenizer.TT_WORD == parser.nextToken() + && parser.sval.equals("MONDE")); + } + +} // StreamKeywordTokenizer + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/StreamKeywordTokenizerTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/StringUtilTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/StringUtilTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/StringUtilTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/StringUtilTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,183 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/******************************************************************************* + * StringUtilTest.java + * + * Created: 7 oct. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import java.awt.Color; +import java.util.Arrays; +import java.util.Locale; + +import org.junit.Test; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; + +public class StringUtilTest { // StringUtilTest + + @Test + public void testSubstring() throws Exception { + String s = "Bonjour le monde"; + String r = StringUtil.substring(s, -5); + assertEquals("monde", r); + + r = StringUtil.substring(s, 7, -5); + assertEquals(" le ", r); + + r = StringUtil.substring(s, 0, s.length()); + assertEquals(s, r); + + r = StringUtil.substring(s, -5, s.length()); + assertEquals("monde", r); + + r = StringUtil.substring("a", 1, -1); + assertEquals("", r); + + r = StringUtil.substring("", 0, -1); + assertEquals("", r); + + } + + @Test + public void testToColor() throws Exception { + Color c; + + c = StringUtil.toColor("#FF55AA"); + assertEquals(c, new Color(255, 85, 170)); + + c = StringUtil.toColor("#FF55AA55"); + assertEquals(c, new Color(255, 85, 170, 85)); + + try { + c = null; + c = StringUtil.toColor("toto"); + assertFalse(true); + } catch (StringUtilException eee) { + assertNull(c); + } + + try { + c = null; + c = StringUtil.toColor("#ZRETJ4040R"); + assertFalse(true); + } catch (StringUtilException eee) { + assertNull(c); + } + } + + @Test + public void testSplit() { + assertTrue(Arrays.equals(StringUtil.split("toto,titi,tutu"), new String[]{"toto", "titi", "tutu"})); + assertTrue(Arrays.equals(StringUtil.split("toto"), new String[]{"toto"})); + assertTrue(Arrays.equals(StringUtil.split(""), new String[0])); + assertTrue(Arrays.equals(StringUtil.split(null), new String[0])); + + String argTest = "toto, titi, titi($tru('roer'), erke), \"t|u(t{u\\\"ti[ti'\", fin"; + String[] arg = StringUtil.split(argTest); + assertEquals(5, arg.length); + + argTest = ""; + arg = StringUtil.split(argTest); + assertEquals(0, arg.length); + + argTest = "tptp"; + arg = StringUtil.split(argTest); + assertEquals(1, arg.length); + + argTest = ",ooo|ooo|o|,ooo'ooo(',ooo-"; + arg = StringUtil.split(argTest, "ooo"); + assertEquals(5, arg.length); + + } + + @Test + public void testConvert() throws Exception { + assertEquals("365d", StringUtil.convertTime(31536000000000000L)); + assertEquals("2d", StringUtil.convertTime(172800000000000L)); + assertEquals("2h", StringUtil.convertTime(7200000000000L)); + assertEquals("2m", StringUtil.convertTime(120000000000L)); + + assertEquals("2s", StringUtil.convertTime(2000000002L)); + assertEquals("2s", StringUtil.convertTime(2000000000L)); + assertEquals("2ms", StringUtil.convertTime(2000000L)); + assertEquals("2ns", StringUtil.convertTime(2L)); + assertEquals("0ns", StringUtil.convertTime(0L)); + + assertEquals("0o", StringUtil.convertMemory(0L)); + assertEquals("2o", StringUtil.convertMemory(2L)); + assertEquals("2Ko", StringUtil.convertMemory(2048L)); + assertEquals("2Mo", StringUtil.convertMemory(2097152L)); + assertEquals("2Mo", StringUtil.convertMemory(2097154L)); + + assertEquals("2Go", StringUtil.convertMemory(2147483648L)); + assertEquals("2To", StringUtil.convertMemory(2199023255552L)); + assertEquals("2000To", StringUtil.convertMemory(2199023255552000L)); + + assertEquals("-2Mo", StringUtil.convertMemory(-2097152L)); + assertEquals("-2Mo", StringUtil.convertMemory(-2097154L)); + + Locale oldLocale = Locale.getDefault(); + // test in french locale + Locale.setDefault(Locale.FRENCH); + assertEquals("2,02s", StringUtil.convertTime(2020000002L)); + assertEquals("2,094Mo", StringUtil.convertMemory(2196152L)); + assertEquals("-2,094Mo", StringUtil.convertMemory(-2196152L)); + + // test in english locale + Locale.setDefault(Locale.ENGLISH); + assertEquals("2.02s", StringUtil.convertTime(2020000002L)); + assertEquals("2.094Mo", StringUtil.convertMemory(2196152L)); + assertEquals("-2.094Mo", StringUtil.convertMemory(-2196152L)); + + // push back previous locale + Locale.setDefault(oldLocale); + } + + @Test + public void testUnaccent() throws Exception { + assertEquals("-aaaeeeeiioouuuc0123456789AAAEEEEIIOOUUUC._", + StringUtil.unaccent("-àâäéèêëîïôöùûüç 0123456789 ÀÂÄÉÈÊËÎÏÔÖÙÛÜÇ._")); + } + + @Test + public void testConvertToConstantName() throws Exception { + assertEquals("YES", StringUtil.convertToConstantName("yes")); + assertEquals("YES", StringUtil.convertToConstantName("*$$?YEs")); + assertEquals("YES", StringUtil.convertToConstantName("_yes!$*_")); + assertEquals("YES", StringUtil.convertToConstantName("_Yes____")); + + assertEquals("YES_OR_NO", StringUtil.convertToConstantName("__yesOrNo_")); + assertEquals("YES_OR_NO", StringUtil.convertToConstantName("Yes-or-!*=No")); + assertEquals("YES_OR_NO", StringUtil.convertToConstantName("_yes__or__no")); + assertEquals("YES_OR_NO", StringUtil.convertToConstantName("_YesOR___No")); + + } + +} // StringUtilTest + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/StringUtilTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/Tbz2UtilTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/Tbz2UtilTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/Tbz2UtilTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/Tbz2UtilTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,214 @@ +/* *##% Lutin utilities library + * Copyright (C) 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +package org.nuiton.util; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.util.List; + +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Test; + +/** + * Tbz2UtilTest.java + * + * @author chatellier + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ +public class Tbz2UtilTest { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static org.apache.commons.logging.Log log = LogFactory + .getLog(Tbz2UtilTest.class); + + public static File I18N_DIR = new File("src" + File.separator + "test" + + File.separator + "resources" + File.separator + "i18n"); + + /** + * Test de decompression d'une archive. + * + * @throws IOException + */ + @Test + public void testUncompress() throws IOException { + + File tbz2File = new File("src" + File.separator + "test" + + File.separator + "resources" + File.separator + "compress", + "i18n.tbz2"); + + Assert.assertTrue(tbz2File.isFile()); + + File uctbz2 = FileUtil.createTempDirectory("testUncompressTbz2", ""); + log.info("uncompress tbz2 " + tbz2File + " in " + uctbz2); + + Tbz2Util.uncompress(tbz2File, uctbz2); + + List<File> dest = FileUtil.getFilteredElements(uctbz2, null, true); + + Assert.assertEquals(13, dest.size()); + + // remove created temp dirs : + FileUtil.deleteRecursively(uctbz2); + } + + /** + * Test de decompression d'une archive. + * + * @throws IOException + */ + @Test + public void testUncompress2() throws IOException { + + File tbz2File = new File("src" + File.separator + "test" + + File.separator + "resources" + File.separator + "compress", + "simulation2.tbz2"); + + Assert.assertTrue(tbz2File.isFile()); + + File uctbz2 = FileUtil.createTempDirectory("testUncompressTbz2", ""); + log.info("uncompress tbz2 " + tbz2File + " in " + uctbz2); + + Tbz2Util.uncompress(tbz2File, uctbz2); + + List<File> dest = FileUtil.getFilteredElements(uctbz2, null, true); + + Assert.assertEquals(254, dest.size()); + + // remove created temp dirs : + FileUtil.deleteRecursively(uctbz2); + } + + /* + * Test to compress directory and uncompress it. + */ + @Test + public void testCompressUncompress() throws IOException { + + File rootDir = new File("src" + File.separator + "test" + + File.separator + "resources" + File.separator + "compress", + "simulation"); + File tbz2File = File.createTempFile("testCompressTbz2-", ".tbz2"); + tbz2File.deleteOnExit(); + log.info("Compress " + rootDir + " in tbz2 file = " + tbz2File); + + Tbz2Util.compress(tbz2File, rootDir); + + Assert.assertTrue(tbz2File.exists()); + Assert.assertTrue(tbz2File.length() > 0); + + // uncompress + File uctbz2 = FileUtil.createTempDirectory("testUncompressTbz2", ""); + Tbz2Util.uncompress(tbz2File, uctbz2); + FileUtil.deleteRecursively(uctbz2); + } + + /* + * Test method for 'org.codelutin.util.ZipUtil.compress(File, File, FileFilter)' + */ + @Test + public void testCompress() throws IOException { + + File tbz2File = File.createTempFile("testCompressTbz2-", ".tbz2"); + tbz2File.deleteOnExit(); + log.info("Compress " + I18N_DIR + " in tbz2 file = " + tbz2File); + + Tbz2Util.compress(tbz2File, I18N_DIR); + + Assert.assertTrue(tbz2File.exists()); + Assert.assertTrue(tbz2File.length() > 0); + } + + @Test + public void testCompressFilter() throws IOException { + + File tbz2File = File.createTempFile("testCompressTbz2Filter-", ".tbz2"); + tbz2File.deleteOnExit(); + log.info("Compress " + I18N_DIR + " in tbz2 file = " + tbz2File); + + FileFilter filter = new FileFilter() { + public boolean accept(File pathname) { + boolean result; + result = !pathname.getPath().contains("fr"); + return result; + } + + }; + + Tbz2Util.compress(tbz2File, I18N_DIR, filter); + + Assert.assertTrue(tbz2File.exists()); + Assert.assertTrue(tbz2File.length() > 0); + } + + /** + * Compress a single file. + * + * @throws IOException + */ + @Test + public void testCompressFile() throws IOException { + File dir = new File(I18N_DIR, "dummy-fr.properties"); + File tbz2File = File.createTempFile("testCompressTbz2File-", ".tbz2"); + tbz2File.deleteOnExit(); + log.info("Compress " + dir + " in tbz2 file = " + tbz2File); + + Tbz2Util.compress(tbz2File, dir); + + Assert.assertTrue(tbz2File.exists()); + Assert.assertTrue(tbz2File.length() > 0); + } + + /** + * Compress a directory and check md5 sum. + * @throws IOException + */ + @Test + public void testCompressMD5() throws IOException { + File tbz2File = File.createTempFile("testCompressTbz2Md5", ".tbz2"); + tbz2File.deleteOnExit(); + log.info("Compress " + I18N_DIR + " in tbz2 file = " + tbz2File); + + FileFilter filter = new FileFilter() { + public boolean accept(File pathname) { + boolean result; + result = !pathname.getPath().contains("svn"); + return result; + } + + }; + + Tbz2Util.compress(tbz2File, I18N_DIR, filter, true); + + Assert.assertTrue(tbz2File.exists()); + Assert.assertTrue(tbz2File.length() > 0); + File md5File = new File(tbz2File.getAbsoluteFile() + ".md5"); + md5File.deleteOnExit(); + Assert.assertTrue(md5File.exists()); + String md5sum = FileUtil.readAsString(md5File); + + // MD5 disabled, files are not same throw svn + // due to svn keywords + //Assert.assertEquals("566f3f4b280eddf8637fe9e4336980a9", md5sum); + } + +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/Tbz2UtilTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Revision Name: svn:mergeinfo + Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/TransparenteReferenceTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/TransparenteReferenceTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/TransparenteReferenceTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/TransparenteReferenceTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,66 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * TransparenteReferenceTest.java + * + * Created: 22 mai 2006 15:41:49 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.util; + +import junit.framework.TestCase; + +import java.util.HashMap; +import java.util.Map; + + +/** @author poussin */ + +public class TransparenteReferenceTest extends TestCase { + + public void testHash() { + Map<TransparenteSoftReference, TransparenteSoftReference> map = new HashMap<TransparenteSoftReference, TransparenteSoftReference>(); + + String key = "key"; + TransparenteSoftReference keyRef = new TransparenteSoftReference<String>(key); + + String value = "value"; + TransparenteSoftReference valueRef = new TransparenteSoftReference<String>(value); + + map.put(keyRef, valueRef); + + + assertEquals(valueRef, map.get(keyRef)); + assertEquals(valueRef.get(), map.get(keyRef).get()); + key = null; + value = null; + + System.gc(); + Thread.yield(); + + assertEquals("value".hashCode(), map.get(keyRef).hashCode()); + } +} + + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/TransparenteReferenceTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/VersionNumberUtilTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/VersionNumberUtilTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/VersionNumberUtilTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/VersionNumberUtilTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,88 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2008 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +/* * + * VersionNumberUtilTest.java + * + * Created: 13 juil. 2004 + * + * @author Benjamin Poussin <poussin@codelutin.com> + * Copyright Code Lutin + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.util; + +import junit.framework.TestCase; + +public class VersionNumberUtilTest extends TestCase { // VersionNumberUtilTest + + public void testSmaller(){ + assertTrue(VersionNumberUtil.smallerThan("1", "2")); + assertFalse(VersionNumberUtil.smallerThan("3", "1")); + + assertFalse(VersionNumberUtil.smallerThan("1.2.3", "1.2.3")); + assertTrue(VersionNumberUtil.smallerThan("1.2.3", "1.2.3.1")); + assertTrue(VersionNumberUtil.smallerThan("1.2.3", "1.3.3.1")); + assertFalse(VersionNumberUtil.smallerThan("1.3.3", "1.2.3.1")); + + assertFalse(VersionNumberUtil.smallerThan("1.2.3", "1.2.3")); + assertFalse(VersionNumberUtil.smallerThan("1.2.3.1", "1.2.3")); + assertFalse(VersionNumberUtil.smallerThan("1.2.3.1", "1.2.3")); + assertTrue(VersionNumberUtil.smallerThan("1.2.3.1", "1.3.3")); + } + + public void testEquals(){ + assertTrue(VersionNumberUtil.equals("10", "10")); + assertFalse(VersionNumberUtil.equals("3", "1")); + + assertTrue(VersionNumberUtil.equals("1.2.3", "1.2.3")); + assertFalse(VersionNumberUtil.equals("1.2.3", "1.2.3.0")); + assertFalse(VersionNumberUtil.equals("1.2.3.0", "1.2.3")); + assertFalse(VersionNumberUtil.equals("1.2.3", "1.2.3.1")); + assertFalse(VersionNumberUtil.equals("1.2.3", "1.3.3.1")); + assertFalse(VersionNumberUtil.equals("1.3.3", "1.2.3.1")); + } + + public void testGreater(){ + assertFalse(VersionNumberUtil.greaterThan("1", "2")); + assertTrue(VersionNumberUtil.greaterThan("3", "1")); + + assertFalse(VersionNumberUtil.greaterThan("1.2.3", "1.2.3")); + assertFalse(VersionNumberUtil.greaterThan("1.2.3", "1.2.3.1")); + assertFalse(VersionNumberUtil.greaterThan("1.2.3", "1.3.3.1")); + assertTrue(VersionNumberUtil.greaterThan("1.3.3", "1.2.3.1")); + + assertFalse(VersionNumberUtil.greaterThan("1.2.3", "1.2.3")); + assertTrue(VersionNumberUtil.greaterThan("1.2.3.1", "1.2.3")); + assertTrue(VersionNumberUtil.greaterThan("1.3.3.1", "1.2.3")); + assertFalse(VersionNumberUtil.greaterThan("1.2.3.1", "1.3.3")); + } + + public void testInc(){ + assertTrue(VersionNumberUtil.equals("1", VersionNumberUtil.inc(null))); + assertTrue(VersionNumberUtil.equals("4", VersionNumberUtil.inc("3"))); + assertTrue(VersionNumberUtil.equals("10", VersionNumberUtil.inc("9"))); + assertTrue(VersionNumberUtil.equals("1.2.4", VersionNumberUtil.inc("1.2.3"))); + assertTrue(VersionNumberUtil.equals("1.2.10", VersionNumberUtil.inc("1.2.9"))); + } + +} // VersionNumberUtilTest + Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/VersionNumberUtilTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Copied: nuitonutil/trunk/src/test/java/org/nuiton/util/ZipUtilTest.java (from rev 1542, nuitonutil/trunk/src/test/java/org/codelutin/util/ZipUtilTest.java) =================================================================== --- nuitonutil/trunk/src/test/java/org/nuiton/util/ZipUtilTest.java (rev 0) +++ nuitonutil/trunk/src/test/java/org/nuiton/util/ZipUtilTest.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -0,0 +1,146 @@ +/* *##% Lutin utilities library + * Copyright (C) 2004 - 2009 CodeLutin + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 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 Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. ##%* */ + +package org.nuiton.util; + +import java.io.File; +import java.io.FileFilter; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Test; + +/** + * ZipUtilTest.java + * + * Created: 24 août 2006 10:47:21 + * + * @author poussin + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ +public class ZipUtilTest { + + /** to use log facility, just put in your code: log.info(\"...\"); */ + private static org.apache.commons.logging.Log log = LogFactory + .getLog(ZipUtilTest.class); + + protected static final File DIR = new File(System.getProperty("java.home"), + "bin"); + + @Test + public void testUncompress() throws IOException { + //File dir = new File(System.getProperty("user.dir")); + File zipFile = File.createTempFile("testCompressZip", ".zip"); + zipFile.deleteOnExit(); + log.info("Compress " + DIR + " in zip file = " + zipFile); + + ZipUtil.compress(zipFile, DIR, null); + + File ucz = FileUtil.createTempDirectory("testUncompressZip", ""); + log.info("uncompress zip " + zipFile + " in " + ucz); + + ZipUtil.uncompress(zipFile, ucz); + + List<File> src = FileUtil.getFilteredElements(DIR, null, true); + List<File> dest = FileUtil.getFilteredElements(ucz, null, true); + + Assert.assertEquals(src.size() + 1, dest.size()); // +1 car il y a le rep lui meme dans dest + + // remove created temp dirs : + FileUtil.deleteRecursively(ucz); + Assert.assertFalse(ucz.isDirectory()); + } + + /* + * Test method for 'org.codelutin.util.ZipUtil.compress(File, File, FileFilter)' + */ + @Test + public void testCompress() throws IOException { + //File dir = new File(System.getProperty("user.dir")); + File zipFile = File.createTempFile("testCompressZip", ".zip"); + zipFile.deleteOnExit(); + log.info("Compress " + DIR + " in zip file = " + zipFile); + + ZipUtil.compress(zipFile, DIR, null); + + Assert.assertTrue(zipFile.exists()); + Assert.assertTrue(0 != zipFile.length()); + } + + @Test + public void testCompressFilter() throws IOException { + //File dir = new File(System.getProperty("user.dir")); + File zipFile = File.createTempFile("testCompressZip", ".zip"); + zipFile.deleteOnExit(); + log.info("Compress " + DIR + " in zip file = " + zipFile); + + FileFilter filter = new FileFilter() { + public boolean accept(File pathname) { + boolean result; + result = !pathname.getPath().contains("/target"); + return result; + } + + }; + + ZipUtil.compress(zipFile, DIR, filter); + + Assert.assertTrue(zipFile.exists()); + Assert.assertTrue(0 != zipFile.length()); + } + + @Test + public void testCompressFile() throws IOException { + File dir = new File(System.getProperty("java.home"), "bin" + + File.separator + "java"); + File zipFile = File.createTempFile("testCompressZip", ".zip"); + zipFile.deleteOnExit(); + log.info("Compress " + dir + " in zip file = " + zipFile); + + ZipUtil.compress(zipFile, dir, null); + + Assert.assertTrue(zipFile.exists()); + Assert.assertTrue(0 != zipFile.length()); + } + + @Test + public void testCompressFileMD5() throws IOException { + File dir = new File(System.getProperty("java.home"), "bin" + + File.separator + "java"); + File zipFile = File.createTempFile("testCompressZip", ".zip"); + zipFile.deleteOnExit(); + log.info("Compress " + dir + " in zip file = " + zipFile); + + Collection<File> files = Collections.singleton(dir); + ZipUtil.compressFiles(zipFile, dir, files, true); + + Assert.assertTrue(zipFile.exists()); + Assert.assertTrue(zipFile.length() > 0); + File md5File = new File(zipFile.getAbsoluteFile() + ".md5"); + md5File.deleteOnExit(); + Assert.assertTrue(md5File.exists()); + Assert.assertTrue(md5File.length() > 0); + } + +} Property changes on: nuitonutil/trunk/src/test/java/org/nuiton/util/ZipUtilTest.java ___________________________________________________________________ Name: svn:keywords + Author Date Id Revision Name: svn:mergeinfo + Name: svn:eol-style + native Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/Abundances.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/Abundances.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/Abundances.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -5,7 +5,7 @@ import java.io.Writer; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.codelutin.math.matrix.*; import scripts.ResultName; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/Biomasses.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/Biomasses.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/Biomasses.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -1,6 +1,6 @@ package exports; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/CapturesNombre.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/CapturesNombre.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/CapturesNombre.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -1,6 +1,6 @@ package exports; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import java.io.Writer; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/CapturesPoids.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/CapturesPoids.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/CapturesPoids.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -1,6 +1,6 @@ package exports; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import java.io.Writer; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/CellsDefinition.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/CellsDefinition.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/CellsDefinition.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -6,7 +6,7 @@ import java.io.Writer; import java.util.List; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.codelutin.math.matrix.*; import fr.ifremer.isisfish.entities.*; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/EffortsMetier.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/EffortsMetier.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/EffortsMetier.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -1,6 +1,6 @@ package exports; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/MetierZone.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/MetierZone.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/MetierZone.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -5,7 +5,7 @@ import java.io.Writer; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.codelutin.math.matrix.*; import scripts.ResultName; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/NonActivite.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/NonActivite.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/NonActivite.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -1,6 +1,6 @@ package exports; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/OwnerMargin.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/OwnerMargin.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/OwnerMargin.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -1,6 +1,6 @@ package exports; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/RegionDefinition.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/RegionDefinition.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/RegionDefinition.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -5,7 +5,7 @@ import java.io.Writer; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.codelutin.math.matrix.*; import fr.ifremer.isisfish.entities.*; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/RejetsNombre.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/RejetsNombre.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/RejetsNombre.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -1,6 +1,6 @@ package exports; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import java.io.Writer; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/RejetsPoids.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/RejetsPoids.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/RejetsPoids.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -1,6 +1,6 @@ package exports; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import java.io.Writer; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/VesselMargin.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/VesselMargin.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/VesselMargin.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -1,6 +1,6 @@ package exports; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/exports/ZonesDefinition.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/exports/ZonesDefinition.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/exports/ZonesDefinition.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -6,7 +6,7 @@ import java.io.Writer; import java.util.List; -import static org.codelutin.i18n.I18n._; +import static org.nuiton.i18n.I18n._; import org.codelutin.math.matrix.*; import fr.ifremer.isisfish.entities.*; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/scripts/GravityModel.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/scripts/GravityModel.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/scripts/GravityModel.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -31,7 +31,7 @@ package scripts; -import static org.codelutin.i18n.I18n.n_; +import static org.nuiton.i18n.I18n.n_; import java.util.Collection; import java.util.List; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/scripts/ResultName.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/scripts/ResultName.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/scripts/ResultName.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -31,7 +31,7 @@ package scripts; -import static org.codelutin.i18n.I18n.n_; +import static org.nuiton.i18n.I18n.n_; import fr.ifremer.isisfish.util.Doc; // pour pouvoir afficher une aide contextuelle (BUG#1605) Modified: nuitonutil/trunk/src/test/resources/compress/simulation/scripts/SiMatrix.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/scripts/SiMatrix.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/scripts/SiMatrix.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -31,7 +31,7 @@ package scripts; -import static org.codelutin.i18n.I18n.n_; +import static org.nuiton.i18n.I18n.n_; import java.util.ArrayList; import java.util.Collection; Modified: nuitonutil/trunk/src/test/resources/compress/simulation/simulators/DefaultSimulator.java =================================================================== --- nuitonutil/trunk/src/test/resources/compress/simulation/simulators/DefaultSimulator.java 2009-05-14 05:39:58 UTC (rev 1547) +++ nuitonutil/trunk/src/test/resources/compress/simulation/simulators/DefaultSimulator.java 2009-05-14 05:40:24 UTC (rev 1548) @@ -31,8 +31,8 @@ package simulators; -import static org.codelutin.i18n.I18n._; -import static org.codelutin.i18n.I18n.n_; +import static org.nuiton.i18n.I18n._; +import static org.nuiton.i18n.I18n.n_; import java.util.List;
participants (1)
-
tchemit@users.labs.libre-entreprise.org