Off the record

Aller au contenu | Aller au menu | Aller à la recherche

mardi 23 juin 2009

Attending Jazoon

Weather is quite bad here in Zürich but well, I don't mind too much as I'll be attending Jazoon, THE java dev conference in Europe. I'll be blogging mainly for my employer but I'll tweet a lot, stay tuned : http://twitter.com/#search?q=Jazoon

Right now, opening keynote by James Gosling ! Edit 12:10 James Gosling's keynote was excellent, presenting shocking numbers and funny projects, in a nutshell :

  • 10 billions Java enabled devices in the world (yes billions)
  • 15 millions downloads of the JRE Java Runtime Environment a week
  • 6 millions Java developpers

Projects mentioned, built on Java (of course) :

  • brazilian healthcare system
  • hadron collider in Geneva
  • eBay.com Orbitz.com
  • the Oyster card (London tube pass system)
  • www.lincvolt.com project transforming a 6000 pounds lincoln car into an electric car, power management done by Java o' course

Then James did a little demo of the 2 ground breaking features of Java EE6, annotated servlets and EJB injection in servlets. I knew already about it, but it remains extremely handy and simplifies the EE development a great deal !

The talk closed with a little Java FX note and the future of computers, heading to massively parrallel computing instead of increasing GHz on single cores.

Afternoon sessions i attended were "RIA, security broken by design" and "JSF and Ajax @ Credit Suisse", quite obvious for the second one !
The RIA session was mostly about demoing XSS attacks and why using a framework is a good idea to enhance the security, nothing much. On the other hand, the CS-Jsf and Ajax session by Micha Kiener was extremely interesting and will hopefully impact my daily work as of Q3 2009. (Wait a minute Q3, really?).

Jazoon updates are starting to pop all around the blogosphere, in french even...Great !

lundi 5 janvier 2009

Java certificates...code snippet.


