Nuiton-utils-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
May 2011
- 4 participants
- 14 discussions
26 May '11
Author: echatellier
Date: 2011-05-26 18:00:41 +0200 (Thu, 26 May 2011)
New Revision: 2147
Url: http://nuiton.org/repositories/revision/nuiton-utils/2147
Log:
Add big warning about split method limit (buggy with special chars).
Modified:
trunk/nuiton-utils/src/main/java/org/nuiton/util/StringUtil.java
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/StringUtil.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/StringUtil.java 2011-05-15 12:18:55 UTC (rev 2146)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/StringUtil.java 2011-05-26 16:00:41 UTC (rev 2147)
@@ -5,7 +5,7 @@
* $Id$
* $HeadURL$
* %%
- * Copyright (C) 2004 - 2010 CodeLutin
+ * Copyright (C) 2004 - 2011 CodeLutin, Chatellier Eric
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
@@ -23,17 +23,6 @@
* #L%
*/
-/* *
- * StringUtil.java
- *
- * Created: Sun Apr 14 2002
- *
- * @author POUSSIN Benjamin <bpoussin(a)free.fr>
- * Copyright Code Lutin
- * @version $Revision$
- *
- * Mise a jour: $Date$
- * par : */
package org.nuiton.util;
import java.awt.Color;
@@ -231,6 +220,11 @@
* this method count the number of open char end close char to split
* correctly argument
*
+ * WARNING: cette method ne fonctionne pas si le contenu contient
+ * des carateres utilisé pour le parsing et présent une seule fois.
+ * Par exemple: "l'idenfiant" contient ' qui empeche totalement le
+ * parsing de fonctionner.
+ *
* @param args string to split
* @param separator separator use to split string
* @return array of string
@@ -241,9 +235,14 @@
/**
- * Use to split string array representation in array according with swixat
- * seperator list
- *
+ * Use to split string array representation in array according with ',' as
+ * default separator.
+ *
+ * WARNING: cette method ne fonctionne pas si le contenu contient
+ * des carateres utilisé pour le parsing et présent une seule fois.
+ * Par exemple: "l'idenfiant" contient ' qui empeche totalement le
+ * parsing de fonctionner.
+ *
* @param stringList string that represent array
* @return array with length > 0 if listAsString != null or null
*/
@@ -260,6 +259,11 @@
* this method count the number of open char end close char to split
* correctly argument
*
+ * WARNING: cette method ne fonctionne pas si le contenu contient
+ * des carateres utilisé pour le parsing et présent une seule fois.
+ * Par exemple: "l'idenfiant" contient ' qui empeche totalement le
+ * parsing de fonctionner.
+ *
* @param openingChars list of opening caracteres
* @param closingChars list of closing caracteres
* @param args string to split
1
0
r2146 - in trunk: . nuiton-profiling nuiton-utils nuiton-validator
by hudson@users.nuiton.org 15 May '11
by hudson@users.nuiton.org 15 May '11
15 May '11
Author: hudson
Date: 2011-05-15 14:18:55 +0200 (Sun, 15 May 2011)
New Revision: 2146
Url: http://nuiton.org/repositories/revision/nuiton-utils/2146
Log:
[maven-release-plugin] prepare for next development iteration
Modified:
trunk/nuiton-profiling/pom.xml
trunk/nuiton-utils/pom.xml
trunk/nuiton-validator/pom.xml
trunk/pom.xml
Modified: trunk/nuiton-profiling/pom.xml
===================================================================
--- trunk/nuiton-profiling/pom.xml 2011-05-15 12:18:54 UTC (rev 2145)
+++ trunk/nuiton-profiling/pom.xml 2011-05-15 12:18:55 UTC (rev 2146)
@@ -33,7 +33,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-utils-parent</artifactId>
- <version>2.2</version>
+ <version>2.2.1-SNAPSHOT</version>
</parent>
<artifactId>nuiton-profiling</artifactId>
Modified: trunk/nuiton-utils/pom.xml
===================================================================
--- trunk/nuiton-utils/pom.xml 2011-05-15 12:18:54 UTC (rev 2145)
+++ trunk/nuiton-utils/pom.xml 2011-05-15 12:18:55 UTC (rev 2146)
@@ -33,7 +33,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-utils-parent</artifactId>
- <version>2.2</version>
+ <version>2.2.1-SNAPSHOT</version>
</parent>
<artifactId>nuiton-utils</artifactId>
Modified: trunk/nuiton-validator/pom.xml
===================================================================
--- trunk/nuiton-validator/pom.xml 2011-05-15 12:18:54 UTC (rev 2145)
+++ trunk/nuiton-validator/pom.xml 2011-05-15 12:18:55 UTC (rev 2146)
@@ -33,7 +33,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-utils-parent</artifactId>
- <version>2.2</version>
+ <version>2.2.1-SNAPSHOT</version>
</parent>
<artifactId>nuiton-validator</artifactId>
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2011-05-15 12:18:54 UTC (rev 2145)
+++ trunk/pom.xml 2011-05-15 12:18:55 UTC (rev 2146)
@@ -37,7 +37,7 @@
</parent>
<artifactId>nuiton-utils-parent</artifactId>
- <version>2.2</version>
+ <version>2.2.1-SNAPSHOT</version>
<modules>
<module>nuiton-utils</module>
@@ -220,12 +220,12 @@
<!-- Source control management. -->
<scm>
<connection>
- scm:svn:http://svn.nuiton.org/svn/nuiton-utils/tags/nuiton-utils-2.2
+ scm:svn:http://svn.nuiton.org/svn/nuiton-utils/trunk
</connection>
<developerConnection>
- scm:svn:http://svn.nuiton.org/svn/nuiton-utils/tags/nuiton-utils-2.2
+ scm:svn:http://svn.nuiton.org/svn/nuiton-utils/trunk
</developerConnection>
- <url>http://www.nuiton.org/repositories/browse/nuiton-utils/tags/nuiton-utils-2.2</url>
+ <url>http://www.nuiton.org/repositories/browse/nuiton-utils/trunk</url>
</scm>
</project>
1
0
Author: hudson
Date: 2011-05-15 14:18:54 +0200 (Sun, 15 May 2011)
New Revision: 2145
Url: http://nuiton.org/repositories/revision/nuiton-utils/2145
Log:
[maven-release-plugin] copy for tag nuiton-utils-2.2
Added:
tags/nuiton-utils-2.2/
Property changes on: tags/nuiton-utils-2.2
___________________________________________________________________
Added: svn:ignore
+ target
velocity.log
maven.log
.eclipse
.classpath
*.iml
*.ipr
*.iws
.settings
.project
testdir
Added: svn:mergeinfo
+
1
0
r2144 - in trunk: . nuiton-profiling nuiton-utils nuiton-validator
by hudson@users.nuiton.org 15 May '11
by hudson@users.nuiton.org 15 May '11
15 May '11
Author: hudson
Date: 2011-05-15 14:18:53 +0200 (Sun, 15 May 2011)
New Revision: 2144
Url: http://nuiton.org/repositories/revision/nuiton-utils/2144
Log:
[maven-release-plugin] prepare release nuiton-utils-2.2
Modified:
trunk/nuiton-profiling/pom.xml
trunk/nuiton-utils/pom.xml
trunk/nuiton-validator/pom.xml
trunk/pom.xml
Modified: trunk/nuiton-profiling/pom.xml
===================================================================
--- trunk/nuiton-profiling/pom.xml 2011-05-15 11:13:57 UTC (rev 2143)
+++ trunk/nuiton-profiling/pom.xml 2011-05-15 12:18:53 UTC (rev 2144)
@@ -33,7 +33,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-utils-parent</artifactId>
- <version>2.2-SNAPSHOT</version>
+ <version>2.2</version>
</parent>
<artifactId>nuiton-profiling</artifactId>
Modified: trunk/nuiton-utils/pom.xml
===================================================================
--- trunk/nuiton-utils/pom.xml 2011-05-15 11:13:57 UTC (rev 2143)
+++ trunk/nuiton-utils/pom.xml 2011-05-15 12:18:53 UTC (rev 2144)
@@ -33,7 +33,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-utils-parent</artifactId>
- <version>2.2-SNAPSHOT</version>
+ <version>2.2</version>
</parent>
<artifactId>nuiton-utils</artifactId>
Modified: trunk/nuiton-validator/pom.xml
===================================================================
--- trunk/nuiton-validator/pom.xml 2011-05-15 11:13:57 UTC (rev 2143)
+++ trunk/nuiton-validator/pom.xml 2011-05-15 12:18:53 UTC (rev 2144)
@@ -33,7 +33,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>nuiton-utils-parent</artifactId>
- <version>2.2-SNAPSHOT</version>
+ <version>2.2</version>
</parent>
<artifactId>nuiton-validator</artifactId>
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2011-05-15 11:13:57 UTC (rev 2143)
+++ trunk/pom.xml 2011-05-15 12:18:53 UTC (rev 2144)
@@ -37,7 +37,7 @@
</parent>
<artifactId>nuiton-utils-parent</artifactId>
- <version>2.2-SNAPSHOT</version>
+ <version>2.2</version>
<modules>
<module>nuiton-utils</module>
@@ -220,12 +220,12 @@
<!-- Source control management. -->
<scm>
<connection>
- scm:svn:http://svn.nuiton.org/svn/nuiton-utils/trunk
+ scm:svn:http://svn.nuiton.org/svn/nuiton-utils/tags/nuiton-utils-2.2
</connection>
<developerConnection>
- scm:svn:http://svn.nuiton.org/svn/nuiton-utils/trunk
+ scm:svn:http://svn.nuiton.org/svn/nuiton-utils/tags/nuiton-utils-2.2
</developerConnection>
- <url>http://www.nuiton.org/repositories/browse/nuiton-utils/trunk</url>
+ <url>http://www.nuiton.org/repositories/browse/nuiton-utils/tags/nuiton-utils-2.2</url>
</scm>
</project>
1
0
r2143 - in trunk/nuiton-utils/src: main/java/org/nuiton/util main/java/org/nuiton/util/beans main/java/org/nuiton/util/converter main/java/org/nuiton/util/rmi test/java/org/nuiton/util
by tchemit@users.nuiton.org 15 May '11
by tchemit@users.nuiton.org 15 May '11
15 May '11
Author: tchemit
Date: 2011-05-15 13:13:57 +0200 (Sun, 15 May 2011)
New Revision: 2143
Url: http://nuiton.org/repositories/revision/nuiton-utils/2143
Log:
fix javadocs
reformat some codes
Added:
trunk/nuiton-utils/src/main/java/org/nuiton/util/package-info.java
Removed:
trunk/nuiton-utils/src/main/java/org/nuiton/util/package.html
Modified:
trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/LoggingPatternFormatter.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/ObjectUtil.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/Resource.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/ResourceResolver.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/StringUtil.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/converter/FormatMap.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/package-info.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/MD5InputStreamTest.java
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -1070,7 +1070,7 @@
hash = value.hashCode();
}
- CacheItem cacheItem = cacheOption.get(cacheKey);
+ CacheItem<?> cacheItem = cacheOption.get(cacheKey);
// compute value if value don't exist in cacheOption or
// if it's modified since last computation
if (cacheItem == null || cacheItem.hash != hash) {
@@ -1084,11 +1084,11 @@
list.add(v);
}
}
- cacheItem = new CacheItem(list, hash);
+ cacheItem = new CacheItem<List<T>>(list, hash);
} else {
// prefer use our converter method (auto-register more converters)
T v = ConverterUtil.convert(clazz, value);
- cacheItem = new CacheItem(v, hash);
+ cacheItem = new CacheItem<T>(v, hash);
}
// add new item to the cache
cacheOption.put(cacheKey, cacheItem);
@@ -1104,8 +1104,8 @@
* Help to convert value to list of object. If no option for this key
* empty List is returned finaly
*
- * @param key
- * @return
+ * @param key the key of searched option
+ * @return value of option list
*/
public OptionList getOptionAsList(String key) {
String value = getOption(key);
@@ -1135,12 +1135,17 @@
*
* @param key the option's key
* @return Properties object loaded with value pointed by file
- * @throws java.io.IOException if exception occured on read file
+ * @throws IOException if exception occured on read file
*/
public Properties getOptionAsProperties(String key) throws IOException {
File file = getOptionAsFile(key);
Properties prop = new RecursiveProperties();
- prop.load(new FileReader(file));
+ FileReader reader = new FileReader(file);
+ try {
+ prop.load(reader);
+ } finally {
+ reader.close();
+ }
return prop;
}
@@ -2110,7 +2115,10 @@
}
protected <T> List<T> convertListOption(Class<T> type) {
- List<T> result= (List<T>) config.convertOption(type, key, value, true);
+ List<T> result= (List<T>) config.convertOption(type, key,
+ value,
+ true
+ );
return result;
}
/**
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/LoggingPatternFormatter.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/LoggingPatternFormatter.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/LoggingPatternFormatter.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -216,7 +216,7 @@
if (argumentClass == null)
throw new LoggingException("Erreur dans le pattern '" + code
+ "' inconnu");
- Argument argument = null;
+ Argument argument;
try {
argument = (Argument) argumentClass.newInstance();
} catch (InstantiationException eee) {
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/ObjectUtil.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/ObjectUtil.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/ObjectUtil.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -98,10 +98,15 @@
* @return new instance
* @throws IllegalArgumentException if something is wrong during instanciation
*/
- static public <E> E newInstance(Class<E> clazz, Collection args, boolean nullIfMissing) {
- Constructor<E>[] constructors = (Constructor<E>[])clazz.getConstructors();
+ static public <E> E newInstance(Class<E> clazz,
+ Collection<?> args,
+ boolean nullIfMissing) {
+ Constructor<E>[] constructors =
+ (Constructor<E>[])clazz.getConstructors();
if (constructors.length != 1) {
- throw new IllegalArgumentException(_("nuitonutil.error.class.with.more.than.one.constructor", clazz));
+ throw new IllegalArgumentException(
+ _("nuitonutil.error.class.with.more.than.one.constructor",
+ clazz));
}
// copy collection into modifiable list to add new object
@@ -127,26 +132,32 @@
}
/**
- * Permet de matcher un type d'agument attendu clazz parmi un ensemble
+ * Permet de matcher un type d'argument attendu clazz parmi un ensemble
* possible de candidat. Les candidats peuvent etre des classes qu'il faudra
* instancier pour satisfaire le type demande.
*
- * @param clazz
- * @param args
- * @param nullIfMissing
- * @return
+ * @param clazz le type recherché
+ * @param args la liste des arguments ou des types
+ * @param nullIfMissing pour retourner nulle si l'argument n'est pas trouvé
+ * @return le type d'argument trouvé
*/
- static protected Object choiceArgument(Class<?> clazz, List args, boolean nullIfMissing) {
+ static protected Object choiceArgument(Class<?> clazz,
+ List args,
+ boolean nullIfMissing) {
Object result = null;
boolean addResult = false;
for (Object o : args) {
if (o != null) {
- if (o instanceof Class<?> && clazz.isAssignableFrom((Class<?>) o)) {
- // cas on l'on trouve une class dans arg qui une fois instancier convient
+ if (o instanceof Class<?> &&
+ clazz.isAssignableFrom((Class<?>) o)) {
+
+ // cas on l'on trouve une class dans arg qui une fois
+ // instancier convient
result = newInstance((Class<?>) o, args, nullIfMissing);
addResult = true;
break;
} else if (clazz.isInstance(o)) {
+
// cas on l'on retrouve un objet assignable pour ce type
result = o;
break;
@@ -164,7 +175,8 @@
// si on ne retrouve rien, result est reste a null
if (result == null && !nullIfMissing) {
throw new IllegalArgumentException(_(
- _("nuitonutil.error.unfound.assignable.argument", clazz, args)));
+ _("nuitonutil.error.unfound.assignable.argument",
+ clazz, args)));
}
return result;
}
@@ -186,11 +198,16 @@
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
- public static Object create(String classnameAndProperties) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+ 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;
+ String classname;
if (p != -1) {
String tmp = classnameAndProperties.substring(p + 1, l);
properties = StringUtil.split(tmp, ",");
@@ -198,16 +215,19 @@
} else {
classname = classnameAndProperties;
}
- Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(classname);
- Object o = clazz.newInstance();
+ ClassLoader loader = Thread.currentThread().getContextClassLoader();
+ Class<?> clazz = loader.loadClass(classname);
+ Object o = clazz.getConstructor().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) == '"') {
+ 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) == '\'') {
+ } else if (propValue.charAt(0) == '\'' &&
+ propValue.charAt(propValue.length()-1) == '\'') {
propValue = propValue.substring(1, propValue.length()-1);
}
BeanUtils.setProperty(o, propName, propValue);
@@ -345,13 +365,16 @@
}
/**
- * Get all methods with name given in argument without check parameters
- * @param clazz
+ * Get all methods with name given in argument without check parameters.
+ *
+ * @param clazz where to search method
* @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) {
+ public static List<Method> getMethod(Class<?> clazz,
+ String methodName,
+ boolean ignoreCase) {
List<Method> result = new ArrayList<Method>();
Method[] methods = clazz.getMethods();
@@ -369,7 +392,7 @@
int p = constructorWithParams.indexOf('(');
int l = constructorWithParams.lastIndexOf(')');
String [] params = null;
- String classname = null;
+ String classname;
if (p != -1) {
String tmp = constructorWithParams.substring(p + 1, l);
params = StringUtil.split(tmp, ",");
@@ -381,6 +404,7 @@
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
@@ -419,19 +443,26 @@
}
if (c.isVarArgs()) {
- Class<?> argClazz = types[last]; // get var args type
- argClazz = argClazz.getComponentType(); // get array component type
+
+ // get var args type
+ Class<?> argClazz = types[last];
+
+ // get array component type
+ argClazz = argClazz.getComponentType();
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()));
+ parameters[last] =
+ tmp.toArray((Object[]) Array.newInstance(
+ argClazz, tmp.size()));
}
if (log.isDebugEnabled()) {
- log.debug(_("nuitonutil.debug.objectutil.create", clazz, Arrays.toString(parameters)));
+ log.debug(_("nuitonutil.debug.objectutil.create",
+ clazz, Arrays.toString(parameters)));
}
T result = c.newInstance(parameters);
@@ -443,7 +474,8 @@
}
}
}
- throw new IllegalArgumentException(_("nuitonutil.debug.objectutil.instantiate",
+ throw new IllegalArgumentException(
+ _("nuitonutil.debug.objectutil.instantiate",
clazz, Arrays.toString(params)));
}
@@ -458,12 +490,15 @@
* @return list of constructors
*/
@SuppressWarnings("unchecked")
- public static <T> List<Constructor<T>> getConstructor(Class<T> clazz, int paramNumber) {
+ 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();
+ Constructor<T>[] constructors =
+ (Constructor<T>[])clazz.getConstructors();
for (Constructor<T> c : constructors) {
if (paramNumber < 0 ||
- c.isVarArgs() && c.getParameterTypes().length <= paramNumber - 1 ||
+ c.isVarArgs() &&
+ c.getParameterTypes().length <= paramNumber - 1 ||
c.getParameterTypes().length == paramNumber) {
result.add(c);
}
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/Resource.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/Resource.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/Resource.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -66,7 +66,7 @@
* Created: 5 août 2003
*
* @author bpoussin <poussin(a)codelutin.com>
- * $Id$
+ * $Id$
*/
public class Resource { // Resource
@@ -98,7 +98,7 @@
public static void addClassLoader(ClassLoader classLoader, URL url) {
try {
Method method = URLClassLoader.class.getDeclaredMethod("addURL",
- new Class[]{URL.class});
+ new Class[]{URL.class});
method.setAccessible(true);
method.invoke(classLoader, url);
} catch (Exception eee) {
@@ -175,7 +175,7 @@
/**
* Retourner la liste des fichiers du classLoader. Ces fichiers doivent
* correspondre au pattern donne.
- *
+ * <p/>
* Utile par defaut {@link ClassLoader#getSystemClassLoader()}.
*
* @param pattern le nom du fichier a extraire du fichier compressé ou
@@ -244,8 +244,7 @@
String fileName;
try {
fileName = urlFile.toURI().getPath();
- }
- catch (Exception e) {
+ } catch (Exception e) {
if (log.isWarnEnabled()) {
log.warn(e);
}
@@ -293,8 +292,8 @@
}
if (log.isInfoEnabled()) {
log.info("search URLs pattern: " + pattern + " in "
- + arrayURL.length + " urls in "
- + StringUtil.convertTime(System.nanoTime() - t0));
+ + arrayURL.length + " urls in "
+ + StringUtil.convertTime(System.nanoTime() - t0));
}
return urlList;
}
@@ -462,20 +461,20 @@
if (log.isTraceEnabled()) {
log.trace("directory: " + repository + " name: "
- + name);
+ + name);
}
// cas de recursivite : repertoire dans un repertoire
if (file.exists() && file.isDirectory()) {
urlList.addAll(getURLsFromDirectory(file,
- pattern));
+ 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);
+ + url);
}
urlList.add(url);
}
@@ -539,7 +538,7 @@
* @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é.
- * @deprecated since 2.2, use now the method {@link ObjectUtil#getPrimitiveClass(Class)}
+ * @deprecated since 2.2, use now the method {@link ObjectUtil#getPrimitiveClass(Class)}
*/
@Deprecated
public static Class getPrimitiveClass(Class clazz) {
@@ -585,10 +584,10 @@
/**
* Return true if {@code str} is a pattern (contains * or ?).
- *
+ *
* @param str str to test
- * @since 2.2
* @return {@code true} if {@code str} is a pattern, {@code false} otherwise
+ * @since 2.2
*/
protected static boolean isPattern(String str) {
return str.indexOf('*') != -1 || str.indexOf('?') != -1;
@@ -596,10 +595,10 @@
/**
* Find pattern resouces in {@link ClassLoader#getSystemClassLoader()}.
- *
+ *
* @param pattern java regex style pattern to find
* @return url list found
- * @throws IOException
+ * @throws IOException if any IO problem while seeking resources
* @since 2.2
*/
public static List<URL> getResources(String pattern) throws IOException {
@@ -608,11 +607,11 @@
/**
* Find pattern resouces in classloader.
- *
- * @param pattern java regex style pattern to find
+ *
+ * @param pattern java regex style pattern to find
* @param classLoader classLoader
* @return url list found
- * @throws IOException
+ * @throws IOException if any IO problem while seeking resources
* @since 2.2
*/
public static List<URL> getResources(String pattern,
@@ -625,8 +624,7 @@
if (isPattern(pattern)) {
urlList = getPatternRessources(pattern, classLoader);
- }
- else {
+ } else {
urlList = new HashList<URL>();
Enumeration<URL> resourceUrls = classLoader.getResources(pattern);
while (resourceUrls.hasMoreElements()) {
@@ -639,11 +637,13 @@
}
/**
- *
- * @param pattern
- * @param classLoader
- * @return
- * @throws IOException
+ * Obtain some resources from a pattern using a specific class loader to
+ * seel resources.
+ *
+ * @param pattern pattern of searched resources
+ * @param classLoader class loader which responsible to seek resources
+ * @return list of resources found
+ * @throws IOException if any IO problem while scanning resources
* @since 2.2
*/
protected static List<URL> getPatternRessources(String pattern,
@@ -657,7 +657,8 @@
// /META-INF/persistence/*.xml -> /META-INF/persistence/
int prefixEnd = pattern.indexOf(":") + 1;
int rootDirEnd = pattern.length();
- while (rootDirEnd > prefixEnd && isPattern(pattern.substring(prefixEnd, rootDirEnd))) {
+ while (rootDirEnd > prefixEnd &&
+ isPattern(pattern.substring(prefixEnd, rootDirEnd))) {
rootDirEnd = pattern.lastIndexOf('/', rootDirEnd - 2) + 1;
}
if (rootDirEnd == 0) {
@@ -666,7 +667,8 @@
String rootDirPath = pattern.substring(0, rootDirEnd);
String subPattern = pattern.substring(rootDirPath.length());
- Enumeration<URL> rootDirResources = classLoader.getResources(rootDirPath);
+ Enumeration<URL> rootDirResources =
+ classLoader.getResources(rootDirPath);
while (rootDirResources.hasMoreElements()) {
URL rootDirResource = rootDirResources.nextElement();
@@ -677,8 +679,7 @@
log.debug("jar to search " + rootDirResource);
}
urlList.addAll(doFindPathMatchingJarResources(rootDirResource, subPattern));
- }
- else {
+ } else {
urlList.addAll(doFindMatchingFileSystemResources(rootDirResource, subPattern));
}
}
@@ -688,10 +689,10 @@
/**
* Test if an url detnoe a jar file.
- *
+ * <p/>
* Code taken from spring source code :
- * org.springframework.core.io.support.PathMatchingResourcePatternResolver
- *
+ * org.springframework.core.io.support.PathMatchingResourcePatternResolver
+ *
* @param url url to test
* @return true if url denote a jar file
* @since 2.2
@@ -702,16 +703,16 @@
"zip".equals(protocol) ||
"wsjar".equals(protocol);
}
-
+
/**
* Find all resources in jar files that match the given location pattern
* via the Java Regex style Matcher.
- *
+ * <p/>
* Code taken from spring source code :
- * org.springframework.core.io.support.PathMatchingResourcePatternResolver
- *
+ * org.springframework.core.io.support.PathMatchingResourcePatternResolver
+ *
* @param rootDirResource the root directory as Resource
- * @param subPattern the sub pattern to match (below the root directory)
+ * @param subPattern the sub pattern to match (below the root directory)
* @return the Set of matching Resource instances
* @throws IOException in case of I/O errors
* @see JarURLConnection
@@ -734,8 +735,7 @@
jarFileUrl = jarCon.getJarFileURL().toExternalForm();
JarEntry jarEntry = jarCon.getJarEntry();
rootEntryPath = jarEntry != null ? jarEntry.getName() : "";
- }
- else {
+ } else {
// No JarURLConnection -> need to resort to URL file parsing.
// We'll assume URLs of the format "jar:path!/entry", with the protocol
// being arbitrary as long as following the entry format.
@@ -748,12 +748,10 @@
//jarFile = getJarFile(jarFileUrl);
if (jarFileUrl.startsWith("file:")) {
jarFile = new JarFile(jarFileUrl.substring("file:".length()));
- }
- else {
+ } else {
jarFile = new JarFile(jarFileUrl);
}
- }
- else {
+ } else {
jarFile = new JarFile(urlFile);
jarFileUrl = urlFile;
rootEntryPath = "";
@@ -783,8 +781,7 @@
}
}
return result;
- }
- finally {
+ } finally {
// Close jar file, but only if freshly obtained -
// not from JarURLConnection, which might cache the file reference.
if (newJarFile) {
@@ -792,16 +789,16 @@
}
}
}
-
+
/**
* Find all resources in the file system that match the given location pattern
* via the Java style matcher.
- *
+ * <p/>
* Code taken from spring source code :
- * org.springframework.core.io.support.PathMatchingResourcePatternResolver
- *
+ * org.springframework.core.io.support.PathMatchingResourcePatternResolver
+ *
* @param rootDirResource the root directory as Resource
- * @param subPattern the sub pattern to match (below the root directory)
+ * @param subPattern the sub pattern to match (below the root directory)
* @return the Set of matching Resource instances
* @throws IOException in case of I/O errors
* @see #retrieveMatchingFiles(File, String)
@@ -810,13 +807,12 @@
protected static List<URL> doFindMatchingFileSystemResources(URL rootDirResource,
String subPattern)
throws IOException {
-
+
File rootDir;
try {
rootDir = new File(rootDirResource.toURI().getSchemeSpecificPart());
rootDir = rootDir.getAbsoluteFile();
- }
- catch (URISyntaxException ex) {
+ } catch (URISyntaxException ex) {
return Collections.emptyList();
}
return retrieveMatchingFiles(rootDir, subPattern);
@@ -825,13 +821,13 @@
/**
* Retrieve files that match the given path pattern,
* checking the given directory and its subdirectories.
- *
+ * <p/>
* Code taken from spring source code :
- * org.springframework.core.io.support.PathMatchingResourcePatternResolver
- *
+ * org.springframework.core.io.support.PathMatchingResourcePatternResolver
+ *
* @param rootDir the directory to start from
* @param pattern the pattern to match against,
- * relative to the root directory
+ * relative to the root directory
* @return the Set of matching File instances
* @throws IOException if directory contents could not be retrieved
* @since 2.2
@@ -858,18 +854,18 @@
doRetrieveMatchingFiles(fullPattern, rootDir, result);
return result;
}
-
+
/**
* Recursively retrieve files that match the given pattern,
* adding them to the given result list.
- *
+ * <p/>
* Code taken from spring source code :
- * org.springframework.core.io.support.PathMatchingResourcePatternResolver
- *
+ * org.springframework.core.io.support.PathMatchingResourcePatternResolver
+ *
* @param fullPattern the pattern to match against,
- * with preprended root directory path
- * @param dir the current directory
- * @param result the Set of matching File instances to add to
+ * with preprended root directory path
+ * @param dir the current directory
+ * @param result the Set of matching File instances to add to
* @throws IOException if directory contents could not be retrieved
* @since 2.2
*/
@@ -878,7 +874,7 @@
List<URL> result) throws IOException {
if (log.isDebugEnabled()) {
log.debug("Searching directory [" + dir.getAbsolutePath() +
- "] for files matching pattern [" + fullPattern + "]");
+ "] for files matching pattern [" + fullPattern + "]");
}
File[] dirContents = dir.listFiles();
if (dirContents == null) {
@@ -895,10 +891,9 @@
if (!content.canRead()) {
if (log.isDebugEnabled()) {
log.debug("Skipping subdirectory [" + dir.getAbsolutePath() +
- "] because the application is not allowed to read the directory");
+ "] because the application is not allowed to read the directory");
}
- }
- else {
+ } else {
doRetrieveMatchingFiles(fullPattern, content, result);
}
}
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/ResourceResolver.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/ResourceResolver.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/ResourceResolver.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -157,7 +157,7 @@
// if URI
Matcher matcher = HREF_PATTERN.matcher(href);
if (matcher.matches()) {
- String protocol = matcher.group(1);
+// String protocol = matcher.group(1);
String path = matcher.group(2);
// try look only with the filename
// this is the last chance to find something :)
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/StringUtil.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/StringUtil.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/StringUtil.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -186,9 +186,9 @@
* example:
* <li> substring("tatetitotu", -4) => totu
*
- * @param s
+ * @param s the string to substring
* @param begin if begin < 0 then begin start at end of string - begin
- * @return
+ * @return the result of substring
*/
static public String substring(String s, int begin) {
String result = substring(s, begin, s.length());
@@ -201,10 +201,10 @@
* example:
* <li> substring("tatetitotu", -4, -2) => to
*
- * @param s
+ * @param s the string to substring
* @param begin if begin < 0 then begin start at end of string - begin
* @param end if end < 0 then end start at end of string - end
- * @return
+ * @return the result of substring
*/
static public String substring(String s, int begin, int end) {
if (begin < 0) {
@@ -693,7 +693,7 @@
* @throws IllegalStateException if could not found algorithm SHA1
*/
public static String encodeSHA1(String toEncode) {
- String result = null;
+ String result;
try {
MessageDigest sha1Md = MessageDigest.getInstance("SHA-1");
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -36,20 +36,21 @@
* This api permits to some object properties from an object to another one.
* </p>
* <h2>Obtain a binder</h2>
- * A {@link Binder} contains a safe model named {@link Binder.BinderModel} which knows
+ * A {@link org.nuiton.util.beans.Binder} contains a safe model named
+ * {@link org.nuiton.util.beans.Binder.BinderModel} which knows
* all properties that can be copied.
* <br/>
- * To use this api, you have only to get a {@link Binder} object from the
- * {@link BinderFactory} like this :
+ * To use this api, you have only to get a {@link org.nuiton.util.beans.Binder}
+ * object from the {@link org.nuiton.util.beans.BinderFactory} like this :
* <pre>
* Binder<A, A> binder = BinderFactory.newBinder(A.class);
* </pre>
*
* It is also possible to build a more sofisticated binder which will only copy
- * some properties, using the {@link BinderModelBuilder}.
+ * some properties, using the {@link org.nuiton.util.beans.BinderModelBuilder}.
*
* <h2>Use a binder</h2>
- * Once you have a binder, you use the {@link Binder} api :
+ * Once you have a binder, you use the {@link org.nuiton.util.beans.Binder} api :
* <p/>
* To copy all properties from an object to another one :
* <pre>
@@ -73,9 +74,11 @@
*
* <h2>Building a new BinderModel</h2>
* <p>
- * In two words, you have to use the {@link BinderModelBuilder} object to do this.
- * then register your binder model into the {@link BinderFactory} using
- * one of the method {@code BinderFactory#registerBinderModel(XXX)}.
+ * In two words, you have to use the
+ * {@link org.nuiton.util.beans.BinderModelBuilder} object to do this.
+ * then register your binder model into the
+ * {@link org.nuiton.util.beans.BinderFactory} using one of the method
+ * {@code org.nuiton.util.beans.BinderFactory#registerBinderModel(XXX)}.
* </p>
* More explainations will come soon...
* <br/>
@@ -86,7 +89,7 @@
*
* <h1>JavaBeans api</h1>
*
- * <h2>{@link BeanMonitor} class</h2>
+ * <h2>{@link org.nuiton.util.beans.BeanMonitor} class</h2>
* This object permits to listen javaBeans and keep modifications made on a bean.
*
* More explanations will come soon, meanwhile you can see the test class :
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/converter/FormatMap.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/converter/FormatMap.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/converter/FormatMap.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -124,7 +124,7 @@
*/
public Object convert(FormatConverterFactory factory, Format format,
Object... args) {
- Object result = null;
+ Object result;
Map<Format, Object> values = this;
//if (!values.containsKey(format) ||
// !format.equals(FormatConverter.FORMAT_JAVA)) {
Added: trunk/nuiton-utils/src/main/java/org/nuiton/util/package-info.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/package-info.java (rev 0)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/package-info.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -0,0 +1,33 @@
+/*
+ * #%L
+ * Nuiton Utils :: Nuiton Utils
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2011 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>.
+ * #L%
+ */
+/**
+ * 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, ...).
+ */
+package org.nuiton.util;
\ No newline at end of file
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/package-info.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Deleted: trunk/nuiton-utils/src/main/java/org/nuiton/util/package.html
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/package.html 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/package.html 2011-05-15 11:13:57 UTC (rev 2143)
@@ -1,35 +0,0 @@
-<!--
- #%L
- Nuiton Utils
-
- $Id$
- $HeadURL$
- %%
- Copyright (C) 2004 - 2010 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>.
- #L%
- -->
-<html>
- <body>
- <h1>Nuiton-utils</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
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/package-info.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/package-info.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/package-info.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -27,9 +27,9 @@
* then get a proxy to access them. The provided classes will hide RMI
* complexity.
* <p/>
- * Use the {@link ServiceExporter} to register an service to the RMI registry.
+ * Use the {@link org.nuiton.util.rmi.ServiceExporter} to register an service to the RMI registry.
* <p/>
- * Use the {@link RemoteProxyFactory} to get a proxy an call the RMI exported
+ * Use the {@link org.nuiton.util.rmi.RemoteProxyFactory} to get a proxy an call the RMI exported
* service.
*
* @author Arnaud Thimel <thimel(a)codelutin.com>
Modified: trunk/nuiton-utils/src/test/java/org/nuiton/util/MD5InputStreamTest.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/MD5InputStreamTest.java 2011-05-15 10:40:37 UTC (rev 2142)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/MD5InputStreamTest.java 2011-05-15 11:13:57 UTC (rev 2143)
@@ -871,7 +871,7 @@
// define settings which are OS arch architecture independent
File arch_lib_path = null;
- String arch_libfile_suffix = null;
+ String arch_libfile_suffix;
// fill in settings for Linux on x86
1
0
15 May '11
Author: tchemit
Date: 2011-05-15 12:40:37 +0200 (Sun, 15 May 2011)
New Revision: 2142
Url: http://nuiton.org/repositories/revision/nuiton-utils/2142
Log:
add test for Evolution #1529: Add some usefull methods to obtain files from paths or fqn
Modified:
trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java
Modified: trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java 2011-05-15 10:35:56 UTC (rev 2141)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java 2011-05-15 10:40:37 UTC (rev 2142)
@@ -325,4 +325,20 @@
Assert.assertEquals(expectedFile, actualFile);
}
+ @Test
+ public void testGetFileFromPaths() {
+ File rootDirectory = TestHelper.getBaseDir();
+ File actual = FileUtil.getFileFromPaths(rootDirectory, "target", "surefire-workdir", "FileUtil");
+ File expected = new File(rootDirectory, "target" + File.separator + "surefire-workdir" + File.separator + "FileUtil");
+ Assert.assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testGetFileFromFQN() {
+ File rootDirectory = TestHelper.getBaseDir();
+ File actual = FileUtil.getFileFromFQN(rootDirectory, "target.surefire-workdir.FileUtil");
+ File expected = new File(rootDirectory, "target" + File.separator + "surefire-workdir" + File.separator + "FileUtil");
+ Assert.assertEquals(expected, actual);
+ }
+
} // FileUtilTest
1
0
Author: tchemit
Date: 2011-05-15 12:35:56 +0200 (Sun, 15 May 2011)
New Revision: 2141
Url: http://nuiton.org/repositories/revision/nuiton-utils/2141
Log:
add svn properties
Modified:
trunk/nuiton-utils/README.txt
trunk/nuiton-utils/src/license/THIRD-PARTY.properties
trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/ArgumentsParserException.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/ClassLoaderUtil.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/DateUtil.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/FasterCachedResourceResolver.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/MD5OutputStream.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/PeriodDates.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/ResourceResolver.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/ReverseFileReader.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/TimeLog.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/TimeTrace.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/Version.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/VersionUtil.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BeanMonitor.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BeanUtil.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/Binder.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderModelBuilder.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/converter/VersionConverter.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/converter/package-info.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java
trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/package-info.java
trunk/nuiton-utils/src/main/resources/META-INF/services/org.apache.commons.beanutils.Converter
trunk/nuiton-utils/src/main/resources/i18n/nuiton-utils_es_ES.properties
trunk/nuiton-utils/src/site/apt/ApplicationConfig.apt
trunk/nuiton-utils/src/site/apt/index.apt
trunk/nuiton-utils/src/test/java/org/nuiton/util/ApplicationConfigTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/DateUtilTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/MD5InputStreamTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/PeriodDatesTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/RecursivePropertiesTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/ReverseFileReaderTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/VersionTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/VersionUtilTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BeanA.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BeanB.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BeanMonitorTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderModelBuilderTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/converter/UnregistreableConverter.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/converter/VersionConverterTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/AnyException.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/SomeBean.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/SomeService.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/SomeServiceImpl.java
trunk/nuiton-utils/src/test/resources/META-INF/services/org.apache.commons.beanutils.Converter
trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt
trunk/nuiton-utils/src/test/resources/org/nuiton/util/reverseread.txt
trunk/nuiton-utils/src/test/resources/properties/recursive.properties
trunk/nuiton-utils/src/test/resources/properties/windows.properties
trunk/nuiton-validator/src/main/resources/META-INF/services/org.nuiton.validator.NuitonValidatorProvider
trunk/nuiton-validator/src/main/resources/i18n/nuiton-validator_es_ES.properties
Property changes on: trunk/nuiton-utils/README.txt
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/license/THIRD-PARTY.properties
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/ApplicationConfig.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/ArgumentsParserException.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/ClassLoaderUtil.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/DateUtil.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/FasterCachedResourceResolver.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/MD5OutputStream.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/PeriodDates.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/PropertiesDateRemoveFilterStream.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/ResourceResolver.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/ReverseFileReader.java
___________________________________________________________________
Added: svn:eol-style
+ native
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/TimeLog.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/TimeLog.java 2011-05-15 10:35:01 UTC (rev 2140)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/TimeLog.java 2011-05-15 10:35:56 UTC (rev 2141)
@@ -58,12 +58,12 @@
* log4j.logger.org.codelutin.MyClass.TimeLog=INFO
*
* @author poussin
- * @version $Revision: 1985 $
+ * @version $Revision$
* @see CallAnalyse
* @since 2.1
* <p/>
- * Last update: $Date: 2010-12-23 12:45:57 +0100 (jeu. 23 déc. 2010) $
- * by : $Author: sletellier $
+ * Last update: $Date$
+ * by : $Author$
*/
public class TimeLog {
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/TimeLog.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/TimeTrace.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/Version.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/VersionUtil.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BeanMonitor.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BeanUtil.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/Binder.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/BinderModelBuilder.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/beans/package-info.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/converter/VersionConverter.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/converter/package-info.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutor.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteMethodExecutorImpl.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/RemoteProxyFactory.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/ServiceExporter.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/java/org/nuiton/util/rmi/package-info.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/resources/META-INF/services/org.apache.commons.beanutils.Converter
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/main/resources/i18n/nuiton-utils_es_ES.properties
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Property changes on: trunk/nuiton-utils/src/site/apt/ApplicationConfig.apt
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/site/apt/index.apt
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/ApplicationConfigTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/DateUtilTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/MD5InputStreamTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/PeriodDatesTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/RecursivePropertiesTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/ReverseFileReaderTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/VersionTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/VersionUtilTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BeanA.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BeanB.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BeanMonitorTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderModelBuilderTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/beans/BinderTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/converter/UnregistreableConverter.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/converter/VersionConverterTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/AnyException.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/RmiExporterAndProxyTest.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/SomeBean.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/SomeService.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/java/org/nuiton/util/rmi/SomeServiceImpl.java
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/resources/META-INF/services/org.apache.commons.beanutils.Converter
___________________________________________________________________
Added: svn:eol-style
+ native
Modified: trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt
===================================================================
--- trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt 2011-05-15 10:35:01 UTC (rev 2140)
+++ trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt 2011-05-15 10:35:56 UTC (rev 2141)
@@ -3,7 +3,7 @@
* Nuiton Utils
*
* $Id$
- * $HeadURL: http://svn.nuiton.org/svn/nuiton-utils/trunk/nuiton-utils/src/main/java/org… $
+ * $HeadURL$
* %%
* Copyright (C) 2004 - 2010 CodeLutin
* %%
Property changes on: trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Property changes on: trunk/nuiton-utils/src/test/resources/org/nuiton/util/reverseread.txt
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/resources/properties/recursive.properties
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-utils/src/test/resources/properties/windows.properties
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-validator/src/main/resources/META-INF/services/org.nuiton.validator.NuitonValidatorProvider
___________________________________________________________________
Added: svn:eol-style
+ native
Property changes on: trunk/nuiton-validator/src/main/resources/i18n/nuiton-validator_es_ES.properties
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
1
0
r2140 - in trunk/nuiton-utils/src: main/java/org/nuiton/util test/java/org/nuiton/util test/resources/org/nuiton/util
by tchemit@users.nuiton.org 15 May '11
by tchemit@users.nuiton.org 15 May '11
15 May '11
Author: tchemit
Date: 2011-05-15 12:35:01 +0200 (Sun, 15 May 2011)
New Revision: 2140
Url: http://nuiton.org/repositories/revision/nuiton-utils/2140
Log:
Reformat some files (80 caracters max)
Anomalie #1528: There is a *testdir* created over and over while building library
Anomalie #1530: Tests for grep methods depends on java source files
Evolution #1529: Add some usefull methods to obtain files from paths or fqn
Added:
trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt
Modified:
trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/ResourceTest.java
trunk/nuiton-utils/src/test/java/org/nuiton/util/ZipUtilTest.java
Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java
===================================================================
--- trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java 2011-05-14 11:44:58 UTC (rev 2139)
+++ trunk/nuiton-utils/src/main/java/org/nuiton/util/FileUtil.java 2011-05-15 10:35:01 UTC (rev 2140)
@@ -36,6 +36,10 @@
package org.nuiton.util;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.swing.JFileChooser;
import java.awt.Component;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
@@ -66,11 +70,6 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import javax.swing.JFileChooser;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
/**
* Opérations sur des fichiers. Copie, suppression, renommage,
* recherche, fichiers d'un répertoire, sous-répertoires d'un répertoire,
@@ -161,7 +160,8 @@
* @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(Component parent, String... patternOrDescriptionFilters) {
+ static public File getFile(Component parent,
+ String... patternOrDescriptionFilters) {
File result;
result = getFile("Ok", "Ok", parent, patternOrDescriptionFilters);
return result;
@@ -179,12 +179,16 @@
* @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, Component parent, String... patternOrDescriptionFilters) {
+ static public File getFile(String title,
+ String approvalText,
+ 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];
+ 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];
@@ -204,7 +208,8 @@
* @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(Component parent, javax.swing.filechooser.FileFilter... filters) {
+ static public File getFile(Component parent,
+ javax.swing.filechooser.FileFilter... filters) {
File result = getFile("Ok", "Ok", parent, filters);
return result;
}
@@ -219,7 +224,10 @@
* @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, Component parent, javax.swing.filechooser.FileFilter... filters) {
+ static public File getFile(String title,
+ String approvalText,
+ Component parent,
+ javax.swing.filechooser.FileFilter... filters) {
try {
JFileChooser chooser = new JFileChooser(currentDirectory);
@@ -279,7 +287,9 @@
* Si le bouton annuler est utilisé, ou qu'il y a une erreur retourne
* null.
*/
- static public String getDirectory(Component parent, String title, String approvalText) {
+ static public String getDirectory(Component parent,
+ String title,
+ String approvalText) {
try {
JFileChooser chooser = new JFileChooser(currentDirectory);
chooser.setDialogType(JFileChooser.CUSTOM_DIALOG);
@@ -311,15 +321,21 @@
* @throws IOException if any io pb
*/
static public byte[] fileToByte(File file) throws IOException {
+ ByteArrayOutputStream result;
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);
+ try {
+ result = new ByteArrayOutputStream();
+ BufferedOutputStream tmp = new BufferedOutputStream(result);
+ try {
+ for (int b = in.read(); b != -1; b = in.read()) {
+ tmp.write(b);
+ }
+ } finally {
+ tmp.close();
+ }
+ } finally {
+ in.close();
}
- in.close();
- tmp.close();
-
return result.toByteArray();
}
@@ -342,11 +358,14 @@
ByteArrayOutputStream result = new ByteArrayOutputStream();
BufferedOutputStream tmp = new BufferedOutputStream(result);
- for (int b = src.read(); b != -1; b = src.read()) {
- tmp.write(b);
+ try {
+ for (int b = src.read(); b != -1; b = src.read()) {
+ tmp.write(b);
+ }
+ src.close();
+ } finally {
+ tmp.close();
}
- src.close();
- tmp.close();
byteToFile(result.toByteArray(), dst);
return dst;
}
@@ -373,7 +392,8 @@
* @return le fichier passé en parametre
* @throws IOException if any io pb
*/
- static public File byteToFile(byte[] bytes, File file) throws IOException {
+ static public File byteToFile(byte[] bytes,
+ File file) throws IOException {
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
out.write(bytes);
@@ -403,7 +423,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 {
+ static public BufferedReader getReader(File file,
+ String encoding) throws IOException {
FileInputStream inf = new FileInputStream(file);
InputStreamReader in = new InputStreamReader(inf, encoding);
BufferedReader result = new BufferedReader(in);
@@ -430,7 +451,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 {
+ static public BufferedWriter getWriter(File file,
+ String encoding) throws IOException {
FileOutputStream outf = new FileOutputStream(file);
OutputStreamWriter out = new OutputStreamWriter(outf, encoding);
BufferedWriter result = new BufferedWriter(out);
@@ -449,7 +471,9 @@
* @return le fichier pointant sur le nouveau repertoire
* @throws IOException if any io pb
*/
- static public File createTempDirectory(String prefix, String suffix, File tmpdir) throws IOException {
+ static public File createTempDirectory(String prefix,
+ String suffix,
+ File tmpdir) throws IOException {
if (tmpdir == null) {
tmpdir = new File(System.getProperty("java.io.tmpdir"));
}
@@ -472,7 +496,8 @@
* @return the temprary created file
* @throws IOException if any io pb
*/
- static public File createTempDirectory(String prefix, String suffix) throws IOException {
+ static public File createTempDirectory(String prefix,
+ String suffix) throws IOException {
return createTempDirectory(prefix, suffix, null);
}
@@ -518,10 +543,13 @@
* @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 {
+ 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 etre cree.
File parentFile = file.getParentFile();
+ //TODO tchemit 2011-05-15 Must test if directory was created (use
+ // the #createDirectoryIfNecessary method).
if (parentFile != null) {
parentFile.mkdirs();
}
@@ -539,10 +567,14 @@
* @param encoding encoding to use
* @throws IOException if any pb while writing
*/
- static public void writeString(File file, String content, String encoding) throws IOException {
+ 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 parentFile = file.getParentFile();
+ //TODO tchemit 2011-05-15 Must test if directory was created (use
+ // the #createDirectoryIfNecessary method).
if (parentFile != null) {
parentFile.mkdirs();
}
@@ -573,8 +605,10 @@
* @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);
+ 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;
@@ -608,7 +642,8 @@
String result = name;
for (String suffixe : suffixes) {
if (result.endsWith(suffixe)) {
- result = result.substring(0, result.length() - suffixe.length());
+ result = result.substring(0,
+ result.length() - suffixe.length());
break;
}
}
@@ -691,9 +726,11 @@
String... extchars) throws IOException {
String extension = extension(name, extchars);
if (extension == null) {
- throw new IOException("Could not find extension for name " + name + " within " + Arrays.toString(extchars));
+ throw new IOException("Could not find extension for name " +
+ name + " within " + Arrays.toString(extchars));
}
- String nameWithoutExtension = name.substring(0, name.length() - extension.length());
+ String nameWithoutExtension = name.substring(
+ 0, name.length() - extension.length());
String newName = nameWithoutExtension + newExtension;
return newName;
}
@@ -775,7 +812,9 @@
* @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) {
+ public static List<File> find(File directory,
+ final String pattern,
+ boolean recursively) {
final String root = directory.getAbsolutePath();
final int rootLength = root.length();
@@ -800,7 +839,9 @@
* @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) {
+ 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()) {
@@ -810,7 +851,8 @@
File file = todo.removeFirst();
if (recursively && file.isDirectory()) {
File[] childs = file.listFiles();
- if (childs != null) { // null if we don't have access to directory
+ if (childs != null) {
+ // null if we don't have access to directory
todo.addAll(Arrays.asList(childs));
}
}
@@ -902,14 +944,26 @@
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é.
+ //TODO tchemit 2011-05-15 Must test if directory was created (use
+ // the #createDirectoryIfNecessary method).
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();
+ FileInputStream fileInputStream = new FileInputStream(source);
+ try {
+ FileChannel sourceChannel = fileInputStream.getChannel();
+ FileOutputStream fileOutputStream = new FileOutputStream(target);
+ try {
+ FileChannel targetChannel = fileOutputStream.getChannel();
+ sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
+ // or
+ // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
+ targetChannel.close();
+ } finally {
+ fileOutputStream.close();
+ }
+ sourceChannel.close();
+ } finally {
+ fileInputStream.close();
+ }
}
/**
@@ -935,7 +989,9 @@
* 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 {
+ static public void copyRecursively(File srcDir,
+ File destDir,
+ String... includePatterns) throws IOException {
copyAndRenameRecursively(srcDir, destDir, null, null, includePatterns);
}
@@ -955,8 +1011,17 @@
* @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);
+ String renameFrom,
+ String renameTo,
+ String... includePatterns) throws IOException {
+ copyAndRenameRecursively(srcDir,
+ destDir,
+ true,
+ renameFrom,
+ renameTo,
+ false,
+ includePatterns
+ );
}
/**
@@ -977,8 +1042,12 @@
* 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,
+ static public void copyAndRenameRecursively(File srcDir,
+ File destDir,
+ boolean includeSrcDir,
+ String renameFrom,
+ String renameTo,
+ boolean exclude,
String... includePatterns) throws IOException {
String rootSrc;
if (includeSrcDir) {
@@ -1042,7 +1111,8 @@
* @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) {
+ private static boolean copyRecursivelyAccept(File file,
+ String[] includePatterns) {
boolean result = includePatterns.length == 0;
String filename = file.getAbsolutePath();
for (String pattern : includePatterns) {
@@ -1068,7 +1138,8 @@
* @throws IOException
* @since 1.1.2
*/
- protected static List<CharSequence> grep(String regex, CharBuffer cb) {
+ protected static List<CharSequence> grep(String regex,
+ CharBuffer cb) {
List<CharSequence> linesList = null;
@@ -1117,7 +1188,9 @@
* @throws IOException
* @since 1.1.2
*/
- public static List<CharSequence> grep(String searchRegex, File f, String encoding) throws IOException {
+ public static List<CharSequence> grep(String searchRegex,
+ File f,
+ String encoding) throws IOException {
List<CharSequence> lines = null;
@@ -1165,9 +1238,13 @@
* @throws IOException
* @since 1.1.2
*/
- public static Map<File, List<CharSequence>> grep(String searchRegex, File rootDirectory, String fileRegex, String encoding) throws IOException {
- Map<File, List<CharSequence>> results = new HashMap<File, List<CharSequence>>();
- List<File> files = FileUtil.find(rootDirectory, fileRegex, true);
+ public static Map<File, List<CharSequence>> grep(String searchRegex,
+ File rootDirectory,
+ String fileRegex,
+ String encoding) throws IOException {
+ Map<File, List<CharSequence>> results =
+ new HashMap<File, List<CharSequence>>();
+ List<File> files = find(rootDirectory, fileRegex, true);
for (File file : files) {
List<CharSequence> lines = grep(searchRegex, file, encoding);
if (lines != null) {
@@ -1187,8 +1264,13 @@
* @throws IOException
* @since 1.1.2
*/
- public static Map<File, List<CharSequence>> grep(String searchRegex, String fileRegex, String encoding) throws IOException {
- Map<File, List<CharSequence>> results = grep(searchRegex, new File("."), fileRegex, encoding);
+ public static Map<File, List<CharSequence>> grep(String searchRegex,
+ String fileRegex,
+ String encoding) throws IOException {
+ Map<File, List<CharSequence>> results = grep(searchRegex,
+ new File("."),
+ fileRegex,
+ encoding);
return results;
}
@@ -1204,15 +1286,17 @@
* @throws IOException
* @since 1.1.2
*/
- public static void sed(String searchRegex, String replace, File file, String encoding) throws IOException {
+ public static void sed(String searchRegex,
+ String replace,
+ File file,
+ String encoding) throws IOException {
Pattern pattern = Pattern.compile(searchRegex);
- FileInputStream fis = null;
String outString = null;
+ FileInputStream fis = new FileInputStream(file);
try {
// Open the file and then get a channel from the stream
- fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
// Get the file's size and then map it into memory
@@ -1227,25 +1311,17 @@
Matcher matcher = pattern.matcher(cb);
outString = matcher.replaceAll(replace);
+ } finally {
+ fis.close();
}
- finally {
- if (fis != null) {
- fis.close();
- }
- }
if (outString != null) {
- PrintStream ps = null;
+ PrintStream ps = new PrintStream(new FileOutputStream(file));
try {
- ps = new PrintStream(new FileOutputStream(file));
ps.print(outString);
+ } finally {
ps.close();
}
- finally {
- if (ps != null) {
- ps.close();
- }
- }
}
}
@@ -1260,8 +1336,12 @@
* @throws IOException
* @since 1.1.2
*/
- public static void sed(String searchRegex, String replace, File rootDirectory, String fileRegex, String encoding) throws IOException {
- List<File> files = FileUtil.find(rootDirectory, fileRegex, true);
+ public static void sed(String searchRegex,
+ String replace,
+ File rootDirectory,
+ String fileRegex,
+ String encoding) throws IOException {
+ List<File> files = find(rootDirectory, fileRegex, true);
for (File file : files) {
sed(searchRegex, replace, file, encoding);
}
@@ -1277,7 +1357,10 @@
* @throws IOException
* @since 1.1.2
*/
- public static void sed(String searchRegex, String replace, String fileRegex, String encoding) throws IOException {
+ public static void sed(String searchRegex,
+ String replace,
+ String fileRegex,
+ String encoding) throws IOException {
sed(searchRegex, replace, new File("."), fileRegex, encoding);
}
@@ -1302,4 +1385,45 @@
return false;
}
+ /**
+ * Obtain a file from the given {@code rootDirectory}, applying given paths.
+ * <p/>
+ * For example with paths = a, b and c, then result is :
+ * <pre>
+ * root/a/b/c
+ * </pre>
+ *
+ * @param rootDirectory the root directory
+ * @param paths paths to apply
+ * @return the final file
+ * @since 2.2
+ */
+ public static File getFileFromPaths(File rootDirectory, String... paths) {
+ File result = rootDirectory;
+ for (String path : paths) {
+ result = new File(result, path);
+ }
+ return result;
+ }
+
+ /**
+ * Obtain a file fro the given {@code rootDirectory}, applying the fqn.
+ * <p/>
+ * For example with fqn = a.b.c, the result is :
+ * <pre>
+ * root/a/b/c
+ * </pre>
+ *
+ * @param rootDirectory the root directory
+ * @param fqn fqn of searched file
+ * @return the final file
+ * @since 2.2
+ */
+ public static File getFileFromFQN(File rootDirectory, String fqn) {
+ String[] paths = fqn.split("\\.");
+
+ File result = getFileFromPaths(rootDirectory, paths);
+ return result;
+ }
+
} // FileUtil
Modified: trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java 2011-05-14 11:44:58 UTC (rev 2139)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/FileUtilTest.java 2011-05-15 10:35:01 UTC (rev 2140)
@@ -25,25 +25,26 @@
package org.nuiton.util;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
/**
* FileUtilTest.
- *
+ * <p/>
* Created: 22 nov. 2004
*
* @author Benjamin Poussin <poussin(a)codelutin.com>
* @version $Revision$
- *
- * Mise a jour: $Date$
- * par : */
+ * <p/>
+ * Mise a jour: $Date$
+ * par :
+ */
public class FileUtilTest { // FileUtilTest
@Test
@@ -67,7 +68,7 @@
result = FileUtil.extension(new File("/tmp/toto.xml"), "t", ".");
Assert.assertEquals("o.xml", result);
}
-
+
@Test
public void testWriteString() throws IOException {
File testFile = new File(System.getProperty("java.io.tmpdir"), "test.txt");
@@ -76,10 +77,10 @@
Assert.assertEquals("testWriteString", FileUtil.readAsString(testFile));
}
-
+
/**
* This test throwed NPE before 1.2.1 with simple file path (current folder).
- *
+ *
* @throws IOException
*/
@Test
@@ -90,15 +91,18 @@
Assert.assertEquals("testWriteString", FileUtil.readAsString(testFile));
}
-
+
/**
* Test testWriteString method with file containing ".."
- *
+ *
* @throws IOException
*/
@Test
public void testWriteStringRelativeNonCanonical() throws IOException {
- File testFile = new File(".." + File.separator + "testdir" + File.separator + "test.txt");
+ File testFile = new File(".." + File.separator +
+ "target" + File.separator +
+ "surefire-workdir" + File.separator +
+ "testdir" + File.separator + "test.txt");
testFile.deleteOnExit();
FileUtil.writeString(testFile, "testWriteString");
@@ -122,7 +126,7 @@
FileUtil.copyRecursively(srcDir, destDir1);
FileUtil.copyRecursively(srcDir, destDir2, ".*titi$");
-
+
// remove created temp dirs :
FileUtil.deleteRecursively(srcDir);
FileUtil.deleteRecursively(destDir1);
@@ -144,55 +148,56 @@
Assert.assertEquals(file.length(), dest.length());
Assert.assertEquals(content, FileUtil.readAsString(dest));
}
-
+
/**
* Test grep on a single file.
- *
+ * <p/>
* Search for grep() method count.
- *
- * @throws IOException
+ *
+ * @throws IOException
*/
@Test
public void testGrepSingleFile() throws IOException {
// search for
- File testUtilFile = FileUtil.find(new File("."), ".*FileUtil\\.java", true).get(0);
+ File testUtilFile = FileUtil.find(new File("."), ".*fileUtilData\\.txt", true).get(0);
- List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile , "UTF-8");
+ List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile, "UTF-8");
Assert.assertNotNull(lines);
Assert.assertEquals(4, lines.size());
-
+
// assert result are ordered
- Assert.assertTrue(lines.get(0).toString().indexOf("CharBuffer") > 0);
- Assert.assertTrue(lines.get(1).toString().indexOf("File f,") > 0);
- Assert.assertTrue(lines.get(2).toString().indexOf("rootDirectory") > 0);
- Assert.assertTrue(lines.get(3).toString().indexOf("String searchRegex, String fileRegex, String encoding") > 0);
+ Assert.assertTrue(lines.get(0).toString().contains("CharBuffer"));
+ Assert.assertTrue(lines.get(1).toString().contains("File f,"));
+ Assert.assertTrue(lines.get(2).toString().contains("rootDirectory"));
+ Assert.assertTrue(lines.get(3).toString().contains("String searchRegex, String fileRegex, String encoding"));
}
-
+
/**
* Test grep on a multiple files.
- *
+ * <p/>
* Try to find all java file containing "CodeLutin". Can fail if some
* src files are deleted.
- *
- * @throws IOException
+ *
+ * @throws IOException
*/
@Test
public void testGrepMultiple() throws IOException {
File rootDir = new File("src");
- Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", rootDir , ".*\\.java", "UTF-8");
+ Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", rootDir, ".*\\.java", "UTF-8");
- Assert.assertTrue("should have more than 50 files, but found : "+
+ Assert.assertTrue("should have more than 50 files, but found : " +
results.size(), results.size() > 50);
-
+
}
-
+
/**
* Test sed method on a single file.
- * @throws IOException
+ *
+ * @throws IOException
*/
@Test
public void testSedSingleFile() throws IOException {
@@ -201,34 +206,34 @@
// try to not make sed in real src dir ;)
File testDirectory = FileUtil.createTempDirectory("sed", "test");
FileUtil.copyRecursively(new File("src").getAbsoluteFile(), testDirectory);
- File testUtilFile = FileUtil.find(testDirectory, ".*FileUtil\\.java", true).get(0);
+ File testUtilFile = FileUtil.find(testDirectory, ".*fileUtilData\\.txt", true).get(0);
- List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile , "UTF-8");
+ List<CharSequence> lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile, "UTF-8");
Assert.assertEquals(4, lines.size());
-
- lines = FileUtil.grep("sedfoo", testUtilFile , "UTF-8");
+
+ lines = FileUtil.grep("sedfoo", testUtilFile, "UTF-8");
Assert.assertNull(lines);
// real method to test here : sed
- FileUtil.sed("grep", "sedfoo", testUtilFile , "UTF-8");
+ FileUtil.sed("grep", "sedfoo", testUtilFile, "UTF-8");
- lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile , "UTF-8");
+ lines = FileUtil.grep("grep\\(String .*\\)", testUtilFile, "UTF-8");
Assert.assertNull(lines);
- lines = FileUtil.grep("sedfoo", testUtilFile , "UTF-8");
+ lines = FileUtil.grep("sedfoo", testUtilFile, "UTF-8");
Assert.assertEquals(9, lines.size());
// clean
FileUtil.deleteRecursively(testDirectory);
}
-
+
/**
* Test sed on a multiple files.
- *
+ * <p/>
* Try to replace all "CodeLutin" by "nuiton" in all files. Can fail if some
* src files are deleted.
- *
- * @throws IOException
+ *
+ * @throws IOException
*/
@Test
public void testSedMultiple() throws IOException {
@@ -239,28 +244,28 @@
File testDirectory = FileUtil.createTempDirectory("sed", "test");
FileUtil.copyRecursively(new File("src").getAbsoluteFile(), testDirectory);
- Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", testDirectory , ".*\\.java", "UTF-8");
- Assert.assertTrue("should have more than 50 files, but found : "+
+ Map<File, List<CharSequence>> results = FileUtil.grep("CodeLutin", testDirectory, ".*\\.java", "UTF-8");
+ Assert.assertTrue("should have more than 50 files, but found : " +
results.size(), results.size() > 50);
- FileUtil.sed("CodeLutin", "Nuiton", testDirectory, ".*\\.java" , "UTF-8");
+ FileUtil.sed("CodeLutin", "Nuiton", testDirectory, ".*\\.java", "UTF-8");
- results = FileUtil.grep("CodeLutin", testDirectory , ".*\\.java", "UTF-8");
+ results = FileUtil.grep("CodeLutin", testDirectory, ".*\\.java", "UTF-8");
Assert.assertTrue(results.isEmpty());
- results = FileUtil.grep("Nuiton", testDirectory , ".*\\.java", "UTF-8");
- Assert.assertTrue("should have more than 50 files, but found : "+
+ results = FileUtil.grep("Nuiton", testDirectory, ".*\\.java", "UTF-8");
+ Assert.assertTrue("should have more than 50 files, but found : " +
results.size(), results.size() > 50);
-
+
// clean
FileUtil.deleteRecursively(testDirectory);
}
-
+
/**
* Test that sed result which produce shorter file work as well.
- *
- * @throws IOException
+ *
+ * @throws IOException
*/
@Test
public void testSedComment() throws IOException {
@@ -268,16 +273,16 @@
// try to not make sed in real src dir ;)
File testDirectory = FileUtil.createTempDirectory("sed", "test", parent);
FileUtil.copyRecursively(new File("src").getAbsoluteFile(), testDirectory);
- File testUtilFile = FileUtil.find(testDirectory, ".*FileUtil\\.java", true).get(0);
+ File testUtilFile = FileUtil.find(testDirectory, ".*fileUtilData\\.txt", true).get(0);
// real method to test here : sed
- FileUtil.sed(".*\\*.*", "** skipped **", testUtilFile , "UTF-8");
+ FileUtil.sed(".*\\*.*", "** skipped **", testUtilFile, "UTF-8");
- List<CharSequence> lines = FileUtil.grep("/var/tmp/bidulle", testUtilFile , "UTF-8");
+ List<CharSequence> lines = FileUtil.grep("/var/tmp/bidulle", testUtilFile, "UTF-8");
Assert.assertNull(lines);
// test une presence en debut et fin de fichier
- List<CharSequence> lines2 = FileUtil.grep("// FileUtil", testUtilFile , "UTF-8");
+ List<CharSequence> lines2 = FileUtil.grep("// FileUtil", testUtilFile, "UTF-8");
Assert.assertEquals(2, lines2.size());
// clean
@@ -288,7 +293,8 @@
@BeforeClass
public static void beforeTest() {
- parent = TestHelper.createTestsDataDirectory("FileUtil");
+ parent = TestHelper.createTestsDataDirectory(
+ "surefire-workdir" + File.separator + "FileUtil");
}
public void testChangeExtension() throws IOException {
Modified: trunk/nuiton-utils/src/test/java/org/nuiton/util/ResourceTest.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/ResourceTest.java 2011-05-14 11:44:58 UTC (rev 2139)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/ResourceTest.java 2011-05-15 10:35:01 UTC (rev 2140)
@@ -25,26 +25,32 @@
package org.nuiton.util;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Assert;
+import org.junit.Test;
+
import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
-import org.junit.Assert;
-import org.junit.Test;
-
/**
* Test class for {@link Resource}.
- *
+ *
* @author chatellier
* @version $Revision$
- *
- * Last update : $Date$
- * By : $Author$
+ * <p/>
+ * Last update : $Date$
+ * By : $Author$
*/
public class ResourceTest { // ResourceTest
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(ResourceTest.class);
+
@Test
public void testaddDefaultClassLoader() throws Exception {
Assert.assertNull(ResourceTest.class.getResource("/bin/java"));
@@ -56,11 +62,11 @@
Assert.assertTrue(result.exists());
URL resultURL = Resource.getURL("bin/java");
- Assert.assertEquals(result.toURI().toURL(),resultURL);
+ Assert.assertEquals(result.toURI().toURL(), resultURL);
}
@Test
- public void testGetURL()throws Exception {
+ public void testGetURL() throws Exception {
URL url;
url = Resource.getURL("README.txt");
@@ -99,15 +105,21 @@
@Test
public void testGetURLs() throws Exception {
- System.out.println(java.util.Arrays.asList(((URLClassLoader)ClassLoader.getSystemClassLoader()).getURLs()));
+ if (log.isInfoEnabled()) {
+ log.info(Arrays.asList(((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs()));
+ }
List<URL> result;
result = Resource.getURLs(".*bin/java");
- System.out.println(result);
+ if (log.isInfoEnabled()) {
+ log.info(result);
+ }
result = Resource.getURLs("META-INF/MANIFEST.MF");
- System.out.println(result);
+ if (log.isInfoEnabled()) {
+ log.info(result);
+ }
}
@Test
@@ -118,7 +130,7 @@
Assert.assertFalse(Resource.isJar(""));
Assert.assertFalse(Resource.isJar(null));
}
-
+
@Test
public void testIsZip() throws Exception {
Assert.assertTrue(Resource.isZip("toto.zip"));
@@ -134,10 +146,10 @@
Assert.assertTrue(Resource.isPattern(".?.zip"));
Assert.assertFalse(Resource.isPattern("toto.zip"));
}
-
+
/**
* Test de recherche de resource dans le classpath (jar).
- *
+ *
* @throws Exception
*/
@Test
@@ -148,7 +160,7 @@
List<URL> urlsClass2 = Resource.getResources("org/nuiton/util/VersionUtilTest.class");
Assert.assertEquals(2, urlsPattern.size());
Assert.assertEquals(urlsPattern.size(), urlsClass1.size() + urlsClass2.size());
-
+
// test sans dossier de recherche (directement un pattern)
List<URL> urlsAllPattern = Resource.getResources("log4j\\..*");
Assert.assertEquals(1, urlsAllPattern.size());
@@ -156,7 +168,7 @@
/**
* Test de recherche de resource dans le classpath (dossier hors jar).
- *
+ *
* @throws Exception
*/
@Test
@@ -165,20 +177,37 @@
// i18n, resources, test resources
Assert.assertEquals(3, urls.size());
}
-
+
/**
* Test de recherche de resource dans le classpath (dossier hors jar) en
* utiliant le classloader de test.
- *
+ *
* @throws Exception
*/
@Test
public void testGetTestResourcesClassPath() throws Exception {
+ URL url1;
+ URL url2;
+ url1 = getClass().getResource("/org/nuiton/util/fileUtilData.txt");
+ url2 = getClass().getResource("/org/nuiton/util/reverseread.txt");
+
List<URL> urls = Resource.getResources("org/nuiton/util/.*\\.txt");
- Assert.assertEquals(1, urls.size());
-
+ // there is at least two such files : fileUtilData.txt and
+ // reverseread.txt
+ Assert.assertTrue(urls.size() >= 2);
+ Assert.assertTrue(urls.contains(url1));
+ Assert.assertTrue(urls.contains(url2));
+
urls = Resource.getResources("org/nuiton/util/.*\\.txt", ResourceTest.class.getClassLoader());
- Assert.assertEquals(1, urls.size());
+
+ url1 = ResourceTest.class.getClassLoader().getResource("org/nuiton/util/fileUtilData.txt");
+ url2 = ResourceTest.class.getClassLoader().getResource("org/nuiton/util/reverseread.txt");
+
+ // there is at least two such files : fileUtilData.txt and
+ // reverseread.txt
+ Assert.assertTrue(urls.size() >= 2);
+ Assert.assertTrue(urls.contains(url1));
+ Assert.assertTrue(urls.contains(url2));
}
} // ResourceTest
Modified: trunk/nuiton-utils/src/test/java/org/nuiton/util/ZipUtilTest.java
===================================================================
--- trunk/nuiton-utils/src/test/java/org/nuiton/util/ZipUtilTest.java 2011-05-14 11:44:58 UTC (rev 2139)
+++ trunk/nuiton-utils/src/test/java/org/nuiton/util/ZipUtilTest.java 2011-05-15 10:35:01 UTC (rev 2140)
@@ -73,7 +73,7 @@
File basedirFile = new File(basedir);
testWorkDir = new File(basedirFile,
"target" + File.separator +
- "test-workdir");
+ "surefire-workdir");
boolean b = testWorkDir.exists() || testWorkDir.mkdirs();
if (!b) {
Added: trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt
===================================================================
--- trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt (rev 0)
+++ trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt 2011-05-15 10:35:01 UTC (rev 2140)
@@ -0,0 +1,1421 @@
+/*
+ * #%L
+ * Nuiton Utils
+ *
+ * $Id$
+ * $HeadURL: http://svn.nuiton.org/svn/nuiton-utils/trunk/nuiton-utils/src/main/java/org… $
+ * %%
+ * Copyright (C) 2004 - 2010 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>.
+ * #L%
+ */
+
+/* *
+ * FileUtil.java
+ *
+ * Created: 22 nov. 2004
+ *
+ * @author Benjamin Poussin <poussin(a)codelutin.com>
+ * @version $Revision$
+ *
+ * Mise a jour: $Date$
+ * par : */
+
+package org.nuiton.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.swing.JFileChooser;
+import java.awt.Component;
+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.io.PrintStream;
+import java.nio.CharBuffer;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetDecoder;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Opérations sur des fichiers. Copie, suppression, renommage,
+ * recherche, fichiers d'un répertoire, sous-répertoires d'un répertoire,
+ * récupération du basename ou de l'extension, création d'un fichier
+ * temporaire, comparaison de dates de création, récupération d'une chaîne,
+ * d'un Reader ou d'un Writer à partir d'un fichier, récupération du fichier
+ * saisi dans une boîte de dialogue, conversions en byte[], en Stream...
+ * <p/>
+ * Created: 22 novembre 2004
+ *
+ * @author bpoussin <poussin(a)codelutin.com>
+ * $Id$
+ */
+public class FileUtil { // FileUtil
+
+ /** Logger. */
+ static private Log log = LogFactory.getLog(FileUtil.class);
+
+ /** Encoding utilisé (peut être redéfini) */
+ // TODO fdesbois 2011-04-16 : Perhaps change ISO encoding by UTF-8
+ 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;
+ protected String description;
+
+ 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(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,
+ 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(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,
+ 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(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 {
+ ByteArrayOutputStream result;
+ InputStream in = new BufferedInputStream(new FileInputStream(file));
+ try {
+ result = new ByteArrayOutputStream();
+ BufferedOutputStream tmp = new BufferedOutputStream(result);
+ try {
+ for (int b = in.read(); b != -1; b = in.read()) {
+ tmp.write(b);
+ }
+ } finally {
+ tmp.close();
+ }
+ } finally {
+ in.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);
+ try {
+ for (int b = src.read(); b != -1; b = src.read()) {
+ tmp.write(b);
+ }
+ src.close();
+ } finally {
+ 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));
+ try {
+ out.write(bytes);
+ } finally {
+ 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);
+ 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);
+ 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 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 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
+ *
+ * Use default enconding : {@link #ENCODING}.
+ *
+ * @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 etre cree.
+ File parentFile = file.getParentFile();
+ //TODO tchemit 2011-05-15 Must test if directory was created (use
+ // the #createDirectoryIfNecessary method).
+ if (parentFile != null) {
+ parentFile.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 parentFile = file.getParentFile();
+ //TODO tchemit 2011-05-15 Must test if directory was created (use
+ // the #createDirectoryIfNecessary method).
+ if (parentFile != null) {
+ parentFile.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 = basename(file.getName(), suffixes);
+ return result;
+ }
+
+ /**
+ * Equivalent de la methode basename unix.
+ * basename("/tmp/toto.xml", ".xml") -> "toto"
+ *
+ * @param name le nom du 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é.
+ * @since 1.4.2
+ */
+ static public String basename(String name, String... suffixes) {
+ String result = name;
+ 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 name = file.getName();
+ String result = extension(name, extchars);
+ return result;
+ }
+
+ /**
+ * Permet de récupérer l'extension d'un nom de fichier
+ *
+ * @param name le nom du 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
+ * @since 1.4.2
+ */
+ static public String extension(String name, String... extchars) {
+ String result = "";
+
+ 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;
+ }
+
+ /**
+ * Recupère le fichier dans le même répertoire que le fichier donné et dont
+ * on a changé l'extension.
+ *
+ * @param file le fichier d'origine
+ * @param newExtension la nouvelle extension à utiliser
+ * @param extchars la liste des extensions possibles
+ * @return le fichier dont on a changé l'extension
+ * @throws IOException si aucune extension trouvé dans le fichier d'origine
+ * @since 1.4.2
+ */
+ static public File changeExtension(File file,
+ String newExtension,
+ String... extchars) throws IOException {
+ String name = file.getName();
+ String newName = changeExtension(name, newExtension, extchars);
+ File newFile = new File(file.getParentFile(), newName);
+ return newFile;
+ }
+
+ /**
+ * Change l'extension du fichier en entrée avec la nouvelle extension
+ *
+ * @param name le nom de fichier à transformer
+ * @param newExtension la nouvelle extension à utiliser
+ * @param extchars la liste des extensions possibles
+ * @return le nouveau nom de fichier
+ * @throws IOException si aucune extension trouvé dans le fichier d'origine
+ * @since 1.4.2
+ */
+ static public String changeExtension(String name,
+ String newExtension,
+ String... extchars) throws IOException {
+ String extension = extension(name, extchars);
+ if (extension == null) {
+ throw new IOException("Could not find extension for name " +
+ name + " within " + Arrays.toString(extchars));
+ }
+ String nameWithoutExtension = name.substring(
+ 0, name.length() - extension.length());
+ String newName = nameWithoutExtension + newExtension;
+ return newName;
+ }
+
+ /**
+ * Recupère le fichier mirroir du fichier {@code file} donnée qui est dans
+ * l'arborescence de {@code inputDirectory} dans le répertoire
+ * {@code ouputDirectory}.
+ *
+ * @param inputDirectory le répertoire de départ
+ * @param outputDirectory le répertoire cible
+ * @param file le fichier
+ * @return le fichier mirroir dans le répertoire cible
+ * @since 1.4.2
+ */
+ static public File getRelativeFile(File inputDirectory,
+ File outputDirectory,
+ File file) {
+ String inputPath = inputDirectory.getAbsolutePath();
+ String s = file.getAbsolutePath();
+ int index = s.indexOf(inputPath);
+ if (index == -1) {
+ throw new IllegalArgumentException(
+ "File " + file + " is not in " + inputDirectory);
+ }
+ String relativePath = s.substring(inputPath.length());
+ File result = new File(outputDirectory, relativePath);
+ return result;
+ }
+
+ public interface FileAction {
+ 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 {
+ @Override
+ 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 {
+ @Override
+ public boolean accept(File f) {
+ return f.isFile();
+ }
+ }
+ return getFilteredElements(directory, new NormalFileFilter(), true);
+ }
+
+ /**
+ * Retourne les fichiers d'un répertoire qui satisfont 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() {
+ @Override
+ 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() {
+ @Override
+ 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é.
+ //TODO tchemit 2011-05-15 Must test if directory was created (use
+ // the #createDirectoryIfNecessary method).
+ target.getParentFile().mkdirs();
+ FileInputStream fileInputStream = new FileInputStream(source);
+ try {
+ FileChannel sourceChannel = fileInputStream.getChannel();
+ FileOutputStream fileOutputStream = new FileOutputStream(target);
+ try {
+ FileChannel targetChannel = fileOutputStream.getChannel();
+ sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
+ // or
+ // targetChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
+ targetChannel.close();
+ } finally {
+ fileOutputStream.close();
+ }
+ sourceChannel.close();
+ } finally {
+ fileInputStream.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 (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);
+ }
+ }
+ }
+ }
+
+ /**
+ * Get a ByteArrayOutputStream containing all data that could be read from the given InputStream
+ * @param inputStream the stream to read
+ * @param defaultBufferSize the buffer size
+ * @return the input stream read for input
+ * @throws IOException if any pb while reading or writing
+ */
+ public static ByteArrayOutputStream readBytesFrom(InputStream inputStream,
+ int defaultBufferSize) throws 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;
+ }
+
+ /**
+ * @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;
+ }
+
+ /**
+ * Use the linePattern to break the given CharBuffer into lines, applying
+ * the input pattern to each line to see if we have a match
+ *
+ * Code taken from :
+ *
+ * http://java.sun.com/javase/6/docs/technotes/guides/io/example/Grep.java
+ *
+ * @param regex regex to search into file
+ * @param cb nio buffer
+ * @return matching lines (or {code null} if no matching lines)
+ * @throws IOException
+ * @since 1.1.2
+ */
+ protected static List<CharSequence> grep(String regex, CharBuffer cb) {
+
+ List<CharSequence> linesList = null;
+
+ Pattern pattern = Pattern.compile(regex);
+
+ Pattern linePattern = Pattern.compile(".*\r?\n");
+
+ Matcher lm = linePattern.matcher(cb); // Line matcher
+ Matcher pm = null; // Pattern matcher
+ //int lines = 0;
+ while (lm.find()) {
+ //lines++;
+ CharSequence cs = lm.group(); // The current line
+ if (pm == null) {
+ pm = pattern.matcher(cs);
+ }
+ else {
+ pm.reset(cs);
+ }
+ if (pm.find()) {
+ // init
+ if (linesList == null) {
+ linesList = new ArrayList<CharSequence>();
+ }
+ linesList.add(cs);
+ }
+ if (lm.end() == cb.limit()) {
+ break;
+ }
+ }
+
+ return linesList;
+ }
+
+ /**
+ * Java implementation for the unix grep command.
+ *
+ * Code taken from :
+ *
+ * http://java.sun.com/javase/6/docs/technotes/guides/io/example/Grep.java
+ *
+ * @param searchRegex regex to search into file
+ * @param f file to search into
+ * @param encoding encoding to use
+ * @return matching lines (or {code null} if no matching lines)
+ * @throws IOException
+ * @since 1.1.2
+ */
+ public static List<CharSequence> grep(String searchRegex, File f, String encoding) throws IOException {
+
+ List<CharSequence> lines = null;
+
+ FileInputStream fis = null;
+ FileChannel fc = null;
+
+ try {
+ // Open the file and then get a channel from the stream
+ fis = new FileInputStream(f);
+ fc = fis.getChannel();
+
+ // Get the file's size and then map it into memory
+ int sz = (int)fc.size();
+ MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
+
+ // Decode the file into a char buffer
+ Charset charset = Charset.forName(encoding);
+ CharsetDecoder decoder = charset.newDecoder();
+ CharBuffer cb = decoder.decode(bb);
+
+ // Perform the search
+ lines = grep(searchRegex, cb);
+ }
+ finally {
+ // Close the channel and the stream
+ if (fc != null) {
+ fc.close();
+ }
+ if (fis != null) {
+ fis.close();
+ }
+ }
+
+ return lines;
+ }
+
+ /**
+ * Java implementation for the unix grep command.
+ *
+ * @param searchRegex regex to search into file
+ * @param rootDirectory directory to seacrh into
+ * @param fileRegex regex for file to find in {@code rootDirectory}
+ * @param encoding encoding to use
+ * @return all matching lines for each files
+ * @throws IOException
+ * @since 1.1.2
+ */
+ public static Map<File, List<CharSequence>> grep(String searchRegex, File rootDirectory, String fileRegex, String encoding) throws IOException {
+ Map<File, List<CharSequence>> results =
+ new HashMap<File, List<CharSequence>>();
+ List<File> files = find(rootDirectory, fileRegex, true);
+ for (File file : files) {
+ List<CharSequence> lines = grep(searchRegex, file, encoding);
+ if (lines != null) {
+ results.put(file, lines);
+ }
+ }
+ return results;
+ }
+
+ /**
+ * Search for files matching regex in current directory.
+ *
+ * @param searchRegex regex to search into file
+ * @param fileRegex regex for file to find in current dir
+ * @param encoding encoding to use
+ * @return all matching lines for each files
+ * @throws IOException
+ * @since 1.1.2
+ */
+ public static Map<File, List<CharSequence>> grep(String searchRegex, String fileRegex, String encoding) throws IOException {
+ Map<File, List<CharSequence>> results = grep(searchRegex,
+ new File("."),
+ fileRegex,
+ encoding);
+ return results;
+ }
+
+ /**
+ * Sed implementation for a single file.
+ *
+ * Oginal source code from http://kickjava.com/src/org/apache/lenya/util/SED.java.htm.
+ *
+ * @param searchRegex Prefix which shall be replaced
+ * @param replace Prefix which is going to replace the original
+ * @param file File which sed shall be applied
+ * @param encoding charset encoding
+ * @throws IOException
+ * @since 1.1.2
+ */
+ public static void sed(String searchRegex,
+ String replace,
+ File file,
+ String encoding) throws IOException {
+
+ Pattern pattern = Pattern.compile(searchRegex);
+
+ String outString = null;
+ FileInputStream fis = new FileInputStream(file);
+ try {
+ // Open the file and then get a channel from the stream
+ FileChannel fc = fis.getChannel();
+
+ // Get the file's size and then map it into memory
+ int sz = (int)fc.size();
+ MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz);
+
+ // Decode the file into a char buffer
+ // Charset and decoder for encoding
+ Charset charset = Charset.forName(encoding);
+ CharsetDecoder decoder = charset.newDecoder();
+ CharBuffer cb = decoder.decode(bb);
+
+ Matcher matcher = pattern.matcher(cb);
+ outString = matcher.replaceAll(replace);
+ } finally {
+ fis.close();
+ }
+
+ if (outString != null) {
+ PrintStream ps = new PrintStream(new FileOutputStream(file));
+ try {
+ ps.print(outString);
+ } finally {
+ ps.close();
+ }
+ }
+ }
+
+ /**
+ * Java implementation for the unix sed command.
+ *
+ * @param searchRegex regex to search into file
+ * @param replace string to replace matching patterns
+ * @param rootDirectory directory to search into
+ * @param fileRegex regex for file to find in {@code rootDirectory}
+ * @param encoding encoding to use
+ * @throws IOException
+ * @since 1.1.2
+ */
+ public static void sed(String searchRegex,
+ String replace,
+ File rootDirectory,
+ String fileRegex,
+ String encoding) throws IOException {
+ List<File> files = find(rootDirectory, fileRegex, true);
+ for (File file : files) {
+ sed(searchRegex, replace, file, encoding);
+ }
+ }
+
+ /**
+ * Java implementation for the unix sed command.
+ *
+ * @param searchRegex regex to search into file
+ * @param replace string to replace matching patterns
+ * @param fileRegex regex for file to find in current dir
+ * @param encoding encoding to use
+ * @throws IOException
+ * @since 1.1.2
+ */
+ public static void sed(String searchRegex,
+ String replace,
+ String fileRegex,
+ String encoding) throws IOException {
+ sed(searchRegex, replace, new File("."), fileRegex, encoding);
+ }
+
+ /**
+ * Create the directory (and his parents) if necessary.
+ *
+ * @param dir the directory to create if not exisiting
+ * @return {@code true} if directory was created, {@code false} if was no
+ * need to create it
+ * @throws IOException if could not create directory
+ * @since 1.3.2
+ */
+ public static boolean createDirectoryIfNecessary(File dir)
+ throws IOException {
+ if (!dir.exists()) {
+ boolean b = dir.mkdirs();
+ if (!b) {
+ throw new IOException("Could not create directory " + dir);
+ }
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Obtain a file from the given {@code rootDirectory}, applying given paths.
+ * <p/>
+ * For example with paths = a, b and c, then result is :
+ * <pre>
+ * root/a/b/c
+ * </pre>
+ *
+ * @param rootDirectory the root directory
+ * @param paths paths to apply
+ * @return the final file
+ * @since 2.2
+ */
+ public static File getFileFromPaths(File rootDirectory, String... paths) {
+ File result = rootDirectory;
+ for (String path : paths) {
+ result = new File(result, path);
+ }
+ return result;
+ }
+
+ /**
+ * Obtain a file fro the given {@code rootDirectory}, applying the fqn.
+ * <p/>
+ * For example with fqn = a.b.c, the result is :
+ * <pre>
+ * root/a/b/c
+ * </pre>
+ *
+ * @param rootDirectory the root directory
+ * @param fqn fqn of searched file
+ * @return the final file
+ * @since 2.2
+ */
+ public static File getFileFromFQN(File rootDirectory, String fqn) {
+ String[] paths = fqn.split("\\.");
+
+ File result = getFileFromPaths(rootDirectory, paths);
+ return result;
+ }
+
+} // FileUtil
Property changes on: trunk/nuiton-utils/src/test/resources/org/nuiton/util/fileUtilData.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
1
0
Author: tchemit
Date: 2011-05-14 13:44:58 +0200 (Sat, 14 May 2011)
New Revision: 2139
Url: http://nuiton.org/repositories/revision/nuiton-utils/2139
Log:
Update mavenpom4redmineAndCentral to 2.5.4.
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2011-05-13 14:21:10 UTC (rev 2138)
+++ trunk/pom.xml 2011-05-14 11:44:58 UTC (rev 2139)
@@ -33,7 +33,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>mavenpom4redmineAndCentral</artifactId>
- <version>2.5.3</version>
+ <version>2.5.4</version>
</parent>
<artifactId>nuiton-utils-parent</artifactId>
1
0
Author: tchemit
Date: 2011-05-13 16:21:10 +0200 (Fri, 13 May 2011)
New Revision: 2138
Url: http://nuiton.org/repositories/revision/nuiton-utils/2138
Log:
Evolution #1525: Updates to i18n 2.4 (using utf-8 i18n files)
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2011-05-13 09:07:31 UTC (rev 2137)
+++ trunk/pom.xml 2011-05-13 14:21:10 UTC (rev 2138)
@@ -183,7 +183,7 @@
<projectId>nuiton-utils</projectId>
- <nuitonI18nVersion>2.4-SNAPSHOT</nuitonI18nVersion>
+ <nuitonI18nVersion>2.4</nuitonI18nVersion>
<aspectwerkzVersion>2.0</aspectwerkzVersion>
<xworkVersion>2.2.1.1</xworkVersion>
1
0