lundi 26 janvier 2009

Traiter les espace dans les lignes de commande

Le traitement des espaces dans les lignes de commande peut-être délicat dans les lignes de commande linux.

mkdir convert/
ls *.dat|
while read i
do
i=${i/ /espace}
i=${i/ /espace}
i=${i/ /espace}
i=${i/ /espace}
i=${i/ /espace}
i=${i/ /espace}
i=${i/ /espace}
i=${i/ /espace}
i=${i/ /espace}
i=${i/espace/\\ }
i=${i/espace/\\ }
i=${i/espace/\\ }
i=${i/espace/\\ }
i=${i/espace/\\ }
i=${i/espace/\\ }
i=${i/espace/\\ }
i=${i/espace/\\ }
i=${i/espace/\\ }
echo sox -c1 $i convert/$i remix 1
done

mardi 16 décembre 2008

Faire un appender suffixé par la date

Cette classe permet de faire un appender qui suffixe la date.
package myprog.util;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.FileAppender;

public class DateFileAppender extends FileAppender {

private String datePattern = "yyyyMMddhhmm";

public void setFile(String strFile) {
String strDate;
SimpleDateFormat sdf;

if (datePattern!=null && strFile!=null) {
sdf = new SimpleDateFormat(datePattern);
strDate = sdf.format(new Date());
fileName = strFile.replaceAll("%date%", strDate);
} else {
System.err.println("Either File or DatePattern options are not set for appender [" + name + "].");
}
}

public String getDatePattern() {
return datePattern;
}

public void setDatePattern(String datePattern) {
this.datePattern = datePattern;
}
}



Pour l'utiliser dans le fichier log4j

log4j.appender.F1=myprog.util.DateFileAppender
log4j.appender.F1.File=log/extract-generated-%date%.log
log4j.appender.F1.layout=org.apache.log4j.PatternLayout
log4j.appender.F1.layout.ConversionPattern=%m%n

vendredi 5 décembre 2008

Utiliser XStream rapidement


Méthodes importantes



Definir une classes



alias("MY_TABLE", MyType.class);


Definir un champ



aliasField("MY_TABLE", MyType.class, "fieldName");


Definir un attribut



aliasAttribute(MyType.class, "fieldName","attribute-name");


Ignorer des champs



omitField(CaptureSacapt.class, "mareeId");


Questions diverses



Utiliser un format de date compatible avec les XSD



registerConverter(new ISO8601DateConverter());


Il est nécessaire pour ceci d'ajouter à son fichier POM

<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>1.5.2</version>
</dependency>



Changer l'ordre des champs


La manière la plus simple de changer l'ordre d'apparition des balise dans le XML généré est tout simplement de changer l'ordre des champs à l'intérieur de la classe.

L'autre méthode consiste à se servir d'un trieur de champs.

SortableFieldKeySorter sorter = new SortableFieldKeySorter();
sorter.registerFieldOrder(MyType.class,
new String[] { "firstToSerialize",
"secondToSerialize",
"thirdToSerialize" }
);
xstream = new XStream(new Sun14ReflectionProvider(new FieldDictionary( sorter)));



Les éléments nuls


Il n'existe pas de manière simple de traiter les chaine vide comme des nulles. Il est nécessaire d'implémenter un convertisseur et de l'enregistrer.


Validation par XSD


Un XML est validé par XSD

SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
sp.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
InputStream schemaIs = getClass().getResourceAsStream("/my-validator.xsd");
sp.setProperty(JAXP_SCHEMA_SOURCE, schemaIs);
XSDHandler handler = new XSDHandler();
sp.parse(file, handler);

mardi 28 octobre 2008

Generators in Hibernate Annotations

Identity generator in hibernate

@Id 
@GeneratedValue (strategy=GenerationType.IDENTITY)
@Column(name = "REJ_CDN")
int id;



* Tested with Sybase

Increment generator in hibernate

@Id
@GeneratedValue(generator = "autoincrement")
@GenericGenerator(strategy = "increment", name = "autoincrement")
@Column(name = "MYID")
Integer id;


* Tested with Sybase

vendredi 24 octobre 2008

AJP13 avec apache

Pour router votre serveur apache vers le serveur tomcat, il faut utiliser un proxy, apache délègue sa requête au serveur tomcat. Ce mode de fonctionnement permet surtout de faire du load balancing et, lorsqu'il s'agit de servir des fichiers, utiliser la code natif plus performant de apache.

Après avoir installé et déclarés le module proxy_ajp_module dans le fichiers httpd.conf :

LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_connect_module modules/mod_proxy_connect.so
LoadModule proxy_ftp_module modules/mod_proxy_ftp.so
LoadModule proxy_http_module modules/mod_proxy_http.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so



Ajouter dans le fichier httpd.conf les lignes suivantes

