lundi 8 avril 2013

Compilation via Maven et UTF-8

Pour forcer la compilation via maven en prenant en charge l'UTF-8, définir les propriétés suivantes :

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
        <encoding>${project.build.sourceEncoding}</encoding>
    </configuration>
</plugin>

Et voilà :)

cf. https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html

dimanche 7 avril 2013

Appeler un processus (Imagemagick) en python

Voici un petit exemple de code en python permettant d'appeler un processus externe.
Dans cet exemple, nous appelons "imagemagick" pour effectuer le redimensionnement des images contenues dans un répertoire vers deux dimensions.

#!/usr/bin/python

from glob import glob
from subprocess import check_call, CalledProcessError
import os

class ConvertError(Exception):
    """Error while trying to convert.
    """

root_path = '/home/user/Bureau/'
ext = '.jpg'
files = glob(root_path + '*' + ext)

try:
    os.mkdir(root_path + "150/")
except OSError:
    pass

try:
    os.mkdir(root_path + "650/")
except OSError:
    pass

for f in files:
    folder_path, file_name = os.path.split(f);
    img_150_path = root_path + '_150' + ext
    img_650_path = root_path + '_650' + ext
    try:
        check_call(["convert", f, "-resize", "150x150", "-quality", "80", root_path + "150/" + file_name])
        check_call(["convert", f, "-resize", "650x900", "-quality", "80", root_path + "650/" + file_name])
    except CalledProcessError:
        raise ConvertError("Error converting")
    try:
        os.renames(f, root_path + "ori/" + file_name)
    except OSError:
        raise ConvertError("Error renaming")

mercredi 6 mars 2013

Archive multi-image

Voici un exemple de classe permettant de regrouper plusieurs images dans une archive unique.

L'archive présente la structure suivante :
- Version : 1 byte
- Count   : 1 integer
{ offsetStart : 1 integer | length : 1 integer }
# --> cible : { offsetStart : 1 integer | length : 1 integer | type : 1 byte }#
{ filesContent }

Quatre commandes permettent de constituer et manipuler les archives d'images :
  • pack
Cette commande permet de constituer une archive d'image à partir d'un répertoire contenant des images.
Exemple : pack("/~/imgArcTest", 355);
  • unpack
Cette commande permet d'extraire une image d'une archive d'images.
Exemple : unpack("/~/imgArcTest", "Test-355.img", 355);
  • unpackAll
Cette commande permet d'extraire toutes les images d'une archive d'images.
Exemple : unpackAll("/~/imgArc/Test", "Test-355.img");
  • unpackrange
Cette commande permet d'extraire une série d'images d'une archive d'images.
Exemple : unpackRange("/~/imgArc/Test", "Test-355.img", 200, 225);

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * Concatène des fichers (de type image) dans un fichier archive dont la structure est la suivante :
 * - Version : 1 byte
 * - Count    : 1 integer
 * { offsetStart : 1 integer | length : 1 integer }
 * # --> cible : { offsetStart : 1 integer | length : 1 integer | type : 1 byte }#
 * { filesContent }
 * 
 * @author ede
 */
public class ImageArchive {

    /**
     * Numéro de version du format
     */
    private final static byte VERSION=1;

    /**
     * Taille du buffer d'écriture (et de lecture)
     */
    private final static int BUFFER_SIZE=40960;
    
    /**
     * Pattern des fichiers lus.
     * Ex : x-001.png
     */
    public static String ENCODE_PREFIX="x-";
    public static int DIGIT_NUMBER=3;
    public static String ENCODE_SUFIX=".png";

