Junit et JMock - HttpServletRequest

31 January 2008

Voici un test unitaire Junit avec exemple de HttpServletRequest Mocké avec les méthodes getParameter et getParameterNames
public class ParametersUtilTest extends MockObjectTestCase {

private HttpServletRequest mRequest;

protected void setUp() throws Exception {

//initialisation de HttpServletRequest
Mock mock = new Mock(HttpServletRequest.class);

mock.expects(atLeastOnce()).method(”getParameter”).with(eq(Constantes.PARAM1))
.will(returnValue(”monParam1″));
mock.expects(atLeastOnce()).method(”getParameter”).with(eq(Constantes.PARAM2))
.will(returnValue(”monParam2″));

List parameters = new ArrayList();
parameters.add(Constantes.PARAM1);
parameters.add(Constantes.PARAM2);

Enumeration enumeration = Collections.enumeration(parameters);
mock.expects(atLeastOnce()).method(”getParameterNames”).will(returnValue(enumeration));

mRequest = (HttpServletRequest)mock.proxy();

}

public void testAddParameters() throws Exception {

mLogger.info(”DEB ********** testAddParameters **********”);

assertNotNull(mRequest.getParameter(Constantes.PARAM1));

//test construction parametres
assertEquals(ParametersUtil.addParameters(mRequest).toString(), “param1=monParam1&param2=monParam2″);

mLogger.info(”FIN ********** testAddParameters **********”);
}

}

EJB JMS

14 November 2007

Introduction
Les Message-driven Beans fournissent des modes d’acc√®s asynchrones comme sp√©fi√©dans les sp√©cifications EJB 2.0.
De plus, il est possible pour tout les EJB ( session, entity, ou Message-driven ) d’envoyer ou recevoir de fa√ßon ¬†synchrone des messages.Pour cela en plus de l’impl√©mentation, il faut penser param√©trer ses Queues et Factory sur le serveur d’application ( ici : Weblogic 8.1) .

ejb-Jar contenu de ejb-jar.xml :

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN” “http://java.sun.com/dtd/ejb-jar_2_0.dtd“>
<ejb-jar>
<display-name>Clint EJB</display-name>
<enterprise-beans>
<message-driven>
<display-name>AlerteMessageBean</display-name>
<ejb-name>AlerteMessageBean</ejb-name>
<ejb-class>fr.zieunoir.ejb.AlerteMessageBean</ejb-class>
<transaction-type>Container</transaction-type>
<message-driven-destination>
<destination-type>javax.jms.Queue</destination-type>
</message-driven-destination>
</message-driven>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<description />
<ejb-name>AlerteMessageBean</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>

weblogic-ejb-jar contenu de weblogic-ejb-jar.xml

<weblogic-enterprise-bean>
<ejb-name>AlerteMessageBean</ejb-name>
<message-driven-descriptor>
<pool>
<max-beans-in-free-pool>5</max-beans-in-free-pool>
<initial-beans-in-free-pool>5</initial-beans-in-free-pool>
</pool>
<destination-jndi-name>AlerteInfoQueue</destination-jndi-name>
<connection-factory-jndi-name>AlerteInfoFactory</connection-factory-jndi-name>
</message-driven-descriptor>
</weblogic-enterprise-bean>

messageManager La classe messageManager fait l’envoi des messages.

package fr.zieunoir.ejb;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
* Titre :
* Description :
* Copyright : Copyright (c) 2003
* Soci? :
* @author non attribuable
* @version 1.0
*/

public final class MessageManager {
protected Static Log log = LogFactory.getLog(
“fr.zieunoir.ejb.MessageManager”);

/** services */
private Static String alerteQueue = null;
private Static String alerteFactory = null;
private Static MessageManager instance = null;
private QueueConnectionFactory fatyinst = null;

    /**
* Constructeur privé    */

private MessageManager() {
alerteQueue = “AlerteInfoQueue”;
alerteFactory = “AlerteInfoFactory”;
}

    /**
* Retourne l’instance unique du Manager
* @return
*/

public Static synchronized MessageManager getInstance() {
if (instance == null) {
instance = new MessageManager();
}

return instance;
}

    /**
* Envoi un message avec des param?es
* @param typeAlerteAEnvoyer = sur/sous conso, depassement, energie reactive
*/

public void sendMessage(String typeAlerteAEnvoyer) {
QueueConnection cnx = null;
QueueSession session = null;
QueueSender sender = null;
Queue queue = null;
Message message = null;

cnx = getConnexion();

if (cnx != null) {
try {
session = getSession(cnx);
queue = getQueue();
sender = session.createSender(queue);
message = session.createMessage();
message.setStringProperty(”TYPE_ALERTE”, typeAlerteAEnvoyer);
sender.send(message);
} catch (JMSException ex) {
log.error(ex);
} finally {
try {
if (sender != null) {
sender.close();
}

if (session != null) {
session.close();
}

                    if (cnx != null) {
cnx.close();
}
} catch (JMSException ex) {
log.error(ex);
}
}
}
}