Include conf/vhosts.d/*.conf
<Location /wiki >
AuthType Basic
AuthName "Restricted Files"
AuthUserFile /etc/apachepasswd
Require user wiki
ProxyPass ajp://localhost:8009/JSPWiki
ProxyPassReverse ajp://localhost:8009/JSPWiki
allow from all
</Location>
<Location /gestion >
ProxyPass ajp://localhost:8009/gestion
ProxyPassReverse ajp://localhost:8009/
allow from all
</Location>



Autrement, il est aussi possible de créer un fichier worker.properties
# worker "worker1" will talk to Tomcat listening on machine www.x.com at port 8007 using 2 lb factor
worker.list=worker1
worker.worker1.host=myhost
worker.worker1.port=9009
worker.worker1.lbfactor=2





# Update this path to match your conf directory location (put workers.properties next to httpd.conf)
JkWorkersFile /etc/httpd/conf/worker.properties
# Where to put jk shared memory
# Update this path to match your local state directory or logs directory
JkShmFile /var/log/httpd/mod_jk.shm
# Where to put jk logs
# Update this path to match your logs directory location (put mod_jk.log next to access_log)
JkLogFile /var/log/httpd/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel info
# Select the timestamp log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
# Send everything for context /examples to worker named worker1 (ajp13)
JkMount /ft-jobs/* worker1


Changer l'URL


Pour configurer de manière centralisée les applications, il est possible d'utiliser un apache frontal et de repartir les adresses vers des serveurs mandatataires, apache agit donc comme un proxy et il suffit d'ajouter la ligne suivante dans le fichier httpd.conf
Par exemple si la machine vm04 est le frontal et que le serveur hudson est sur la vm04, il suffit d'ajouter la ligne suivante au fichier httpd.conf


ProxyPass /hudson/ http://vm04:8080/hudson/


On accedera à hudson par l'url http://vm01/hudson/



Faire du load balancing


Solution n°1


<Location /jonas>
ProxyPass balancer://mycluster/
ProxyPassReverse balancer://mycluster/
Allow From All
</Location>


<Proxy balancer://mycluster>
BalancerMember ajp://localhost:9009/myapp
BalancerMember ajp://localhost:8009/myapp
</Proxy>


Solution n°2




ProxyPass http://localhost/myapp/
ProxyPassReverse /myapp/
Allow From All


JkWorkersFile /etc/httpd/conf/worker.properties
JkShmFile /var/log/httpd/mod_jk.shm
access_log)
JkLogFile /var/log/httpd/mod_jk.log
JkLogLevel info
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
JkMount /myapp/* worker1

mardi 21 octobre 2008

No Dialect mapping for JDBC type: -1

org.hibernate.MappingException: No Dialect mapping for JDBC type: -1

Was provoked by :

String query = "SELECT * FROM MYTABLE WHERE MYID=? "
+ "AND MYCRITERIA >= ?";
SQLQuery sqlQuery;
sqlQuery = session.createSQLQuery(query);
sqlQuery.setString(0, code);
sqlQuery.setDate(1, date);
List<string> ports = sqlQuery.list();


The cause was I could not to use the *, I had to specify each field instead.

How to copy a file on webdav using common-httpclient ?

Webdav technology allow sharing files with internet. WebDav is a filesytem interface relying on http protocol, a non transactionnal. Webdav manages files whithout locking and work using a versionning system in order to continue working for multiple users. A tricky mecanism for holding concurrent versions lay behind the scene, but if you plan to use WebDav like you'd use a samba filesytem, you may not care understanding of the hidden processes.

If your on a local network, you'd still prefer more standard file system for convenience.

In java, you can use the generic http client commons-httpclient to put your files on a webdav server. I give you a sample code that let you create a file on the server and then DELETE it. Somme more sophisticated operations can be performed with the jackrabbit-webdav library, it will provide you with more operations.

HostConfiguration hostConfig = new HostConfiguration();
hostConfig.setHost("targetserver");
HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = new HttpConnectionManagerParams();
int maxHostConnections = 20;
params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
connectionManager.setParams(params);
HttpClient client = new HttpClient(connectionManager);
Credentials creds = new UsernamePasswordCredentials("username","password");
client.getState().setCredentials(AuthScope.ANY, creds);
client.setHostConfiguration(hostConfig);
PutMethod putMethod = new PutMethod(
"http://targetserver:8080/webdav/targetfilename");
FileInputStream is = new FileInputStream("myfile.pdf");
InputStreamRequestEntity requestEntity = new InputStreamRequestEntity(is);
putMethod.setRequestEntity(requestEntity);
client.executeMethod(putMethod);
System.out.println(putMethod.getStatusCode() + " "
+ putMethod.getStatusText());


You could have to sort of status code :
201 Created (A file has been created)
204 No data(The http response has no data, but the operation has performed correctly)

And to delete a file :



DeleteMethod deleteMethod = new DeleteMethod(
"http://targetserver:8080/webdav/targetfilename");
client.executeMethod(deleteMethod);
System.out.println(putMethod.getStatusCode() + " "
+ putMethod.getStatusText());