    /**
     * Pattern des fichiers extraits.
     */
    public static String DECODE_PREFIX=ENCODE_PREFIX;
    public static String DECODE_SUFIX=ENCODE_SUFIX;

    
    /**
     * Package un ensemble d'images dans une archive
     * 
     * @param path : Chemin d'accès aux fichiers à packager.
     * @param count : Nombre de fichier à packager. L'index commence à 0.
     * @param destFilename : Nom du fichier à prendre en compte.
     * @return Chemin d'accès au fichier packagé
     */
    public static String pack(final String path, final int count, final String destFilename) {
        
        FileInputStream fis = null;
        RandomAccessFile raf = null;
        byte[] b = new byte[BUFFER_SIZE];
        int offsetStart=0;
        int length=1+4+count*8;
        int len = -1;
        String oPath = path+File.separator+destFilename;
        
        try {
            raf = new RandomAccessFile(oPath, "rw");
            raf.writeByte(VERSION);
            raf.writeInt(count);
            for(int i=0; i<count; i++) {
                fis = new FileInputStream(path+File.separator+ENCODE_PREFIX+format(i+1,DIGIT_NUMBER)+ENCODE_SUFIX);
                offsetStart+=length;
                raf.seek(offsetStart);
                length=0;
                while((len = fis.read(b)) >= 0) {
                    raf.write(b,0,len);
                    length+=len;
                }
                raf.seek(1+4+i*8);
                raf.writeInt(offsetStart);
                raf.writeInt(length);
            }
            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        return oPath;
    }
    
    /**
     * Extrait les fichiers contenu dans une archive.
     * 
     * @param path : Chemin d'accès au répertoire contenant le fichier archive source
     * @param filename : Nom du fichier archive à partir duquel extraire
     * @return Chemin d'accès au répertoire contenant les fichiers extraits
     */
    public static String unpackAll(final String path, final String filename) {
        
        byte version;
        FileOutputStream fos = null;
        RandomAccessFile raf = null;
        int count = 0;
        byte[] b = new byte[BUFFER_SIZE];
        int offsetStart = 0;
        int length = 0;
        int num = 0;
        int mod = 0;
        File f = null;
        
        try {
            raf = new RandomAccessFile(path+File.separator+filename, "r");
            version = raf.readByte();
            count = raf.readInt();
            for(int i=0; i<count; i++) {
                raf.seek(1+4+i*8);
                offsetStart = raf.readInt();
                length = raf.readInt();
                
                raf.seek(offsetStart);
                
                f = new File(path+File.separator+"unpack"+File.separator+DECODE_PREFIX+format(i,DIGIT_NUMBER)+DECODE_SUFIX);
                if(f.createNewFile()) {
                    fos = new FileOutputStream(f, true);
                    
                    num = length / BUFFER_SIZE;
                    mod = length % BUFFER_SIZE;
                    for(int j=0; j<num; j++) {
                        raf.read(b);
                        fos.write(b);
                        fos.flush();
                    }
                    raf.read(b,0,mod);
                    fos.write(b,0,mod);
                    fos.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos!=null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        return path+File.separator+"unpack";
    }
 
    /**
     * Extrait le fichier contenu dans une archive correspondant à l'index donné.
     *
     * @param path : Chemin d'accès au répertoire contenant le fichier archive source
     * @param filename : Nom du fichier archive à partir duquel extraire
     * @param index : index du fichier à extraire. L'index commence à 0.
     * @return Chemin d'accès au répertoire contenant les fichiers extraits
     */
    public static String unpack(final String path, final String filename, final int index) {
       
        byte version;
        FileOutputStream fos = null;
        RandomAccessFile raf = null;
        byte[] b = new byte[BUFFER_SIZE];
        int offsetStart = 0;
        int length = 0;
        int num = 0;
        int mod = 0;
        File f = null;
        int count = 0;

        try {
            raf = new RandomAccessFile(path+File.separator+filename, "r");
            version = raf.readByte();
            count = raf.readInt();
            if (index<0 || index>count)
                throw new ArrayIndexOutOfBoundsException();

            raf.seek(1+4+index*8);
            offsetStart = raf.readInt();
            length = raf.readInt();
               
            raf.seek(offsetStart);
               
            f = new File(path+File.separator+"unpack"+File.separator+DECODE_PREFIX+format(index,DIGIT_NUMBER)+DECODE_SUFIX);
            if(f.createNewFile()) {
                fos = new FileOutputStream(f, true);
                   
                num = length / BUFFER_SIZE;
                mod = length % BUFFER_SIZE;
                for(int j=0; j<num; j++) {
                    raf.read(b);
                    fos.write(b);
                    fos.flush();
                }
                raf.read(b,0,mod);
                fos.write(b,0,mod);
                fos.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos!=null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
       
        return path+File.separator+"unpack";
    }
   
    /**
     * Extrait le fichier contenu dans une archive correspondant à l'index donné.
     *
     * @param path : Chemin d'accès au répertoire contenant le fichier archive source
     * @param filename : Nom du fichier archive à partir duquel extraire
     * @param index1 : index inférieur de la plage de fichiers à extraire. L'index commence à 0.
     * @param index2 : index supérieur de la plage de fichiers à extraire.
     * @return Chemin d'accès au répertoire contenant les fichiers extraits
     */
    public static String unpackRange(final String path, final String filename, final int index1, final int index2) {
       
        byte version;
        FileOutputStream fos = null;
        RandomAccessFile raf = null;
        int count = 0;
        byte[] b = new byte[BUFFER_SIZE];
        int offsetStart = 0;
        int length = 0;
        int num = 0;
        int mod = 0;
        File f = null;
       
        try {
            raf = new RandomAccessFile(path+File.separator+filename, "r");
            version = raf.readByte();
            count = raf.readInt();
           
            if (index1<0 || index2>count || index1>index2)
                throw new ArrayIndexOutOfBoundsException();
           
            for(int i=index1; i<index2; i++) {
                raf.seek(1+4+i*8);
                offsetStart = raf.readInt();
                length = raf.readInt();
               
                raf.seek(offsetStart);
               
                f = new File(path+File.separator+"decode"+File.separator+DECODE_PREFIX+format(i,DIGIT_NUMBER)+DECODE_SUFIX);
                if(f.createNewFile()) {
                    fos = new FileOutputStream(f, true);
                   
                    num = length / BUFFER_SIZE;
                    mod = length % BUFFER_SIZE;
                    for(int j=0; j<num; j++) {
                        raf.read(b);
                        fos.write(b);
                        fos.flush();
                    }
                    raf.read(b,0,mod);
                    fos.write(b,0,mod);
                    fos.flush();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos!=null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
       
        return path;
    }      
    /**
     * Produit un compteur de fichier formaté de la forme suivante :
     * 001, 002, ..., 00N sur 3 digits.
     *
     * @param num : index à formater
     * @param size : nombre de digit à prendre en compte
     * @return Compteur formaté
     */
    private static String format(int num, int size) {
   
        String str=Integer.toString(num);       
        while(str.length()<size) {
            str = "0"+str;
        }
        return str;
    }
   
    /**
     * Méthode de test...
     *
     * @param args
     */
    public static void main(String[] args) {

        long t0 = System.currentTimeMillis();
       
        ENCODE_PREFIX = "x-";
        ENCODE_SUFIX = ".png";
        DECODE_PREFIX = "y-";
        //ENCODE_SUFIX = ".png";
       
        if ("-pack".equals(args[0])) {
            String path = args[1];
            int count = Integer.parseInt(args[2]) ;
            pack(path, count, "Test-"+count+".img");           
        }
       
        if ("-unpackAll".equals(args[0])) {
            String path = args[1];
            String name = args[2];
            unpackAll(path, name);           
        }

        if ("-unpack".equals(args[0])) {
            String path = args[1];
            String name = args[2];
            int count = Integer.parseInt(args[3]) ;
            unpack(path, name, count);           
        }

        if ("-unpackRange".equals(args[0])) {
            String path = args[1];
            String name = args[2];
            int index1 = Integer.parseInt(args[3]);
            int index2 = Integer.parseInt(args[4]);
            unpackRange(path, name, index1, index2);           
        }

        long t1 = System.currentTimeMillis();
        System.out.println("--> time="+(t1-t0));

//        unpackAll("/~/imgArc/Test", "Test-355.img");
//        unpack("/~/imgArcTest", "Test-355.img", 355);
//        unpackRange("/~/imgArc/Test", "Test-355.img", 200, 225);
    }
}

dimanche 17 février 2013

DavMail : configuration


Davmail est outils permettant d'interagir avec un serveur Microsoft Exchange et offrant une interface POP et IMAP. Concrétement, il permet d'accéder aux boites aux lettres Exchange depuis Linux (Thunderbird par exemple).

Une fois installé, l'outil est accessible à l'emplacement suivant : /usr/bin/davmail
Il s'agit d'un script exécutant les modules suivants :

#!/bin/sh
export LD_LIBRARY_PATH=/usr/lib/jni
for i in /usr/share/davmail/lib/*; do export CLASSPATH=$CLASSPATH:$i; done
java -Xmx128M -cp /usr/share/davmail/davmail.jar:/usr/share/java/swt.jar:$CLASSPATH davmail.DavGateway "$@"

Remarques : Même si techniquement, davmail peut s'exécuter avec 64 Mo de mémoire vive, en pratique, 128 Mo est préférable (dès lors que la messagerie contient de nombreux messages).

Le fichier de configuration est accessible à l'emplacement suivant : ~/.davmail.properties

davmail.allowRemote=false
davmail.bindAddress=
davmail.caldavAlarmSound=
davmail.caldavEditNotifications=false
davmail.caldavPastDelay=90
davmail.caldavPort=1080
davmail.clientSoTimeout=
davmail.defaultDomain=
davmail.disableGuiNotifications=false
davmail.disableUpdateCheck=false
davmail.enableEws=auto
davmail.enableProxy=false
davmail.forceActiveSyncUpdate=false
davmail.imapAutoExpunge=true
davmail.imapIdleDelay=
davmail.imapPort=1143
davmail.keepDelay=30
davmail.ldapPort=1389
davmail.logFilePath=
davmail.logFileSize=
davmail.noProxyFor=
davmail.popMarkReadOnRetr=false
davmail.popPort=1110
davmail.proxyHost=
davmail.proxyPassword=
davmail.proxyPort=
davmail.proxyUser=
davmail.sentKeepDelay=90
davmail.server=false
davmail.server.certificate.hash=
davmail.showStartupBanner=true
davmail.smtpPort=1025
davmail.smtpSaveInSent=true
davmail.ssl.clientKeystoreFile=
davmail.ssl.clientKeystorePass=
davmail.ssl.clientKeystoreType=
davmail.ssl.keyPass=
davmail.ssl.keystoreFile=
davmail.ssl.keystorePass=
davmail.ssl.keystoreType=
davmail.ssl.nosecurecaldav=false
davmail.ssl.nosecureimap=false
davmail.ssl.nosecureldap=false
davmail.ssl.nosecurepop=false
davmail.ssl.nosecuresmtp=false
davmail.ssl.pkcs11Config=
davmail.ssl.pkcs11Library=
# ex : https://myexchangeserver/owa/
davmail.url=<URL_SERVER>
davmail.useSystemProxies=true
log4j.logger.davmail=INFO
log4j.logger.httpclient.wire=INFO
log4j.logger.org.apache.commons.httpclient=INFO
log4j.rootLogger=INFO

vendredi 1 février 2013

Streamripper

Voici un petit outil bien pratique pour enregistrer des flux streamés (webradio, webtv, etc.) : streamripper.

Exemple de commande :

streamripper http://str0.creacast.com:80/pharefm --xs_offset=-2000


jeudi 24 janvier 2013

Simple MFP Daemon

Si, après l'installation du pilote "Samsung Unified Linux Driver", vous observez une tâche smfpd consommant en permanence du temps CPU, sachez qu'il est possible (dans la plupart des cas) de désinstaller cette tâche sans impact pour le bon fonctionnement de votre périphérique Samsung.

smfpd correspond à "Simple MFP Daemon". Ce deamon est exécuté en root et fournie un accès au port parallèle via le port tcp/8822.

Si votre périphérique n'est pas connecté au port parallèle, ce deamon n'est pas nécessaire.
Pour le desinstaller, exécuter les commandes suivantes :

sudo rm /etc/init.d/smfpd

sudo rm /etc/rc*.d/*smfpd


Et voilà ;-)

dimanche 20 janvier 2013

Ubuntu : Nettoyer son systeme et récupérer de l'espace


1. Supprimer les fichiers temporaires des fichiers d'installation

Supprimer uniquement les paquets périmés :
sudo apt-get autoclean

Supprimer tous les paquets téléchargés et installés :
sudo apt-get autoremove

2. Supprimer des logiciels

Supprimer des logiciels en sauvegardant la configuration
sudo apt-get remove <progname>

Supprimer des logiciels en supprimant la configuration
sudo apt-get purge <progname>

3. Supprimer des fichiers de sauvegarde (sans confirmation) :
find ~/ -name '*~' -print0 | xargs -0 rm


4. Supprimer des anciens noyaux

Vérifier quel noyau est utilisé :
uname -r

Lister les noyaux installés :
dpkg -l | grep -Ei "linux-headers|linux-image"

Exemple de commande de desinstallation d'un noyau :
sudo apt-get remove linux-headers-3.2.0-33 linux-headers-3.2.0-33-generic linux-image-3.2.0-33-generic linux-image-3.2.0-33-generic --purge


Related Posts Plugin for WordPress, Blogger...