    /**
* retrouve un Factory pour l’instance
* @return QueueConnectionFactory
*/

private QueueConnectionFactory getFactory() {
QueueConnectionFactory factory = null;
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,
“weblogic.jndi.WLInitialContextFactory”);
env.put(Context.PROVIDER_URL, “t3://localhost:7001″);

        try {
Context ctx = new InitialContext(env);
factory = (QueueConnectionFactory) ctx.lookup(alerteFactory);
} catch (NamingException ex) {
log.error(ex);
}

        return factory;
}

    /**
* Récupération de la connexion
* @return QueueConnection
*/

private QueueConnection getConnexion() {
QueueConnection cnx = null;

if (fatyinst == null) {
fatyinst = getFactory();
}

        if (fatyinst != null) {
try {
cnx = fatyinst.createQueueConnection();

                //cnx = fatyinst.();
} catch (JMSException ex) {
log.error(ex);
}
}

return cnx;
}

  /**
* R√©cup√©ration¬†d’une session
* @return QueueSession
*/

private QueueSession getSession(QueueConnection pcnx) {
QueueSession session = null;

if (pcnx != null) {
try {
session = pcnx.createQueueSession(false,
QueueSession.AUTO_ACKNOWLEDGE);
} catch (JMSException ex) {
log.error(ex);
}
}

return session;
}