/*
 * Copyright 2006 Sun Microsystems, Inc.  All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class InstallCert {

	public static void main(String[] args) throws Exception {
		String host;
		int port;
		char[] passphrase;
		if ((args.length == 1) || (args.length == 2)) {
			String[] c = args[0].split(":");
			host = c[0];
			port = (c.length == 1) ? 443 : Integer.parseInt(c[1]);
			String p = (args.length == 1) ? "changeit" : args[1];
			passphrase = p.toCharArray();
		} else {
			System.out
					.println("Usage: java InstallCert [:port] [passphrase]");
			return;
		}

		File file = new File("jssecacerts");
		if (file.isFile() == false) {
			char SEP = File.separatorChar;
			File dir = new File(System.getProperty("java.home") + SEP + "lib"
					+ SEP + "security");
			file = new File(dir, "jssecacerts");
			if (file.isFile() == false) {
				file = new File(dir, "cacerts");
			}
		}
		System.out.println("Loading KeyStore " + file + "...");
		InputStream in = new FileInputStream(file);
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		ks.load(in, passphrase);
		in.close();

		SSLContext context = SSLContext.getInstance("TLS");
		TrustManagerFactory tmf = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(ks);
		X509TrustManager defaultTrustManager = (X509TrustManager) tmf
				.getTrustManagers()[0];
		SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
		context.init(null, new TrustManager[] { tm }, null);
		SSLSocketFactory factory = context.getSocketFactory();

		System.out
				.println("Opening connection to " + host + ":" + port + "...");
		SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
		socket.setSoTimeout(10000);
		try {
			System.out.println("Starting SSL handshake...");
			socket.startHandshake();
			socket.close();
			System.out.println();
			System.out.println("No errors, certificate is already trusted");
		} catch (SSLException e) {
			System.out.println();
			e.printStackTrace(System.out);
		}

		X509Certificate[] chain = tm.chain;
		if (chain == null) {
			System.out.println("Could not obtain server certificate chain");
			return;
		}

		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));

		System.out.println();
		System.out.println("Server sent " + chain.length + " certificate(s):");
		System.out.println();
		MessageDigest sha1 = MessageDigest.getInstance("SHA1");
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		for (int i = 0; i < chain.length; i++) {
			X509Certificate cert = chain[i];
			System.out.println(" " + (i + 1) + " Subject "
					+ cert.getSubjectDN());
			System.out.println("   Issuer  " + cert.getIssuerDN());
			sha1.update(cert.getEncoded());
			System.out.println("   sha1    " + toHexString(sha1.digest()));
			md5.update(cert.getEncoded());
			System.out.println("   md5     " + toHexString(md5.digest()));
			System.out.println();
		}

		System.out
				.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
		String line = reader.readLine().trim();
		int k;
		try {
			k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1;
		} catch (NumberFormatException e) {
			System.out.println("KeyStore not changed");
			return;
		}

		X509Certificate cert = chain[k];
		String alias = host + "-" + (k + 1);
		ks.setCertificateEntry(alias, cert);

		OutputStream out = new FileOutputStream("jssecacerts");
		ks.store(out, passphrase);
		out.close();

		System.out.println();
		System.out.println(cert);
		System.out.println();
		System.out
				.println("Added certificate to keystore 'jssecacerts' using alias '"
						+ alias + "'");
	}

	private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();

	private static String toHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder(bytes.length * 3);
		for (int b : bytes) {
			b &= 0xff;
			sb.append(HEXDIGITS[b >> 4]);
			sb.append(HEXDIGITS[b & 15]);
			sb.append(' ');
		}
		return sb.toString();
	}

	private static class SavingTrustManager implements X509TrustManager {

		private final X509TrustManager tm;
		private X509Certificate[] chain;

		SavingTrustManager(X509TrustManager tm) {
			this.tm = tm;
		}

		public X509Certificate[] getAcceptedIssuers() {
			throw new UnsupportedOperationException();
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			throw new UnsupportedOperationException();
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			this.chain = chain;
			tm.checkServerTrusted(chain, authType);
		}
	}

}

Highlighted by Syntaxhighlighter...What a nice tool !

mardi 27 mai 2008

Spring, listener et ApplicationContext.

Dans le fichier de configuration web.xml de notre application, il est possible de déclarer des éléments "listener". Que font-ils? Comment Spring s'initialise grâce à eux?

Une classe listener implémenter l'une des deux super classe suivantes :

  • ServletContextListener
  • HttpSessionListener

Dans le premier cas, il faudra obligatoirement implémenter la méthode suivante : public void contextInitialized(ServletContextEvent ce)

Dans le second cas, il faudra implémenter entre autres : ublic void sessionCreated(HttpSessionEvent se)

A quoi tout cela peut il bien servir?
Oui exact, c'est ça, on obtient tout simplement ce qu'on appelle un hook sur les événements suivants (respectivement) :

  • création d'un ServletContext
  • création d'une session

Revenons en à Spring. Dés que l'application est démarrée, il nous faut le fameux "ApplicationContext Spring".
Très simplement, on va choisir de démarrer ce dernier par le biais d'une classe listener, qui sera déclarée dans le fichier web.xml comme suit :

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Et bien sûr il existe une configuration par défaut pour le nom de fichier. S'il est déclaré comme suit, le listener le trouvera sans plus de configuration :
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/applicationContext.xml, /WEB-INF/classes/resources.xml</param-value>
</context-param>

Voila voila...(A noter qu'en fait, petit malin, j'ai passé deux fichiers de config).

vendredi 28 mars 2008

JEE authentication best practices for the web

4 authentication methods to identify a user with JAAS over HTTP

  • basic authentication : the popup asking for login/password, not encrypting anything :-C
  • digest-authentication : same as basic, with password encryption. Not a really nice user experience (login popups remind of the 90's :( )
  • certificate based authentication : HTTPS, using SSL, secured socket layer. first the usual PKI handshake (asymetric encryption) then the usual symetric encryption for performance. (A variant of this authentication is also managed for installations providing users PKI certificates, chip card format for example)
  • form based authentication, the usual HTML form...

How do i do that?

-> form based authentication, most often used :

  • add a security constraint and a security role in web.xml :
 <security-constraint>  
     <web-resource-collection>  
       <web-resource-name>All JSP direct access</web-resource-name>  
       <url-pattern>private/*</url-pattern>  
       <http-method>POST</http-method>  
       <http-method>GET</http-method>  
     </web-resource-collection>  
     <auth-constraint>  
       <description>  
        No Access  
       </description>  
       <role-name>restricted</role-name>  
      </auth-constraint>  
   </security-constraint> 


   <security-role>  
     <description>NO Access</description>  
     <role-name>restricted</role-name>  
   </security-role> 
  • edit the web.xml file to add a login-config block :
 <login-config>  
   <auth-method>FORM</auth-method>  
   <realm-name>JAASDBRealm</realm-name>  
   <form-login-config>  
     <form-login-page>/blog.html</form-login-page>  
     <form-error-page>/blog.html</form-error-page>  
   </form-login-config>  
 </login-config> 

Then config your JAAS realm. Done. ;-)
-> Seriously. I'll complete the article later.

http://delicious.com/nicobeez/security

mercredi 26 mars 2008

Java annotations

Brief review of the Java annotations.

standard annotations
  • @Deprecated
  • @SuppressWarnings
  • @Override
meta-annotations
  • @Inherited
  • @Retention(RetentionPolicy.SOURCE / RetentionPolicy.CLASS / RetentionPolicy.RUNTIME)
  • @Target(ElementType.CONSTRUCTOR / ElementType.METHOD / ElementType.PACKAGE / ElementType. ) (Note that more than one ElementType is allowed here).
additional annotations

Here we go. Now we want to developp our own annotation. Example...

 @Documented  
 @Retention(SOURCE) 
 public @interface TODO { 
 
 	String value(); 
 	Level  level() default Level.NORMAL; 
 	public static enum Level { MINEUR, NORMAL, IMPORTANT }; 
 
 } 

This will be used as follows :

 @TODO(value="whatever message we want here describing the TODO...", level=NORMAL) 

Afterwards, we will have to tell the APT (annotation processing tool) what he is supposed to do with those annotations.
Source : http://developpez.com

mercredi 5 décembre 2007

Paradigmes objet et relationel

Paradigme : Un paradigme est une représentation du monde, une manière de voir les choses [...] wikipedia.
La suite? ->

Lire la suite

vendredi 30 novembre 2007

Les basiques de la base de donnée HSQL

HSQLDB est un SGBD (systême de gestion de base de données) qui offre une alternative simplifiée pour le prototypage et le développement rapide d'application.
Ô joie, un client qui permet de se connecter à la base et de regarder un peu ce qu'il s'y passe est livré avec. Plus besoin de télécharger Squirrel SQL, le driver JDBC pour HSQL...Déja 20 minutes de gagnées.

Bref, on télécharge ici : http://hsqldb.org/, on dézippe, et on copie le jar nommé hsqldb.jar contenu dans le dossier lib de notre projet.
Ensuite, on peut lancer le serveur HSQL à la ligne de commande : java -classpath lib/hsqldb.jar org.hsqldb.Server

Ou si on est un inconditionnel de Ant :
<java classname="org.hsqldb.Server" fork="yes">
<classpath>
<fileset dir="./lib" includes="*.jar"/>
</classpath>
</java>

Log de démarrage classique...

Ensuite on peut démarrer le client pour passer des commandes SQL : java -classpath lib/hsqldb.jar org.hsqldb.util.DatabaseManager -driver org.hsqldb.jdbcDriver -url jdbc:hsqldb:hsql://localhost/ -user sa

Ou cible Ant once again :

<java classname="org.hsqldb.util.DatabaseManager" fork="yes">
<classpath path="./lib" />
<arg value="-driver" />
<arg value="org.hsqldb.jdbcDriver" />
<arg value="-url" />
<arg value="jdbc:hsqldb:hsql://localhost/" />
<arg value="-user" />
<arg value="sa" />
</java>

Hop. On passe quelques commandes SQL par exemple celles décrites ici pour créer un schéma et les autres...

Récupérer l'archive du projet Eclipse avec le fichier Ant qui va bien : http://betabloguant.free.fr/ressources/ hsqldbUtility.zip

La documentation complète en français.

mercredi 17 octobre 2007

Another ant trick

need to print the ant version at build, just because?

<echo message="******************** " />
<echo message="${ant.version}" />
<echo message="******************** " />

Done !
Java version?

<echo message="******************** " />
<echo message="${ant.java.version}" />
<echo message="******************** " />

Secure copy over the network with ant :

<scp todir="${username}:${password}@${host}:${destination_dir}" trust="true">
<fileset dir="${src_dir}"/>
</scp>

This ant task, however, needs additional libs : check for the keyword scp here... Afterwards, if you use Eclipse to run ant, you need to do the following :

Go into Eclipse then click on Window->Preferences->ant->Runtime, then select 'Ant Home Entries (Default). Click on the button 'Add External JARs'. Locate the jar file you copied, select it and hit 'OK'.

Need to tell Ant about the proxy?
set ANT_OPTS=-Dhttp.proxyHost=myproxy -Dhttp.proxyPort=3128

Another ant trick

need to print the ant version at build, just because?

<echo message="******************** " />
<echo message="${ant.version}" />
<echo message="******************** " />

Done !
Java version?

<echo message="******************** " />
<echo message="${ant.java.version}" />
<echo message="******************** " />

Secure copy over the network with ant :

<scp todir="${username}:${password}@${host}:${destination_dir}" trust="true">
<fileset dir="${src_dir}"/>
</scp>

This ant task, however, needs additional libs : check for the keyword scp here... Afterwards, if you use Eclipse to run ant, you need to do the following :

Go into Eclipse then click on Window->Preferences->ant->Runtime, then select 'Ant Home Entries (Default). Click on the button 'Add External JARs'. Locate the jar file you copied, select it and hit 'OK'.

Need to tell Ant about the proxy?
set ANT_OPTS=-Dhttp.proxyHost=myproxy -Dhttp.proxyPort=3128

vendredi 11 mai 2007

Use dates with ant

Need to generate a jar file including the current date in your ant script?
Here :

<tstamp/> <!-- extract the system date to the ant environment -->
<jar destfile="${build}/${DSTAMP}-${TSTAMP}-myfile.zip" etc.


Hope that helps someone somewhere !

mercredi 21 février 2007

XML update...

Under which conditions is my XML document valid?

  1. the document validates the xml formatting rules :
    • XML documents must have a root element
    • XML elements must have a closing tag
    • XML tags are case sensitive
    • XML elements must be properly nested
    • XML attribute values must always be quoted
    • check everything regarding your XML document syntax with this online validator
  2. the document validates against the DTD !

What are XML data islands?

Data islands are a way to introduce xml data in an HTML document in Internet Explorer only ;-( with the special HTML tag <xml>.
This is very very very probable that you do not want to do that because it will NOT be supported by any other browser
More on XML data islands

XML namespace

Namespaces are usually used to avoid conflicts between tags having the same name but not the same meaning (semantically differents ;-) ).
Example : xmlns:namespace-prefix="namespaceURI"

The CDATA tag

All text in an XML document will be parsed by the parser.
Only text inside a CDATA section will be ignored by the parser.
Example : <!CDATA[ myjavascript code... ]>

vendredi 16 février 2007

Tuning the logging level in Tomcat

Little tip in case ou want to have HIGHER level of logging from tomcat (version 5.5 or higher), because he fails to do something but just says failure ;-)
Tomcat, out of the box, does not include any logging library. However, if you want to make some fine-tuning on the logging, he is ready to achieve your configuration.
At startup (my guess...) Tomcat checks if some special configuration has to be applied, via the "bridge" interface commons logging . This library can be described as a logging implementation abstraction layer. If so, he applies it. Commons logging interface hides the actual implementation, that is, you can use either log4j or any alternative behind the scenes.
Anyway, drop the commons logging and log4j jar files in the common/lib directory, write a log4j.properties file in the common/classes directory, and you should be fine.

Log4j.properties example :

log4j.rootLogger=ERROR, A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout

# Print the date in ISO 8601 format
log4j.appender.A1.layout.ConversionPattern=%d %t %-5p %c - %m%n

log4j.logger.org.apache=DEBUG



Pour tester tout ça, rapatriez ce petit projet JSF dans eclipse, ant compile et deploy...

Environment variables in Java

also looking for two lines of code to access the Tomcat directory seamlessly?
Works for any environment variable o' course...

public static void main(String args) {
String tomcatHome = System.getenv("TOMCAT_HOME");
System.out.println("Tomcat Home vaut : "+tomcatHome);
}

vendredi 2 février 2007

Performance testing, load testing or stress testing?

Il est important de comprendre les différences entre ces trois types de testing. Performance, stress et charge. Selon le vocabulaire établi :

  • les tests de performance sont menés pour valider le fait que le systême va donner un temps de réponse correct à son ou ses utilisateurs dans les conditions d'utilisation normales définies. Par exemple, 400 utilisateurs effectuant des requêtes concurrentes, temps de réponse maximum 4s pour une requête donnée. Ces tests vont permettre de repérer les goulots d'étranglement à tous les niveaux et ainsi permettre de gagner en...performance.
  • le stress testing permet de valider que le systême va savoir réagir correctement en cas de disfonctionnement d'un des modules qui le constitue. L'état est-il sauvé avant clôture? L'état du systême est-il correctement restauré au redémarrage. Les cas de stress habituels sont par exemple :
    • chute du réseau / d'un ou plusieurs ports réseau
    • chute du serveur de base de données
    • forte charge en terme d'utilisateurs
  • Enfin, les tests de charge cherchent à détecter des bugs ou erreurs de conception qui n'apparaissent qu'en cas de charge réelle du systême. On recherche classiquement les fuites de mémoires...Ce type de test s'appelle aussi volume testing ou endurance testing.

Toute une batterie d'outils existe pour mener ces tests, simuler plusieurs milliers d'utilisateurs etc, je citerais le projet Apache Jmeter, parce que c'est écrit en Java et parce que c'est open source !

Mes sources d'inspiration sur ce sujet :

lundi 15 janvier 2007

Mock objects

Let's say you are a programmer.
Let's say you are aware of the traps a big IT project can fall into, and you decide to adopt a test driven approach.
On the next day, you find out that this huge (900 md) part of the code that is done by this other contractor will not be delivered until 2009, and of course you need this part to test your code...Treat yourself and build a mock object that will simulate the behaviour of the missing part of the code !

Wikipedia says you normally need this (these) mock object because this damn contractor code :

  • produces non-deterministic results like current time or current temperature
  • has states that are difficult to create or reproduce (e.g. a network error);
  • is slow (e.g. a complete database, which would have to be initialized before the test); (You don't run a test that is slo 100 times a day...especially if you have 100 tests like this one 8-O )
  • does not yet exist or may change behavior;
  • would have to include information and methods exclusively for testing purposes (and not for its actual task).

A proper conception of your mock object will be the following :
Upon a commonly agreed interface with the ... contractor :

  1. he builds his code
  2. you call the interface to interact with his object
  3. you buil a mockup implementing the interface, who will act in the same way as the other guy's code
  4. you deliver !

Ok, but a test class can do the job, why would i want a mockup?
Probably in the cases where you interact with some objects that are complex to mimic (you do not want to build them in messy test cases), when these objects are slow to build, or cost time to calculate (remember a big project usually involves a suite of hundreds of test, and the suite needs to be run fast...), when you need to test states like DB is down, but you do not want to stop the db to run your test ;-)

vendredi 5 janvier 2007

Retrieve LDAP informations in BEA Portal

The object ProfileFactory delivers user profiles based on the user name and the group name, however, the group seems to be optional so far...
From there, you can access all the LDAP properties (permitted by the login/pass provided by Weblogic...) !
For instance, if we want the userTown field, "request" being a HttpServletRequest Object :

ProfileWrapper p = ProfileFactory.getProfile(request.getRemoteUser(), null);
p.getProperty("LDAP_RepositoryName_In_BEA", "userTown");


That's it.
Nota, from version 9.2 on, an entry point to the user segments is provided in the API !

mercredi 22 novembre 2006

Attribute or parameter

If you never know wich one to use, read on...

Lire la suite

lundi 13 novembre 2006

Portlets for starters

Some technical informations gathered from JSR 168 regarding portlet development

Lire la suite

mercredi 8 novembre 2006

Eclipse project build : make it do what you want it to do.

project view [edit November 9th 2006 : ] The solution exposed probably won't work, a bug has been reported on Eclipse 3 to 3.2, probably resolved on 3.3 The bug on eclipse forum
So what do i do until Eclipse 3.3? Build an Ant script with this tutorial, and learn Ant scripting for god's sake ;-(

Eclipse offers great abilities and easy configuration...Although sometimes it's hard to get you want, like :

  • "I want my classes in build/web/WEB-INF/classes"
  • "I want my JSP's in build/web"
  • etc...

properties The only way to achieve your needs in this case is to parametrize :

  1. source folder, for instance "src"
  2. a build location for this exact folder
  3. a general build location for JSP's, properties, and so on.

add src folder, declare output folder Following this tutorial on mashup portlets, i achieved my goals as follows :

  1. organize my project folders(first pic)
  2. Edit the project properties with a right click, properties->Java build path->source tab(second pic)
  3. At that point (last pic):
    1. change the default output src folder to "build" (for example)
    2. declare my "src" folder as a source folder
    3. check "allow output folders for source folders"
    4. modify the output folder for our source folder "src"

As a conclusion, i would say : forget about having nested folders in the output (buggy for now, see head of this page).
Not following this advice will lead you to the so called "Cannot nest output folder 'X/Y' inside output folder 'X'", and you don't want to go down that road, believe me!

vendredi 3 novembre 2006

Débuter avec BEA weblogic application server

Comme je l'avais déja fait précedemment sur JBoss, je vais exposer ici les notions de bases pour commencer à développer avec BEA Weblogic application server, et plus particulièrement sur la partie "portail" (BEA Portal)...-> "Suite" ;-)

Lire la suite

mardi 3 octobre 2006

BEA Portal : shallow and deep retrieve with "getBookView"

As i was working on a BEA Portal 8.1.5, trying to obtain the number of children of a view through the "BookView" Interface, obtained itself as follows :
BookView bv = PortalAdminManager.getBookView(myBookDefinitionId, myLocale, myHttpRequest);
i encountered a problem when running this code :
if(bv.getNavigableViews().length == 0) // etc
This condition was always met...altough the book title, the bookInstance id etc. are correct...Why??? Thank to the documentation of BEA 9.2, i finally figured out how it was working....
It appears that the method "getBookView" exists with two different signatures, one retrieving a "shallow" (lightweight) BookView, the other one retrieving the full object. If you want to use the methods getPageCount, getBookCount, getNavigableViews etc., DON'T use the shallow object : it's empty...
The code to use then is :
BookView bv = PortalAdminManager.getBookView(myParentBookInstanceId, myBookDefinition.getWebAppName(), myPortalPath, myDesktopPath, true, myLocale, request);

This is a pretty tricky error, as the code compiles and runs without any Exception rise...Hope that helps someone somewhere sometimes !

samedi 23 septembre 2006

L'injection de dépendances.

Weather L'injection de dépendances (DI Dependency Injection) encore connue sous le nom d'inversion de contrôle (IOC Inversion of control IOC) est un concept qui mène sa petite révolution depuis quelques temps. J'ai donc fouillé un peu, et je vous recommande chaudement un article d'introduction à la chose sur the server side.
Sur ce, excellente fin de semaine...Il fait beau à Zürich, moche à Paris, donc je rentre...Classique ! 8-)
Au fait, comment dit-on "design pattern" en Francais? "Motif de conception" bien sur...

jeudi 20 juillet 2006

JBoss, pionnier du business model open source

Business model

JBoss est une application open-source, tout le monde peut ainsi connaitre le mode complet de fabrication, et également participer, corriger des bugs, ajouter de nouvelles fonctionnalités... Comme le veut la licence GPL, ce logiciel est gratuit.
Ok, mais d'ou vient l'argent???
En fait, Marc Fleury, initiateur du projet JBoss, et premier programmeur de l'équipe, a créé une entreprise nommée JBoss Group, qui fournit un support sur les applications développées sous JBoss...
Ce monsieur définit ainsi son action (sur 01.net) :

Le modèle commercial, établi pour le serveur d'applications J2EE Open Source JBoss, est simple. Le serveur est gratuit, JBoss Group se rémunère sur la maintenance des applications. « C'est une démarche qui déroute les clients habitués aux modèles classiques, mais qu'ils apprécient vite. Tout le monde y trouve son compte. La maintenance nécessite beaucoup moins d'efforts commerciaux que la vente de licences. Notre service est facturé à l'application. Plus il y a de bugs, mieux nous gagnons notre vie. Si le bug provient du serveur, l'assistance est illimitée. S'il provient de l'application, nous le facturons. Il nous est arrivé de revoir complètement un logiciel, ce qui a été facturé en conseil, avec un autre tarif, et non pas en service. » Le soutien de la communauté des développeurs JBoss représente un atout important. « Ils améliorent constamment notre serveur et nous permettent de nous focaliser sur l'assistance aux utilisateurs » , conclut Marc Fleury.

Et voila, tout le monde y gagne, et on réussit à s'affranchir de ce pénible coté "vente de licences" et "marketing"...
JBoss Group est depuis le 5/06/2006 une filiale de Red Hat, un des grands du conseil autour de Linux...

Le produit

JBoss 4.0.4 a fait sa sortie le 24 Mai 2006, retour sur la courte histoire de ce produit qui a su se tailler une place de choix parmi les grand éditeurs de serveurs d'application J2EE.

La version 1, démarrée par Marc Flerury en Mars 1999 sort en Février 2000, à l'époque, il s'agit principalement de supporter les EJB, session (service) et entity (persistance).

La version 2, sortie en 2002, ajoute le support de :

  • JMX Java management extension :
    • administration des applications déployées dur le serveur d'app
    • statistiques serveurs sur les applications, les pools...
  • JMS : Java Messaging service, qui offre une gestion de files de messages (comparable à MQSeries d'IBM)

La version 3, sortie également en 2002, se voit certifié J2EE version 1.3 (EJB 2.0, Servlets 2.3, JCA, etc) par Sun, JBoss devient un concurrent vraiment sérieux pour IBM Wesphere AS, BEA WebLogic et leurs concurrents...

JBoss 4 sort en Octobre 2004, il est alors le premier à être CERTIFI2 J2EE 1.4, coup dur pour ses concurrents...
Il propose en particulier le support d'EJB 3 (Java 5 nécessaire...). JBoss 4 supporte Java 1.4, cependant l'ensemble des fonctionnalités ne sont pas disponibles avec cette version de Java.
Le rôle de conteneur de servlets, nécessaire pour les webapps, est assuré par Tomcat, quand à la CMP (container managed persistence), elle est assurée par Hibernate !
L'environnement de développement proposé par le JBoss Group (entreprise de conseil autour de JBoss) est Eclipse assoocié aux plugins JBoss.
JBoss fournit également un mécanisme nommé JBossCache, cache d'objets, transactionnel et distribué (sur un cluster par exemple).
On trouve également en standard un scheduler qui permet de lancer des tâches à des dates précises.
La gestion du farming est assurée : elle concerne le redéploiement automatisé des composants distribués sur l'ensemble du cluster (ferme de serveurs).

Coté portabilité, JBoss s'en tire plutôt bien, écrit entièrement en Java, il est portable sur tout systême possédant la version correcte de Java...Ainsi porter toutes les applications d'un serveur Windows vers un Linux se fera de manière transparente.

Allez, l'essayer, c'est l'adopter...

vendredi 14 avril 2006

Apprendre Eclipse...

apprendre son IDE (environnement de développement intégré, par exemple Visual Studio ou Eclipse) est un investissement qui rapporte une productivité très appréciable...
Quelques raccourcis Eclipse :

  • Ctrl + O : mettre &agrave; jour les dépendances (les import)
  • Ctrl + espace : la complétion automatique : si vous devez n'en connaitre un, que ce soit celui-la
  • Ctrl + Shift + R : Recherche d'un fichier dans le workspace
  • Ctrl + O : affichage des attributs et methodes de la classe courante
  • Ctrl + O une deuxieme fois : ajoute &agrave; l'affichage les attributs et methodes hérités
  • Ctrl + T : affiche l'arborescence d'héritage de la classe courante
  • Alt + Shift + J : génére un template de javadoc pour une classe une méthode ou un attribut en fonction de la séléction
  • Ctrl + Shift + F : mise en forme du code (vous pouvez surligner une zone de code pour restreindre le formatage)
  • Ctrl + Shift + I : indentation du code (vous pouvez surligner une zone de code pour restreindre l'indentation)
  • Ctrl + D : efface la ligne courante
  • Alt + Shift + R : pour refactoriser le nom d'une fonction ou d'une variable
  • Ctrl + Shift + C : pour commenter / decommenter des lignes
  • Crtl + Shift + P : Pour se deplacer d'une accolade &agrave; l'autre
  • En tapant "sysout" puis ctrl+espace on obtient le pénible "System.out.println("");" !


Liste issue de developpez.com
Outils pour faciliter le déploiement de vos applications standalone sur les postes clients?

  • très simple, transforme un jar en éxecutable qui vérifie la présence d'une JVM avant de lancer le jar et affiche un message idoine si pas de jvm :JSmooth
  • Plus complexe, mais pour un déploiement encore plus aisé, par le web, vous avez seulement un lien &agrave; envoyer, mais un serveur &agrave; mettre en place au préalable :java web start

lundi 3 avril 2006

Expressions régulières (regexp) avec Perl

Si vous croyez que Perl sert à fabriquer des bijoux, allez plutôt ici ou la.
Les expressions régulières sont un outil intégré dans presque tous les langages de programmation...Plus loin mon petit pense-bète

Lire la suite

jeudi 2 mars 2006

Mon premier service web avec google.

Les web services, les architectures orientées services, c'est hype. Google s'y est mis il y a un bon bout de temps, et propose aux développeurs un kit avec tout le nécessaire pour intégrer des résultats de recherche (google) au sein d'applicatifs developpé dans le langage de leurs rêves.

Lire la suite

vendredi 24 février 2006

Les langages de programmation les plus populaires

Fortran le dinausore va bientôt disparaître du classement tiobe des langages les plus populaires...(en)

Lire la suite

vendredi 10 février 2006

Le mapping objet/données avec Java

Le mapping objet-relationnel est désormais un incontournable de J2EE, avec toujours les mêmes concepts, fournir :

Lire la suite

jeudi 26 janvier 2006

Apprendre JUnit avec Eclipse en 10 minutes

Série "faster Java"


Un tutorial de (jmdoudoux) encore lui... sur JUnit qui met en scêne l'écriture d'une classe "addition", et d'une classe de test JUnit, avec des tests intégrés.
Ainsi, cette classe de test va permettre au cours des versions successives de ma classe "addition" de recueillir et de cumuler tout un paquet de tests que l'on lancera afin de valider entre autres choses la non-régression...pas mal 8-)


JUnit est un peu dépassé, essayez donc TestNG...le tuto de JMDoudoux.

jeudi 5 janvier 2006

Manipulation de la classe Calendar avec Java

Pour récupérer le lundi d'une semaine dont on connait le n? et l'année,
rien de plus simple avec la classe Calendar en Java :
SimpleDateFormat sdf = new SimpleDateFormat("E/ww/yyyy");
try{ Date dateDebut = sdf.parse("Lundi/05/2005"); }
catch( ParseException pe){System.out.println(pe); }

vendredi 2 décembre 2005

Données transientes en Java

c'est vrai, transient &ccedil;a veut dire quoi ?

Lire la suite

mardi 8 novembre 2005

J2SE et J2EE

Série "un jour, une définition" :
Quelle est la différence de contenu entre J2SE (Java 2 standard edition) et J2EE (Java 2 enterprise edition)?
En fait, J2SE contient tous les outils nécessaires pour faire de la programmation classique, réseau, graphique, et J2EE apporte un support pour des applications orientées entreprise.

Lire la suite

lundi 1 août 2005

Commencer avec log4j

Comment dire...ça ne concerne pas forçément tout le monde, mais ça peut en intéresser plus d'un. Pour le jour ou vous ferez un programme solide en Java !
Vous voulez démarrer avec log4J?
Vous voulez commencer avec log4J?
Vous voulez apprendre avec log4J?
Vous cherchez un tutorial sur log4J?
C'est ici !

Lire la suite

vendredi 1 juillet 2005

Technical party

Hier soir soirée technique dans mon entreprise préférée, le thême, assez ambitieux : J2EE vs .Net" !
Tout pleins d'idées générales, un peu de considéraitons techniques surle typage, le fonctions de boxing unboxing, présentes en .Net et aussidans la dernière version du JDK (5.0) etc.
Les intervenants étaient passionnés, mais ont bien expliqué les avantages et inconvénients de chacun.
Ce que j'ai retenu : J2EE profite d'un serveur d'app très pratique,.Net souffre de l'image de MS, mais tourne pourtant sous FreeBSD etLinux...(ces dév s'appellent rotor et chaiplukoi...)
Quelques idées reçues se sont évaporées !
j'ai tjs pas bien compris ce que c'est qu'un typage fort, Tom si tu sais

lundi 20 juin 2005

Tagger la javadoc...

C'est les trucs dont on se souvient jamais alors...ils sont ici désormais.

Pour pouvoir être interprétés les tags standards doivent obligatoirement commencer en début de ligne.

Tag Rôle élément concerné
@author permet de préciser l'auteur de l'élement classe et interface
@deprecated permet de préciser qu'un élément est déprécié package, classe, interface, méthode et champ
{@docRoot} représente le chemin relatif du répertoire principal de génération de la documentation  
@exception permet de préciser une exception qui peut être levée par l'élément méthode
{@link} permet d'inserer un lien vers un élément de la documentation dans n'importe quel texte package, classe, interface, methode, champ
@param permet de préciser un paramètre de l'élément constructeur et méthode
@see permet de préciser un élément en relation avec l'élément documenté package, classe, interface, champ
@serial   classe, interface
@serialData   methode
@serialField   classe, interface,
@since permet de préciser depuis quelle version l'élément aété ajouté package, classe, interface, méthode et champ
@throws identique ´ @exception méthode
@version permet de préciser le numéro de version de l'élément classe et interface
@return permet de préciser la valeur de retour d'un élément méthode

 source

"

jeudi 2 juin 2005

L'expertise d'entreprise et la gestion de workflow

La gestion de worflow sera probablement aussi vitale que les bases de données à l'avenir.
Pourtant le BPM (business process management) ne remplacera probablement pas la logique des applications professionnelles : eneffet, les applis pros constituent souvent une mine de connaissances acquises sur le domaine cible.
Et les entreprises sont très habituées au passage de compétences et à l'enrichissement de celles-ci par le biais de ces applications. C'est d'ailleurs souvent elles qui créent une grande partie de la valeur d'une entreprise aux yeux d'un client.
Pour en revenir au BPM, tout au contraire, il ne contient pas de savoir intrinsèque sur le domaine pour lequel il va être utilisé.
Ainsi, le BPM requiert (on s'en doutait) l'implémentation desprocessus, et offre donc une beaucoup plus grande latitude/flexibilité(premier point).
La ou tout ça devient assez novateur(second point), c'est que lacommunauté Java propose, pour implémenter BPM, un ensemble d'outilspour le programmeur, mais surtout un langage très aisé à manipuler par des non-programmeurs (des managers par exemple). Et oui, les koders ne saisissent pas toujours la totalité du fonctionnement du business pour lequel ils travaillent...
Plus qu'à déléguer au chef
Idées tirées du white paper JBoss/JBPM.