mardi 6 mars 2012

[JAVA] JDOM - Ne pas parser un XML

Bonjour,

Dans le cas où on utilise JDOM pour parser un fichier XML en java et que ce fichier XML contient une balise doctype  :

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">

Pour parser ce XML, on commence comme ceci :

SAXBuilder sxb = new SAXBuilder();
try{
       document = sxb.build(strutsConfig);
}
catch (Exception e)
{
       System.out.println(e.getMessage());
}

Le problème est lorsque l'on travaille en local ( sans accès à internet ), la validation du XML va échouer car il n'arrivera pas à atteindre l'URL contenue dans le doctype :http://struts.apache.org/dtds/struts-config_1_2.dtd
Et on obtiendra une erreur dans ce genre là : Connection timed out: connect

Dans ce cas là, on peut indiquer à JDOM de ne pas vérifier le XML :

SAXBuilder sxb = new SAXBuilder();
sxb.setValidation(false);
sxb.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
try{
       document = sxb.build(strutsConfig);
}
catch (Exception e)
{
       System.out.println(e.getMessage());
}

Et maintenant ça marche.

mardi 28 février 2012

[JAVA] Eclipse shared images - ISharedImages

On peut avoir besoin (même surement besoin) pour le développement d'un plugin ou d'une application RCP d'utiliser des icônes. On peut dans ce cas là se servir des images que Eclipse partage comme ceci :

PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_DEF_VIEW);

Ci-dessous la liste des images correspondantes aux clés de ISharedImages.*

IMG_DEF_VIEW

IMG_OBJS_BKMRK_TSK

IMG_OBJS_ERROR_TSK

IMG_OBJS_INFO_TSK

IMG_OBJS_TASK_TSK

IMG_OBJS_WARN_TSK

IMG_OBJ_FILE

IMG_OBJ_FOLDER

IMG_OBJ_PROJECT

IMG_OBJ_PROJECT_CLOSED

IMG_OPEN_MARKER

IMG_TOOL_BACK

IMG_TOOL_BACK_DISABLED

IMG_TOOL_BACK_HOVER

IMG_TOOL_COPY

IMG_TOOL_COPY_DISABLED

IMG_TOOL_COPY_HOVER

IMG_TOOL_CUT

IMG_TOOL_CUT_DISABLED

IMG_TOOL_CUT_HOVER

IMG_TOOL_DELETE

IMG_TOOL_DELETE_DISABLED

IMG_TOOL_DELETE_HOVER

IMG_TOOL_FORWARD

IMG_TOOL_FORWARD_DISABLED

IMG_TOOL_FORWARD_HOVER

IMG_TOOL_NEW_WIZARD

IMG_TOOL_NEW_WIZARD_DISABLED

IMG_TOOL_NEW_WIZARD_HOVER

IMG_TOOL_PASTE

IMG_TOOL_PASTE_DISABLED

IMG_TOOL_PASTE_HOVER

IMG_TOOL_REDO

IMG_TOOL_REDO_DISABLED

IMG_TOOL_REDO_HOVER

IMG_TOOL_UNDO

IMG_TOOL_UNDO_DISABLED

IMG_TOOL_UNDO_HOVER

IMG_TOOL_UP

IMG_TOOL_UP_DISABLED

IMG_TOOL_UP_HOVER

Bon courage.


mercredi 28 décembre 2011

[UNIX] Trouver le PID d'un processus qui n'apparait plus

J'ai souvent eu le cas d'un processus qui n'avait pas de PID quand je faisais un pgrep "monProcess".
Voici donc la commande qui me permet de récuper son PID :

ps -ef|grep -v grep|grep 'monProcess' | while read user pid filler; do print $pid; done

*Remplacer monProcess par la chaine du processus à rechercher.

Elle renvoie tous les PID des processus correspondants.

mardi 27 décembre 2011

[UNIX] Trouver le processus qui écoute ce port

Voici un petit script qui permet de déterminer quel est le processus qui écoute le port indiqué.
Pratique pour déterminer si un port est utilisé et surtout par qui.


#
# Script recherchant le processus qui ecoute un port TCP
#