    /**
* R√©cur√©ation d’une queue dans l’annuaire
* @return Queue
*/

private Queue getQueue() {
Queue queue = null;
Properties env = new Properties();

env.put(Context.INITIAL_CONTEXT_FACTORY,
“weblogic.jndi.WLInitialContextFactory”);
env.put(Context.PROVIDER_URL, “t3://localhost:7001″);

try {
Context ctx = new InitialContext(env);
queue = (Queue) ctx.lookup(alerteQueue);
} catch (NamingException ex) {
log.error(ex);
}

return queue;
}
}

ejb-JMS La classe JMS qui fait le traitement des messages.

package fr.zieunoir.ejb;

import fr.zieunoir.dao.valerte.ValerteBean;
import fr.zieunoir.dao.valerte.ValerteManager;
import fr.zieunoir.service.ServiceLocatorException;

import org.apache.log4j.Logger;

import weblogic.ejb.GenericMessageDrivenBean;

import java.sql.SQLException;

import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
//to be done creer une queue jms et la configurer

/**
* @ejbgen:message-driven
*   ejb-name = AlerteMessageBean
*   destination-jndi-name = jms.DepecheJMSDestination
*   destination-type = javax.jms.Queue
*
* @ejbgen:ejb-ref type=”Session”¬†¬†¬†¬†¬†¬†¬† remote=”DataManipSession”
*¬†¬†¬†¬† home=”DataManipSessionHome”
*¬†¬†¬†¬† jndi-name=”ejb.DataManipSessionRemoteHome”
*¬†¬†¬†¬† name=”DataManipSession”
*
*/

public class AlerteMessageBean extends GenericMessageDrivenBean
implements MessageDrivenBean, MessageListener {
private Static final long serialVersionUID = 1L;
private transient Logger log = Logger.getLogger(AlerteMessageBean.class);
private MessageDrivenContext messageDrivenContext = null;

  /**
* Mode appell??a r?ption d’un message JMS,
* d?enche la mise ?our du canal de d?che spacifi?ans le message JMS
* @param Message le message JMS re?
*/
public void onMessage(Message msg) {
ValerteManager man = null;

        try {
man = ValerteManager.getInstance();
} catch (ServiceLocatorException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

        ValerteBean[] listeUser = null;
String sujetMail = null;
String urlJsp = null;

        try {
final String typeAlerteAEnvoyer = msg.getStringProperty(
“TYPE_ALERTE”);

¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† if (”1″.equals(typeAlerteAEnvoyer)) {
listeUser = man.loadDetailAlerte1();
sujetMail = “ZieunoirJMS : “;
urlJsp = “/jsp/externe/mail_mailAlerte.jsp”;
} else if (”2″.equals(typeAlerteAEnvoyer)) {
listeUser = man.loadDetailAlerte2();
sujetMail = “ZieunoirJMS : “;
urlJsp = “/jsp/externe/mail_mailPenalite.jsp”;
} else if (”3″.equals(typeAlerteAEnvoyer)) {
listeUser = man.loadDetailAlerte3();
sujetMail = “ZieunoirJMS : “;
urlJsp = “/jsp/externe/mail_mailEnergie.jsp”;
}

¬†¬†¬†¬†¬†¬†¬†¬†¬†¬†¬† log.debug(”sujetmail =” + sujetMail + “url JSP =” + urlJsp);
} catch (JMSException e) {
log.error(”Bad message type ” + e);
log.error(e);
} catch (SQLException e) {
log.error(”Bad message type ” + e);
log.error(e);
}
}

public void ejbCreate() {
}

    /**
* récupérattion du contexte jndi et message driven
* Methode de callback
*/

public void setMessageDrivenContext(
MessageDrivenContext messageDrivenContext) {
this.messageDrivenContext = messageDrivenContext;
}
}

weblogic Configuration de la console WEBLOGIC

penser à déclarer une Factory et une Queue sur la console weblogic dans les services

 

Lecture d’un BLOB

28 August 2007

set serveroutput on

spool monblob.txt

DECLARE
src_lob BLOB;
buffer RAW(32767);
amt BINARY_INTEGER := 32767;
pos INTEGER := 2147483647;
BEGIN
DBMS_OUTPUT.ENABLE(200000);

SELECT TAM_T_INFOS_SPEC INTO src_lob
FROM TAMPON;
LOOP
DBMS_OUTPUT.PUT_LINE(’Contenu du blob :’);
DBMS_LOB.READ(src_lob, amt, pos, buffer);

pos := pos + amt;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line(’Fin des donnees’);
END;

Astuce Ant pour supprimer tous les dossiers CVS d’un projet commit√©

16 August 2007

<delete includeEmptyDirs=”true”>
<fileset dir=”base”>
<include name=”**/CVS”/>
</fileset>
</delete>

Créer son plugin Maven 2

29 July 2007

Voici mon projet Eclipse en pi√®ce jointe qui va permettre de cr√©er rapidement son propre plugin Maven 2. Ainsi que de g√©n√©rer des rapports checkstyle, et autres …

A télécharger ici -> maven-perso-plugin.zip

How do I configure Apache 2.0.x to support ActivePerl?

28 July 2007

These instructions assume that you have installed the Apache web server according to the instructions for the 2.0.x Windows version.

  1. Open the httpd.conf file for editing by selecting Start > Programs > Apache HTTP Server > Configure Apache Server > Edit the Apache httpd.conf Configuration File.

    This will open your httpd.conf file in the notepad editor.

  2. Make the following changes to the httpd.conf file:
    • In the DocumentRoot section, set the value of DocumentRoot to the directory in which your web site files will be located on your system’s hard drive(s). Ensure that you use forward slashes (/) in the path, as Apache doesn’t understand backward slashes (\) in paths. For example:
      # DocumentRoot: The directory out of which you will serve your
      # documents. By default, all requests are taken from this directory, but
      # symbolic links and aliases may be used to point to other locations.
      #
      DocumentRoot "C:/apacheroot"
    • In the main directory section, add ExecCGI to the Options line. For example:
      Options FollowSymLinks ExecCGI
    • Search for the following line and remove the hash mark character (#) to uncomment this line. (You can also change .cgi to .pl if you prefer.) For example:
      #AddHandler cgi-script .cgi

      Should look like:

      AddHandler cgi-script .pl
  3. Save your changes to the httpd.conf file, and restart the Apache Service using the Apache Service Monitor.
  4. Test your configuration as described in the Testing Your Web Server Configuration section below.

Forcer Apache en HTTPS

27 June 2007

RewriteEngine on
RewriteLog “logs/rewrite.log”
RewriteLogLevel 3
RewriteCond %{SERVER_PORT} ^80$
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}

Créer une répertoire de plugin Eclipse

23 June 2007

Create an extension descriptor file with the following contents (eclipse/.eclipseextensions):

name=My Eclipse Configuration
id=my.eclipse.configuration
version=1.0.0

Cr√©ation d’un repository Maven distant

21 June 2007

Ajouter à votre fichier de conf apache les lignes suivantes

#
# Ajout Repository Maven
#
Alias /maven/repository “E:/Maven 1.0.2/repository/”
<Directory “E:/Maven 1.0.2/repository”>
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>

Commandes utiles

12 January 2007

UNIX

liste process java
/usr/ucb/ps -auxwwwww | grep java

recherche chaine de caracteres dans fichiers et ses sous -repertoire sans utiliser fgrep
find . -name *.ora -exec cat {} \; | grep LISTENER

ORACLE
lsnrctl start LISTENER
lsnrctl stop LISTENER
lsnrctl statut
lsnrctl services

export ORACLE_SID=[NOM_SID]
sqlplus /nolog
>connect /as sysdba

VI
copier entre la ligne 4 et 13 sur la ligne 3
4,13t 3

Afficher les numéros de lignes
:se nu

Recherche chaine
/chaine
[n] aller √† l’occurrence suivante
[N] aller √† l’occurrence pr√©cedente

Remplacer tout occurence d’une chaine dans un fichier
:%s/old/new/g

APACHE
apachectl -k restart


WordPress database error: [Table 'foubert.wp_ss_stats' doesn't exist]
INSERT INTO wp_ss_stats (remote_ip,country,language,domain,referer,resource,user_agent,platform,browser,version,dt) VALUES ('54.234.147.84','Indeterminable','en-us','','','/wordpress/','CCBot/2.0 (http://commoncrawl.org/faq/)','Indeterminable','Crawler/Search Engine','Indeterminable',1406542677)