if [ $# -ne 1 ]
then
    echo "$0 <PORT NUMBER>"
    exit 1
fi 

PORT_NUM=$1
#netstat -Aan | egrep "\.$PORT_NUM\ "| grep LISTEN| awk '{print "echo port:"$5";rmsock "$1" tcpcb"}'|ksh
PID=`netstat -Aan | egrep "\.$PORT_NUM\ "| grep LISTEN| awk '{print "rmsock "$1" tcpcb"}'|ksh|sed 's/^The socket .* is being held by proccess \([0-9]*\).*$/\1/g'`
#echo Le PID est $PID

if [ $PID ]
then
    ps -f -p $PID
else
        echo "Aucun processus trouve en ecoute du port $PORT_NUM"
    exit 2
fi

Exemple :

mercredi 21 décembre 2011

[Utilitaire] - Capture d'écran

Gadwin Print Screen est un petit utilitaire bien pratique pour faire des captures d'écran.
Pour ma part je recherchai un outil simple qui permettait en appuyant sur une seule touche de pouvoir faire un aperçu d'écran d'un zone que je sectionne moi même.
En bref, c'est un outil bien complet.

Lien de téléchargement : http://www.gadwin.com/download/




mardi 20 décembre 2011

[JAVA] Connexion LDAP en java

Besoin :
  • Connexion à un LDAP en SSL
  • Ajouter des groupes ( organizationalUnit et group )
  • Ajout des users
  • Changer son mot de passe
  • Ajouter l'utilisateur à un groupe
  • Le tout en java
Donc pour cela j'ai utilisé la bibliothèque déjà inclue dans java :

Classe permettant d’interagir avec l'annuaire
package tools;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NameAlreadyBoundException;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.AttributeInUseException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;

public class LdapTool {

    private DirContext context;

    /**
     * Connexion au LDAP
     * @param url
     * @param port
     * @param base
     * @param password
     * @throws NamingException
     */
    public void connect(String url, int port, String base, String password)
            throws NamingException {
        Hashtable<String, Object> env = new Hashtable<String, Object>(11);
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");
        // Bien spécifier le port non SSL
        env.put(Context.PROVIDER_URL, url + ":" + port);
        // Authentification en mode simple
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, base);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.SECURITY_PROTOCOL, "ssl");
        context = new InitialDirContext(env);

    }

    /**
     * Permet de créer un groupe organizationalperson (OU)
     */
    public void createUser(String distinguishedName) throws NamingException {
        //Création des attributs à injecter
        Attributes newAttributes = new BasicAttributes(true);
        Attribute oc = new BasicAttribute("objectclass");
        oc.add("top");
        oc.add("person");
        oc.add("organizationalperson");
        oc.add("user");
        newAttributes.put(oc);
        // newAttributes.put(new BasicAttribute("memberOf",
        // "CN=Gestionnaire sinistre,OU=GROUPES,OU=ENTITE_GAM,DC=RACONIT2" ));
        context.createSubcontext("CN=" + distinguishedName, newAttributes);
    }

    /**
     * Permet de modifier un attribut
     * Si on ajouter un utilisateur à groupe, il suffit de modifier l'attribut member
     *
     * @throws NamingException
     */
    public void modifyAttributes(String distinguishedName, String attribut,
            String valeur) throws NamingException,AttributeInUseException {
        BasicAttribute att = new BasicAttribute(attribut);
        att.add(valeur);
        ModificationItem[] mod = new ModificationItem[1];
        mod[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, att);
        context.modifyAttributes(distinguishedName, mod);
    }

    /**
     * Permet de créer un groupe de type group (CN)
     */
    public void createGroup(String distinguishedName, String classGroup,
            String description) throws NamingException,
            NameAlreadyBoundException {
        Attributes newAttributes = new BasicAttributes(true);
        Attribute oc = new BasicAttribute("objectclass");
        oc.add("top");
        oc.add(classGroup);
        if (classGroup.equals("group")) {
        }
        if (!description.equals("")) {
            newAttributes.put(new BasicAttribute("description", description));
        }
        // Rajouter ici les parametres supplémetaires
        // newAttributes.put(new BasicAttribute("displayName", "test" ));*/
        newAttributes.put(oc);
        context.createSubcontext(distinguishedName, newAttributes);
    }

    /**
     * Permet de modifier le passord
     *
     * @throws NamingException
     */
    public void updatePassword(String distinguishedName, String password)
            throws NamingException {

        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
                new BasicAttribute("userPassword", password));
        context.modifyAttributes("CN=" + distinguishedName, mods);
    }

    /**
     *
     * @param distinguishedName
     * @throws NamingException
     */
    public void activateUser(String distinguishedName) throws NamingException {
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute("msDS-UserAccountDisabled", "FALSE"));
        context.modifyAttributes("CN=" + distinguishedName, mods);
    }

    /**
     * Permet de créer un utilisateur, de changer son mot de passe et d'activer son compte )
     * @param distinguishedName
     * @param password
     * @throws NamingException
     */
    public void createUserPasswordActivate(String distinguishedName, String password)
            throws NamingException {
        //Création du compte
        createUser(distinguishedName);
       
        //Assignation du mot de passe
        updatePassword(distinguishedName, password);
        //Activation du compte
        activateUser(distinguishedName);
    }
}

Classe de test :
String url = myProp.getProperty("monLDAP.fr");
int port = Integer.valueOf(myProp.getProperty("651"));
String base = myProp.getProperty("CN=TOTO,OU=UTILISATEURS,DC=DCBASE");
String password = myProp.getProperty("monPassword");

//Import du KeyStore - Nécessaire pour la connexion LDAP
String keystore = myProp.getProperty("keyStore.path");
System.setProperty("javax.net.ssl.trustStore", keystore);
System.setProperty("javax.net.ssl.keyStorePassword",  myProp.getProperty("keyStore.key"));

//Connexion au LDAP
mLdap.connect(url, port, base, password);
//Création d'un groupe
mLdap.createGroup("OU=Groupe1,DC=DCBASE,"oganizationalUnit", "Description du groupe");
mLdap.createGroup("CN=Groupe11,OU=Groupe1,DC=DCBASE,"group", "Description du groupe");
mLdap.createUserPasswordActivate("CN=monUser,CN=Groupe11,OU=Groupe1,DC=DCBASE","toto");
//Ajout de l'utilisateur au groupe
mLdap.modifyAttributes("CN=Groupe11,OU=Groupe1,DC=DCBASE "member", "CN=monUser,CN=Groupe11,OU=Groupe1,DC=DCBASE");