<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java, Mac et parfois plus ...</title>
	<atom:link href="http://gabriel.dromard.free.fr/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://gabriel.dromard.free.fr/blog</link>
	<description>Le blog de Gabriel Dromard</description>
	<lastBuildDate>Thu, 07 Jun 2012 08:27:05 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Une petite application Web maison de gestion des taches</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=534</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=534#comments</comments>
		<pubDate>Fri, 13 Apr 2012 16:07:08 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[Agilité]]></category>
		<category><![CDATA[Application]]></category>
		<category><![CDATA[Logiciel]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Tache]]></category>
		<category><![CDATA[Task]]></category>
		<category><![CDATA[Utilitaire]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=534</guid>
		<description><![CDATA[Une petite présentation rapide* de mon outil de gestion des taches (Si ça vous intéresse, je le mettrais peut-être sur GitHub ??) :

Un clic sur le bouton d&#8217;ajout pour créer une nouvelle tache :



Il suffit de survoler une tache … pour pouvoir la supprimer :

Un clic sur une tache   …  pour la modifier

Un clic sur l’icône … [...]]]></description>
			<content:encoded><![CDATA[<p>Une petite présentation rapide* de mon outil de gestion des taches (Si ça vous intéresse, je le mettrais peut-être sur GitHub ??) :</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-526" title="screenshot01" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/screenshot01.jpg" alt="screenshot01" width="695" height="354" /></p>
<p><span id="more-534"></span>Un clic sur le bouton d&#8217;ajout pour créer une nouvelle tache :</p>
<p><img class="alignleft size-full wp-image-535" title="screenshot10" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/screenshot10.jpg" alt="screenshot10" width="801" height="27" /></p>
<p><br class="spacer_" /></p>
<p><br class="spacer_" /></p>
<p>Il suffit de survoler une tache … pour pouvoir la supprimer :</p>
<p><img class="alignnone size-full wp-image-527" title="screenshot02" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/screenshot02.jpg" alt="screenshot02" width="515" height="18" /></p>
<p>Un clic sur une tache   …  pour la modifier</p>
<p><img class="alignnone size-full wp-image-528" title="screenshot03" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/screenshot03.jpg" alt="screenshot03" width="802" height="23" /></p>
<p>Un clic sur l’icône … et la tache change de statut TODO (rouge):</p>
<p><img class="alignnone size-full wp-image-530" title="screenshot05" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/screenshot05.jpg" alt="screenshot05" width="471" height="19" /></p>
<p>Un clic sur l’icône … et la tache change de statut IN WORK (orange):</p>
<p><img class="alignnone size-full wp-image-531" title="screenshot06" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/screenshot06.jpg" alt="screenshot06" width="474" height="19" /></p>
<p>Un clic sur l’icône … et la tache change de statut DONE (vert):</p>
<p><img class="alignnone size-full wp-image-532" title="screenshot07" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/screenshot07.jpg" alt="screenshot07" width="470" height="18" /></p>
<p>Un clic sur l’icône … et la tache change de statut SKIPPED (gris):</p>
<p><img class="alignnone size-full wp-image-533" title="screenshot08" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/screenshot08.jpg" alt="screenshot08" width="478" height="19" /></p>
<p>Un clic sur l’icône … et la tache change de statut NEED INFO (jaune):</p>
<p><img class="alignnone size-full wp-image-525" title="screenshot09" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/screenshot09.jpg" alt="screenshot09" width="471" height="19" /></p>
<p><br class="spacer_" /></p>
<p>* Rapide et incomplète.</p>
<p>Incomplète, car je ne parle pas de la partie technique, qui est assez importante dès lors que l’on doit l’utiliser dans la vrai vie. En effet, cette application n’a pas été pensée dès l’origine pour être multi projet. Or dans le monde réel nous avons souvent, voir toujours, plusieurs type de taches à suivre !</p>
<p>Pour ce faire, c&#8217;est toujours possible, mais il faut déployer plusieurs instances de l&#8217;outil !</p>
<p>Si jamais c&#8217;est un outil qui vous intéresse, dites le moi, je le partagerais sur GitHub, dans un premier temps, et qui sait, peut-être deviendra-t-il multi-projet ??</p>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=534</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Le Lion de la savane Mac se repose &#8230;</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=517</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=517#comments</comments>
		<pubDate>Thu, 29 Mar 2012 12:51:31 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[Mac]]></category>
		<category><![CDATA[Lion]]></category>
		<category><![CDATA[OS X]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=517</guid>
		<description><![CDATA[Mac OS X Lion rencontre des lenteurs inexplicables ! Peut-être que de vider la PRAM résoudra le problème ?]]></description>
			<content:encoded><![CDATA[<p>Mac OS X à tendance à être très long sur mon Mac Book.</p>
<p>Après avoir fait quelques recherches avec mon amis google j&#8217;ai trouvé comment vider la mémoire PRAM de Mac OS X Lion.</p>
<p><span id="more-517"></span>PRAM veut dire: Parameter random access memory. C&#8217;est dans cet espace mémoire que Lion va stocker toutes une série de paramètres systèmes afin d&#8217;y accéder rapidement. Cependant, il se peut que ces informations ne soient plus à jour. C&#8217;est alors qu&#8217;il faut les nettoyer afin que les paramètres soient recréés.</p>
<p>Pour ce faire: <span style="color: #808080;"><span style="color: #808080;">(Attention: si vous avez mot de passe Firmware, EFI, il vous faut le désactiver pour pouvoir faire cette manipulation ! Attention, je ne peux pas être tenu responsable de dégâts causés si cette technique ne fonctionne pas !) </span></span></p>
<ol>
<li>Éteindre votre Mac. <span style="color: #808080;">Pas besoin de se poser de question sur le fait qu&#8217;il soit connecté au secteur ou pas.</span></li>
<li>Allumer votre Mac en appuyant sur les 4 touches Command, Option P, et R en même temps :<br />
 <img class="alignnone" src="http://gigaom2.files.wordpress.com/2011/07/pram-reset-graphic.jpg?w=300&amp;h=148" alt="" width="300" height="148" /> </li>
<li>Garder appuyé sur les 4 touches jusqu&#8217;à ce que vous entendiez le son du démarrage du Mac pour la seconde fois.</li>
</ol>
<p>Dans des cas plus extrême on peut également réinitialiser le contrôleur de gestion système SMC, mais pour cela je vous invite à faire une recherche sur la toile.</p>
<p>Pour ma part cela a résolu les lenteurs particulièrement gênantes de mon Mac Book. En espérant que ça puisse aider certain.</p>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=517</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Désinstaller Xcode sur lion avant d&#8217;installer la version 4.3</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=514</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=514#comments</comments>
		<pubDate>Sat, 18 Feb 2012 12:59:20 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[Mac]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[xcode]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=514</guid>
		<description><![CDATA[Avant d&#8217;installer la version 4.3 de xcode, peut-être voudriez-vous désisntaller la version précédente:
sudo /Developer/Library/uninstall-devtools –mode=all
La nouvelle version est packagé sous forme d&#8217;application &#171;&#160;normale&#160;&#187; et non plus dans un package à installer à part !

Pour plus de détail allez voir: QuickTip uninstalling xcode développer tools
]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-515" title="xcode" src="http://gabriel.dromard.free.fr/blog/wp-content/uploads/xcode.png" alt="xcode" width="220" height="220" />Avant d&#8217;installer la version 4.3 de xcode, peut-être voudriez-vous désisntaller la version précédente:</p>
<p><code>sudo /Developer/Library/uninstall-devtools –mode=all</code></p>
<p>La nouvelle version est packagé sous forme d&#8217;application &laquo;&nbsp;normale&nbsp;&raquo; et non plus dans un package à installer à part !</p>
<p><br class="spacer_" /></p>
<p>Pour plus de détail allez voir: <a href="http://macamour.com/blog/2011/04/03/quick-tip-uninstalling-xcode-developer-tools/">QuickTip uninstalling xcode développer tools</a></p>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=514</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript Bookmark function</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=509</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=509#comments</comments>
		<pubDate>Wed, 08 Jun 2011 13:31:24 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[bookmark]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[IE]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=509</guid>
		<description><![CDATA[

function bookmark(bookmarkurl, bookmarktitle) {
    try {
        if (typeof window.sidebar == &#34;object&#34; &#38;&#38; typeof window.sidebar.addPanel == &#34;function&#34;) {
            window.sidebar.addPanel(bookmarktitle, bookmarkurl, &#34;&#34;);
        } else if (typeof window.external == &#34;object&#34;) [...]]]></description>
			<content:encoded><![CDATA[<pre name="code" class="javascript">

function bookmark(bookmarkurl, bookmarktitle) {
    try {
        if (typeof window.sidebar == &quot;object&quot; &amp;&amp; typeof window.sidebar.addPanel == &quot;function&quot;) {
            window.sidebar.addPanel(bookmarktitle, bookmarkurl, &quot;&quot;);
        } else if (typeof window.external == &quot;object&quot;) {
            if (typeof window.external.AddToFavoritesBar == &quot;function&quot;) {
                window.external.AddToFavoritesBar(bookmarkurl,bookmarktitle);
            } else {
                window.external.AddFavorite(bookmarkurl,bookmarktitle);
            }
        } else {
            alert(&#039;Ooops, I do not know how to create a bookmark on your browser!\nYou have to do it your self!&#039;);
        }
    } catch(e) {
        alert(&#039;Ooops, I did not manage to create the bookmark on your browser!\nYou have to do it your self!&#039;);
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=509</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MessageHandler class</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=507</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=507#comments</comments>
		<pubDate>Tue, 24 May 2011 08:24:37 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=507</guid>
		<description><![CDATA[


/***********************
 *  ERROR MANAGEMENT   *
 ***********************
 * Depends on :
 *  - StringBuffer class.
 */

var MessageHandler = Class.create({
	messageDisplayTime: 4 * 1000,
	reqMsgId: null,
	reqErrId: null,

	initialize: function(divId, attributes) {
		var errorContainer = $(&#039;mhContainer&#039;);
		if (errorContainer == null) {
			var buf = new StringBuffer();
			buf.append(&#039;&#60;div id=&#34;mhContainer&#34; class=&#34;messages&#34;&#62;&#039;);
				buf.append(&#039;&#60;div id=&#34;mhMsg&#34; class=&#34;message&#34; style=&#34;display:none&#34;&#62;&#60;/div&#62;\n&#039;);
				buf.append(&#039;&#60;div id=&#34;mhErr&#34; class=&#34;error&#34; style=&#34;display:none&#34;&#62;&#60;/div&#62;\n&#039;);
			buf.append(&#039;&#60;/div&#62;&#039;);
       [...]]]></description>
			<content:encoded><![CDATA[<pre>
<pre name="code" class="javascript">

/***********************
 *  ERROR MANAGEMENT   *
 ***********************
 * Depends on :
 *  - StringBuffer class.
 */

var MessageHandler = Class.create({
	messageDisplayTime: 4 * 1000,
	reqMsgId: null,
	reqErrId: null,

	initialize: function(divId, attributes) {
		var errorContainer = $(&#039;mhContainer&#039;);
		if (errorContainer == null) {
			var buf = new StringBuffer();
			buf.append(&#039;&lt;div id=&quot;mhContainer&quot; class=&quot;messages&quot;&gt;&#039;);
				buf.append(&#039;&lt;div id=&quot;mhMsg&quot; class=&quot;message&quot; style=&quot;display:none&quot;&gt;&lt;/div&gt;\n&#039;);
				buf.append(&#039;&lt;div id=&quot;mhErr&quot; class=&quot;error&quot; style=&quot;display:none&quot;&gt;&lt;/div&gt;\n&#039;);
			buf.append(&#039;&lt;/div&gt;&#039;);
            $$(&#039;body&#039;)[0].innerHTML += buf.toString();
		}
	},

	showMessage: function(msg) {
		var div = $(&#039;mhMsg&#039;);
		div.update(/*&#039;&lt;p align=&quot;right&quot;&gt;&lt;a href=&quot;#&quot; onClick=&quot;$(\&#039;mhMsg\&#039;).hide()&quot;&gt;[X]&lt;/a&gt;&lt;/p&gt;&#039;+*/msg);
		div.show();
		if (this.reqMsgId != null) clearTimeout(this.reqMsgId);
		this.reqMsgId = setTimeout(function() { $(&#039;mhMsg&#039;).hide(); }, this.messageDisplayTime);
	},

	showError: function(msg) {
		var div = $(&#039;mhErr&#039;);
		div.update(/*&#039;&lt;p align=&quot;right&quot;&gt;&lt;a href=&quot;#&quot; onClick=&quot;$(\&#039;mhErr\&#039;).hide()&quot;&gt;[X]&lt;/a&gt;&lt;/p&gt;&#039;+*/msg);
		div.show();
		if (this.reqErrId != null) clearTimeout(this.reqErrId);
		this.reqErrId = setTimeout(function() { $(&#039;mhErr&#039;).hide(); }, this.messageDisplayTime);
	}
});
</pre>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=507</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>StringBuffer Class</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=505</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=505#comments</comments>
		<pubDate>Tue, 24 May 2011 08:23:06 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=505</guid>
		<description><![CDATA[


var StringBuffer = Class.create({
	buffer: null,

	initialize: function() {
		this.buffer = [];
	}, 

	append: function(string) {
		this.buffer.push(string);
		return this;
	},

	toString: function() {
		return this.buffer.join(&#34;&#34;);
	}
});


]]></description>
			<content:encoded><![CDATA[<pre>
<pre name="code" class="javascript">

var StringBuffer = Class.create({
	buffer: null,

	initialize: function() {
		this.buffer = [];
	}, 

	append: function(string) {
		this.buffer.push(string);
		return this;
	},

	toString: function() {
		return this.buffer.join(&quot;&quot;);
	}
});
</pre>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=505</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ajouter un timeout en RMI &#8211; How to handle a timeout on RMI connections ?</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=481</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=481#comments</comments>
		<pubDate>Tue, 29 Jun 2010 13:19:47 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[RMI]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=481</guid>
		<description><![CDATA[Par défaut les connexions RMI ont un timeout assez long (20s sur mon environnement).
Il peut être utile de gérer soit même le timeout utilisé pour se connecter au serveur RMI.
Prenons le code suivant:
Here is a little &#171;&#160;How to handle timeout on a RMI connection&#160;&#187;, lets try the execution of following code:

import java.io.Serializable;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import [...]]]></description>
			<content:encoded><![CDATA[<p>Par défaut les connexions RMI ont un timeout assez long (20s sur mon environnement).</p>
<p>Il peut être utile de gérer soit même le timeout utilisé pour se connecter au serveur RMI.</p>
<p>Prenons le code suivant:</p>
<p>Here is a little &laquo;&nbsp;How to handle timeout on a RMI connection&nbsp;&raquo;, lets try the execution of following code:</p>
<p><span id="more-481"></span><br class="spacer_" /></p>
<pre>import java.io.Serializable;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.server.RMISocketFactory;

/**
 * Exécution:
 *
 * java -Djava.security.policy=policy.txt TestRmi
 *
 * policy.txt
 * -------------------
 * grant {
 *   // Allow everything for now
 *   permission java.security.AllPermission;
 * };
 * -------------------
 */

public class TestRmi {
    public static void main(final String[] args) {
        // Server Side
        try {
            LocateRegistry.createRegistry(1099);
            System.setSecurityManager(new RMISecurityManager());
            Test test = new TestServer();
            Naming.rebind("rmi://localhost:1099/test", test);
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        // Client side
        long start = System.currentTimeMillis();
        try {
            //RMISocketFactory.setSocketFactory(new TimedSocketFactory(2000));
            Test test = (Test) Naming.lookup("rmi://128.0.0.1:1099/test");
            System.out.println(test.sayMeHello());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Duration: " + (System.currentTimeMillis() - start));
    }

    private static interface Test extends Remote, Serializable {
        String sayMeHello() throws RemoteException;
    }

    private static class TestServer implements Test {
        /** The serialVersionUID. */
        private static final long serialVersionUID = 5171499581308608043L;

        public String sayMeHello() {
            return "Hello !";
        }
    }
}
</pre>
<p>Après l&#8217;avoir lancé, vous obtiendrez une stack trace puis un temps de l&#8217;ordre de 20s. Pour gérer cela, nous allons utiliser notre propre implémentation du RMISocketFactory.</p>
<p>You may have seen that duration variable is up to 20s &#8230; Lets implements our TimedSocketFactory :</p>
<pre>import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.server.RMISocketFactory;

public class TimedSocketFactory extends RMISocketFactory {
    private final int timeout;

    /**
     * @param timeout The time out in milliseconds.
     */
    public TimedSocketFactory(final int timeout) {
        this.timeout = timeout;
    }

    public Socket createSocket(final String host, final int port) throws IOException {
        Socket socket = new Socket();
        socket.connect(new InetSocketAddress(host, port), timeout);
        socket.setSoTimeout(timeout);
        socket.setSoLinger(false, 0);
        return socket;
    }

    public ServerSocket createServerSocket(final int port) throws IOException {
        return getDefaultSocketFactory().createServerSocket(port);
    }
}
</pre>
<p>Décommentez la ligne:</p>
<pre>RMISocketFactory.setSocketFactory(new TimeoutSocketFactory(2000));</pre>
<p>Et relancez, vous obtiendrez un temps légèrement supérieur à 2s !!</p>
<p>Et voilà le tour est joué !</p>
<p><br class="spacer_" /></p>
<p>Uncomment the line:</p>
<pre>RMISocketFactory.setSocketFactory(new TimeoutSocketFactory(2000));</pre>
<p>Than restart, and you will have duration time arround 2s !!</p>
<p><br class="spacer_" /></p>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=481</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Reflect Helper class</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=279</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=279#comments</comments>
		<pubDate>Wed, 24 Mar 2010 11:35:24 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=279</guid>
		<description><![CDATA[


import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Utility class for reflect purpose.
 */
public final class ReflectHelper {
    /**
     * Empty private constructor for util class.
     */
    private ReflectHelper() {
        // Empty [...]]]></description>
			<content:encoded><![CDATA[<pre>
<pre name="code" class="java">

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Utility class for reflect purpose.
 */
public final class ReflectHelper {
    /**
     * Empty private constructor for util class.
     */
    private ReflectHelper() {
        // Empty private constructor for util class.
    }

    /** Constant meaning accessor type setter. */
    public static final String SETTER = &quot;set&quot;;

    /** Constant meaning accessor type getter. */
    public static final String GETTER = &quot;get&quot;;

    /** Constant meaning accessor type getter for boolean. */
    public static final String BOOLEAN_GETTER = &quot;is&quot;;

    /**
     * Instantiate a Class using its name.
     * @param className The class name.
     * @param arguments The arguments to be passed to constructor.
     * @param types The types of arguments.
     * @return The instance
     * @throws ClassNotFoundException Thrown if you try to instanciate a class that does not exist.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     * @throws InstantiationException Any other case
     */
    public static Object newInstance(final String className, final Object[] arguments, final Class[] types) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        // Retrieve class to be load
        Class clazz = Class.forName(className);

        // R??cup??ration du constructeur correspondant ????????? la liste des parametres donn??e
        Constructor constructor = clazz.getConstructor(types);

        // Cr??ation d&#039;une instance avec le constructeur r??cup??r??s
        return constructor.newInstance(arguments);
    }

    /**
     * Instantiate a Class using its name.
     * @param className The class name.
     * @param arguments The parameters to be passed to constructor.
     * @return The instance
     * @throws ClassNotFoundException Thrown if you try to instanciate a class that does not exist.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     * @throws InstantiationException Any other case
     */
    public static Object newInstance(final String className, final Object[] arguments) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        // Construct the types array
        Class[] types = new Class[arguments.length];
        for (int i = 0; i &lt;= arguments.length; ++i) {
            types[i] = arguments[i].getClass();
        }
        // Instantiate class
        return newInstance(className, arguments, types);
    }

    /**
     * Instantiate a Class using its name.
     * @param className The class name
     * @return The instance
     * @throws ClassNotFoundException Thrown if you try to instanciate a class that does not exist.
     * @throws InstantiationException Any other case
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object newInstance(final String className) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        return newInstance(className, new Object[] {});
    }

    /**
     * Invoke a methods (&lt;code&gt;methodName&lt;/code&gt;) from an &lt;code&gt;object&lt;/code&gt; with &lt;code&gt;arguments&lt;/code&gt; of &lt;code&gt;types&lt;/code&gt;.
     * @param object     The object from which you want to invoke a methods.
     * @param methodName The method name to invoke.
     * @param arguments  The arguments to pass to the methods.
     * @param types      The types of arguments.
     * @return the result of the invoked method.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeMethod(final Object object, final String methodName, final Object[] arguments, final Class[] types) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        try {
            // If simple getter is not found ... try boolean one
            return getMethod(object.getClass(), methodName, types).invoke(object, arguments);
        } catch (NoSuchMethodException ex) {
            NoSuchMethodException thrown = new NoSuchMethodException(formatInvokeGetterException(ex, object, methodName, arguments));
            thrown.setStackTrace(ex.getStackTrace());
            throw thrown;
        } catch (InvocationTargetException ex) {
            throw new InvocationTargetException(ex.getTargetException(), formatInvokeGetterException(ex.getTargetException(), object, methodName, arguments));
        } catch (IllegalAccessException ex) {
            IllegalAccessException thrown = new IllegalAccessException(formatInvokeGetterException(ex, object, methodName, arguments));
            thrown.setStackTrace(ex.getStackTrace());
            throw thrown;
        }
    }

    /**
     * Invoke a methods (&lt;code&gt;methodName&lt;/code&gt;) from an &lt;code&gt;object&lt;/code&gt; with &lt;code&gt;arguments&lt;/code&gt; of &lt;code&gt;types&lt;/code&gt;.
     * @param object     The object from which you want to invoke a methods.
     * @param method     The method to invoke.
     * @param arguments  The arguments to pass to the methods.
     * @return the result of the invoked method.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeMethod(final Object object, final Method method, final Object[] arguments) throws IllegalAccessException, InvocationTargetException {
        return method.invoke(object, arguments);
    }

    /**
     * Invoke a methods (&lt;code&gt;methodName&lt;/code&gt;) from an &lt;code&gt;object&lt;/code&gt; with &lt;code&gt;arguments&lt;/code&gt; of &lt;code&gt;types&lt;/code&gt;.
     * @param clazz      The &lt;code&gt;clazz&lt;/code&gt; on which to retreive the method.
     * @param methodName The method name to invoke.
     * @param arguments  The arguments to pass to the methods.
     * @param types      The types of arguments.
     * @return the result of the invoked method.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeStaticMethod(final Class clazz, final String methodName, final Object[] arguments, final Class[] types) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        return getMethod(clazz, methodName, types).invoke(null, arguments);
    }

    /**
     * Invoke a methods (&lt;code&gt;methodName&lt;/code&gt;) from an &lt;code&gt;object&lt;/code&gt; with &lt;code&gt;arguments&lt;/code&gt;.
     * @param object The object from which you want to invoke a methods.
     * @param methodName The method name to invoke.
     * @param arguments The arguments to pass to the methods.
     * @return the result of the invoked method.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeMethod(final Object object, final String methodName, final Object[] arguments) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        // Construct the types array
        Class[] types = new Class[arguments.length];
        for (int i = 0; i &lt; arguments.length; ++i) {
            types[i] = arguments[i].getClass();
        }
        return invokeMethod(object, methodName, arguments, types);
    }

    /**
     * This method invoke the setter according to the &lt;code&gt;fieldName&lt;/code&gt; on the &lt;code&gt;toFill&lt;/code&gt; object with as argument.
     * &lt;code&gt;valueToSet&lt;/code&gt; of type &lt;code&gt;valueToSetType&lt;/code&gt;
     * @param toFill the object to fill.
     * @param fieldName the field name.
     * @param valueToSet the value to set.
     * @param valueToSetType the type of the value to set.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static void invokeSetter(final Object toFill, final String fieldName, final Object valueToSet, final Class valueToSetType) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        invokeMethod(toFill, computeAccessorMethodName(SETTER, fieldName), new Object[] {valueToSet}, new Class[] {valueToSetType});
    }

    /**
     * This method invoke the getter according to the &lt;code&gt;fieldName&lt;/code&gt; on the &lt;code&gt;toFill&lt;/code&gt; object with as argument.
     * &lt;code&gt;valueToSet&lt;/code&gt; of type &lt;code&gt;valueToSetType&lt;/code&gt;
     * @param bean the JavaBean object.
     * @param fieldName the field name.
     * @return The value returned by the getter.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object invokeGetter(final Object bean, final String fieldName) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        String field = fieldName;
        Object instance = bean;
        while (field.indexOf(&#039;[&#039;) &gt; -1) {
            // Invoke getter to retreive the child element
            instance = invokeGetter(instance, field.substring(0, field.indexOf(&#039;[&#039;)));
            // If result is null no need to continue
            if (instance == null) {
                return null;
            }
            // Re route field name to retreive the field of the child instance
            int index = Integer.parseInt(field.substring(field.indexOf(&#039;[&#039;) + 1, field.indexOf(&#039;]&#039;)));
            instance = Array.get(instance, index);
            field = field.substring(field.indexOf(&#039;]&#039;) + 1);
        }
        // In the case that you want to retrieve in one time the field of a child object
        while (field.indexOf(&#039;.&#039;) &gt; 0) {
            // Invoke getter to retreive the child element
            instance = invokeGetter(instance, field.substring(0, field.indexOf(&#039;.&#039;)));
            // If result is null no need to continue
            if (instance == null) {
                return null;
            }
            // Re route field name to retreive the field of the child instance
            field = field.substring(field.indexOf(&#039;.&#039;) + 1);
        }
        if (field.length() == 0) {
            return instance;
        }
        try {
            return invokeMethod(instance, computeAccessorMethodName(GETTER, field), new Object[] {});
        } catch (NoSuchMethodException noSuchMethod) {
            String accessor = computeAccessorMethodName(BOOLEAN_GETTER, field);
            try {
                // If simple getter is not found ... try boolean one
                return invokeMethod(instance, accessor, new Object[] {});
            } catch (NoSuchMethodException ex) {
                // If it&#039;s still not found or return an error ... than throw the original error.
                throw noSuchMethod;
            }
        }
    }

    /**
     * Format a more detailed message when an exception occured during invocation.
     * @param ex        The exception
     * @param object    The object on which the given method is invoked
     * @param method    The invoked method
     * @param arguments The method arguments
     * @return The detailed message
     */
    private static String formatInvokeGetterException(final Throwable ex, final Object object, final String method, final Object[] arguments) {
        String message = ex.getMessage();
        if (message == null) {
            message = &quot;&quot;;
        } else {
            message += &quot; - &quot;;
        }
        String args = &quot;&quot;;
        for (int i = 0; i &lt; arguments.length; ++i) {
            args += arguments[i].getClass().getName();
            // Concat each element
            args += arguments[i];
            // Add separator if necessary
            if ((i &lt; arguments.length - 1)) {
                args += &quot;, &quot;;
            }
        }
        return message + &quot;Error occured while tyring to invoke &quot; + object.getClass().getName() + &quot;.&quot; + method + &quot;(&quot; + args + &quot;) method.&quot;;
    }

    /**
     * Get the field (&lt;code&gt;filedName&lt;/code&gt;) value of an &lt;code&gt;object&lt;/code&gt;.
     * @param object The &lt;code&gt;object&lt;/code&gt; on which to retreive the field value.
     * @param fieldName The &lt;code&gt;fieldName&lt;/code&gt; to retreive.
     * @return The value of the field.
     * @throws NoSuchFieldException Thrown if you try to retreive a field that does not exist.
     * @throws InvocationTargetException Can occure during invocation
     * @throws IllegalAccessException Thrown while trying to access illagaly the instance
     */
    public static Object getFieldValue(final Object object, final String fieldName) throws NoSuchFieldException, IllegalAccessException, InvocationTargetException {
        try {
            return getField(object.getClass(), fieldName).get(object);
        } catch (NoSuchFieldException ex) {
            try {
                return invokeGetter(object, fieldName);
            } catch (NoSuchMethodException x) {
                throw ex;
            }
        }
    }

    /**
     * Get the field (&lt;code&gt;filedName&lt;/code&gt;) of a class (&lt;code&gt;clazz&lt;/code&gt;).
     * @param clazz The &lt;code&gt;clazz&lt;/code&gt; on which to retreive the field.
     * @param fieldName The &lt;code&gt;fieldName&lt;/code&gt; to retreive.
     * @return The Field object of the given class.
     * @throws NoSuchFieldException Thrown if you try to retreive a field that does not exist.
     */
    public static Field getField(final Class clazz, final String fieldName) throws NoSuchFieldException {
        try {
            Field f = clazz.getDeclaredField(fieldName);
            f.setAccessible(true);
            return f;
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            if (clazz == Object.class) {
                throw e;
            }
            // Get the one from parent super class recursivly
            return getField(clazz.getSuperclass(), fieldName);
        }
    }

    /**
     * Return all declared fields of a class (and all its super class).
     * @see {@link Class#getDeclaredFields()}
     * @param clazz The class on which to retreive the fields.
     * @return All the fields.
     */
    public static List getDeclaredFields(final Class clazz) {
        List fields = new ArrayList();
        Class current = clazz;
        while (!current.getName().equals(Object.class.getName())) {
            fields.addAll(Arrays.asList(current.getDeclaredFields()));
            current = current.getSuperclass();
        }
        return fields;
    }

    /**
     * Return all getter of a class (but not the ones from parent).
     * @param clazz The class on which to retreive the getters.
     * @return All the methods.
     */
    public static List getGetters(final Class clazz) {
        List getters = new ArrayList();
        if (clazz != null) {
            Method[] methods = clazz.getMethods();
            for (int i = 0; i &lt; methods.length; i++) {
                if (methods[i].getDeclaringClass().equals(clazz)) {
                    if ((methods[i].getName().startsWith(GETTER) || methods[i].getName().startsWith(BOOLEAN_GETTER)) &amp;amp;&amp;amp; methods[i].getParameterTypes().length == 0) {
                        getters.add(methods[i]);
                    }
                }
            }
        }
        return getters;
    }

    /**
     * Return all getter of a class (even parent&#039;s ones).
     * @param clazz The class on which to retreive the getters.
     * @return All the methods.
     */
    public static List getGettersRecursivly(final Class clazz) {
        List getters = new ArrayList();
        if (clazz != null) {
            Class current = clazz;
            while (!current.getName().equals(Object.class.getName())) {
                Method[] methods = current.getMethods();
                for (int i = 0; i &lt; methods.length; i++) {
                    if (methods[i].getDeclaringClass().equals(current)) {
                        if ((methods[i].getName().startsWith(GETTER) || methods[i].getName().startsWith(BOOLEAN_GETTER)) &amp;amp;&amp;amp; methods[i].getParameterTypes().length == 0) {
                            getters.add(methods[i]);
                        }
                    }
                }
                current = current.getSuperclass();
            }
        }
        return getters;
    }

    /**
     * Return all getter of a class (but not the ones from parent).
     * @param clazz The class on which to retreive the getters.
     * @return All the methods.
     */
    public static List getSetters(final Class clazz) {
        List getters = new ArrayList();
        if (clazz != null) {
            Method[] methods = clazz.getMethods();
            for (int i = 0; i &lt; methods.length; i++) {
                if (methods[i].getDeclaringClass().equals(clazz)) {
                    if (methods[i].getName().startsWith(SETTER) &amp;amp;&amp;amp; methods[i].getName().length() &gt; SETTER.length() &amp;amp;&amp;amp; methods[i].getParameterTypes().length == 1) {
                        getters.add(methods[i]);
                    }
                }
            }
        }
        return getters;
    }

    /**
     * Return all getter of a class (even parent&#039;s ones).
     * @param clazz The class on which to retreive the getters.
     * @return All the methods.
     */
    public static List getSettersRecursivly(final Class clazz) {
        List getters = new ArrayList();
        if (clazz != null) {
            Class current = clazz;
            while (!current.getName().equals(Object.class.getName())) {
                Method[] methods = current.getMethods();
                for (int i = 0; i &lt; methods.length; i++) {
                    if (methods[i].getDeclaringClass().equals(current)) {
                        if (methods[i].getName().startsWith(SETTER) &amp;amp;&amp;amp; methods[i].getName().length() &gt; SETTER.length() &amp;amp;&amp;amp; methods[i].getParameterTypes().length == 1) {
                            getters.add(methods[i]);
                        }
                    }
                }
                current = current.getSuperclass();
            }
        }
        return getters;
    }

    /**
     * Retreive the method (&lt;code&gt;methodName&lt;/code&gt;) of a class (&lt;code&gt;clazz&lt;/code&gt;) using parameters &lt;code&gt;types&lt;/code&gt;.
     * @param clazz The &lt;code&gt;clazz&lt;/code&gt; on which to retreive the method.
     * @param methodName The method name to retreive.
     * @param types The types of the method&#039;s arguments.
     * @return A Method objec.
     * @throws NoSuchMethodException Thrown if you try to retreive a method that does not exist.
     */
    public static Method getMethod(final Class clazz, final String methodName, final Class[] types) throws NoSuchMethodException {
        try {
            Method m = clazz.getDeclaredMethod(methodName, types);
            m.setAccessible(true);
            return m;
        } catch (NoSuchMethodException x) {
            try {
                if (clazz == Object.class) {
                    throw x;
                }
                return getMethod(clazz.getSuperclass(), methodName, types);
            } catch (Exception ex) {
                throw x;
            }
        }
    }

    /**
     * This method compute the accessor method name according to the &lt;code&gt;accessorType&lt;/code&gt; and &lt;code&gt;fieldName&lt;/code&gt;.
     * @param accessorType the accessor type.
     * @param fieldName the field name.
     * @return the accessor method name.
     * @throw IllegalArgumentException If the arguments type is not valid.
     */
    private static String computeAccessorMethodName(final String accessorType, final String fieldName) {
        if (!accessorType.equals(SETTER) &amp;amp;&amp;amp; !accessorType.equals(GETTER) &amp;amp;&amp;amp; !accessorType.equals(BOOLEAN_GETTER)) {
            throw new IllegalArgumentException(&quot;Accessor Type : &quot; + accessorType + &quot; isn&#039;t correct&quot;);
        }
        if (null == fieldName || &quot;&quot;.equals(fieldName)) {
            throw new IllegalArgumentException(&quot;fieldName migth not be null or empty&quot;);
        }
        return accessorType + fieldName.replaceFirst(&quot;&quot; + fieldName.charAt(0), (&quot;&quot; + fieldName.charAt(0)).toUpperCase());
    }

    /**
     * If you want to map a getter/setter with its fied name.
     * Use this method to convert getter or setter into fieldname
     * @param method The method to be converted
     * @return The field name or method name if the method is neither a getter neither a setter
     */
    public static String getFieldName(final Method method) {
        String prefix = null;
        if (method.getName().startsWith(GETTER)) {
            prefix = GETTER;
        } else if (method.getName().startsWith(SETTER)) {
            prefix = SETTER;
        } else if (method.getName().startsWith(BOOLEAN_GETTER)) {
            prefix = BOOLEAN_GETTER;
        } else {
            return method.getName();
        }
        if (method.getName().length() == prefix.length()) {
            return method.getName();
        }
        return (&quot;&quot; + method.getName().charAt(prefix.length())).toLowerCase() + method.getName().substring(prefix.length() + 1);
    }
}
</pre>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=279</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Audio snippet code in Java</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=257</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=257#comments</comments>
		<pubDate>Wed, 24 Mar 2010 11:25:27 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Audio]]></category>
		<category><![CDATA[Snippet]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=257</guid>
		<description><![CDATA[Here is an example of two simple Java classes that deals with audio streams ! One for retrieving Info, the other for playing sound &#8230;
Voici deux petits exemples de classe Java pour gérer des flux audio. L&#8217;une affichant les informations, l&#8217;autre implémentant un lecteur très minimaliste !



import java.io.File;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.Port;
import [...]]]></description>
			<content:encoded><![CDATA[<p>Here is an example of two simple Java classes that deals with audio streams ! One for retrieving Info, the other for playing sound &#8230;</p>
<p>Voici deux petits exemples de classe Java pour gérer des flux audio. L&#8217;une affichant les informations, l&#8217;autre implémentant un lecteur très minimaliste !</p>
<pre>
<pre name="code" class="java">

import java.io.File;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.Port;
import javax.sound.sampled.SourceDataLine;

public class AudioInfo {

    public static void main(final String[] args) {
        try {
            AudioFileFormat format = AudioSystem.getAudioFileFormat(new File(&quot;Recharger.wav&quot;));
            System.out.println(&quot;format: &quot; + format);

            Mixer.Info[] infos = AudioSystem.getMixerInfo();
            Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
            Line.Info lineInfo = null;
            for (int i = 0; i &lt; infos.length; ++i) {
                Mixer mixer = AudioSystem.getMixer(mixerInfo[i]);
                System.out.println(&quot;Target lines infos&quot;);
                Line.Info[] lineInfos = mixer.getTargetLineInfo(Port.Info.SPEAKER);
                for (int l = 0; l &lt; lineInfos.length; ++l) {
                    System.out.println(&quot;Line Info &quot; + l + &quot; - &quot; + lineInfos[l]);
                    lineInfo = lineInfos[l];
                }
            }

            SourceDataLine sourceLine;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, format.getFormat()); // format is an AudioFormat object
            if (AudioSystem.isLineSupported(info)) {
                // Obtain and open the line.
                try {
                    sourceLine = (SourceDataLine) AudioSystem.getLine(info);
                    sourceLine.open(format.getFormat());
                } catch (LineUnavailableException ex) {
                    // Handle the error.
                    ex.printStackTrace();
                }
            } else {
                // Handle the error.
                System.out.println(&quot;Line is not supported&quot;);
            }

            Port targetLine;
            if (AudioSystem.isLineSupported(Port.Info.SPEAKER)) {
                try {
                    targetLine = (Port) AudioSystem.getLine(Port.Info.SPEAKER);
                    targetLine.open();
                } catch (LineUnavailableException ex) {
                    // Handle the error.
                    ex.printStackTrace();
                }
            } else {
                // Handle the error.
                System.out.println(&quot;SPEAKER Line is not supported&quot;);
            }

        } catch (Exception ex) {
            //UnsupportedAudioFile... &amp;amp; IO...
            ex.printStackTrace();
        }
    }
}
</pre>
</pre>
<pre>
<pre name="code" class="java">

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class SoundPlayer extends JFrame implements Runnable {

    private final File currentDir; // Current directory
    private String oldFilename; // Last selected file name
    private final JComboBox soundChoice; // Dropdown list of files
    private final JButton play; // PLAY button
    private AudioInputStream source; // Stream for the sound file
    private SourceDataLine sourceLine; // The speaker output line
    private byte[] soundData; // Buffer to hold samples
    private int bufferSize; // Buffer size in bytes
    private Thread thread; // Playing thread
    private boolean playing = false; // Thread control

    public SoundPlayer() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle(&quot;Sound File Player&quot;);
        setSize(250, 100);

        // Get the sounds file names from current directory
        currentDir = new File(System.getProperty(&quot;user.dir&quot;));
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(final File directory, final String filename) {
                String name = filename.toLowerCase();
                return name.endsWith(&quot;.au&quot;) || name.endsWith(&quot;.aif&quot;) || name.endsWith(&quot;.wav&quot;);
            }
        };
        String soundFiles[] = currentDir.list(filter);
        if (soundFiles == null || soundFiles.length == 0) {
            JOptionPane.showMessageDialog(this, &quot;No sound files .:. terminating...&quot;, &quot;Sound Files Error&quot;, JOptionPane.ERROR_MESSAGE);
            System.exit(1);
        }
        soundChoice = new JComboBox(soundFiles);
        soundChoice.setSelectedIndex(0);
        newSound(soundFiles[0]);
        oldFilename = soundFiles[0];

        soundChoice.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                newSound((String) soundChoice.getSelectedItem());
            }
        });

        // Set up the PLAY button to play the current sound file
        play = new JButton(&quot;PLAY&quot;);
        play.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                if (e.getActionCommand().equals(&quot;PLAY&quot;)) {
                    startPlay();
                    play.setText(&quot;STOP&quot;);
                } else {
                    stopPlay();
                    play.setText(&quot;PLAY&quot;);
                }
            }
        });
        Container content = getContentPane();
        content.add(soundChoice);
        content.add(play, BorderLayout.SOUTH);
        setVisible(true);
    }

    public static void main(final String[] args) {
        new SoundPlayer();
    }

    public void newSound(final String filename) {
        File soundFile = new File(currentDir, filename);

        // We may have played a file already
        if (sourceLine != null) {// If we have a line
            if (sourceLine.isActive()) {
                sourceLine.stop(); // ...stop it
            }
            play.setText(&quot;PLAY&quot;); // Ensure button is PLAY
        }

        // Now try for a stream and a line
        try {
            AudioInputStream newSource = AudioSystem.getAudioInputStream(soundFile);

            if (newSource.markSupported()) {
                newSource.mark(Integer.MAX_VALUE); // mark the start for later reset
            }

            AudioFormat format = newSource.getFormat(); // Get the audio format
            DataLine.Info sourceInfo = new DataLine.Info(SourceDataLine.class, format);
            if (AudioSystem.isLineSupported(sourceInfo)) { // If the line type is supported
                // Get a new line
                sourceLine = (SourceDataLine) AudioSystem.getLine(sourceInfo);
                bufferSize = (int) (format.getFrameSize() * format.getFrameRate() / 2.0f);
                sourceLine.open(format, bufferSize); // Open the line
                source = newSource; // New line is OK so save it
                soundData = new byte[bufferSize]; // Create the buffer for read
                oldFilename = filename; // Save the current file name
            } else {
                JOptionPane.showMessageDialog(null, &quot;Line not supported&quot;, &quot;Line NotSupported&quot;, JOptionPane.WARNING_MESSAGE);
                soundChoice.setSelectedItem(oldFilename); // Restore the old selection
            }
        } catch (UnsupportedAudioFileException e) {
            JOptionPane.showMessageDialog(null, &quot;File not supported&quot;, &quot;Unsupported File Type&quot;, JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        } catch (LineUnavailableException e) {
            JOptionPane.showMessageDialog(null, &quot;Line not available&quot;, &quot;Line Error&quot;, JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, &quot;I/O Error creating stream&quot;, &quot;I/O Error&quot;, JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        }
    }

    // Start playing the current file
    public void startPlay() {
        if (sourceLine == null) {// Verify we have a line
            JOptionPane.showMessageDialog(null, &quot;No line available&quot;, &quot;Play Problem&quot;, JOptionPane.WARNING_MESSAGE);
            return;
        }
        thread = new Thread(this); // Create the playing thread
        playing = true; // Set the control to true
        thread.start(); // Start the thread
    }

    // Stop playing the current file
    public void stopPlay() {
        playing = false;
    }

    // The playing thread
    public void run() {
        sourceLine.start(); // Start the line
        int byteCount = 0; // Bytes read
        try {
            while (playing) { // Continue while true
                byteCount = source.read(soundData, 0, soundData.length); // Read the stream

                if (byteCount == -1) { // If it&#039;s the end of input
                    if (source.markSupported()) {
                        source.reset(); // ...put it back to the start
                        sourceLine.drain(); // Play what is left in the buffer
                        playing = false; // Reset the thread control
                    } else {
                        sourceLine.drain(); // Play what is left in the buffer
                        playing = false; // Reset the thread control
                        source.close();
                        newSound((String) soundChoice.getSelectedItem());
                    }
                    break; // then stop playing
                }
                sourceLine.write(soundData, 0, byteCount); // Write the array to the line
            }
        } catch (IOException e) { // For the stream read operation
            System.err.println(e);
        }
        sourceLine.stop(); // Stop the line
        play.setText(&quot;PLAY&quot;); // Reset the button text
    }
}
</pre>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=257</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get classes contained in a package</title>
		<link>http://gabriel.dromard.free.fr/blog/?p=270</link>
		<comments>http://gabriel.dromard.free.fr/blog/?p=270#comments</comments>
		<pubDate>Wed, 24 Mar 2010 10:46:37 +0000</pubDate>
		<dc:creator>Gab</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://gabriel.dromard.free.fr/blog/?p=270</guid>
		<description><![CDATA[En Anglais: This is a java code snipplet that retrieve the package&#8217;s classes.
In French: Un petit exemple de code java permettant de récupérer les classes contenues dans un package.



public static Class[] getClasses(Package pckg) throws IOException, ClassNotFoundException {
    // Translate the package name into an absolute path
    String name = [...]]]></description>
			<content:encoded><![CDATA[<p>En Anglais: This is a java code snipplet that retrieve the package&#8217;s classes.</p>
<p>In French: Un petit exemple de code java permettant de récupérer les classes contenues dans un package.</p>
<pre>
<pre name="code" class="java">

public static Class[] getClasses(Package pckg) throws IOException, ClassNotFoundException {
    // Translate the package name into an absolute path
    String name = &quot;/&quot; + pckg.getName().replace(&#039;.&#039;,&#039;/&#039;);

    // Get a File object for the package
    URL url = Launcher.class.getResource(name);
    File directory = new File(url.getFile());

    if (directory.exists()) {
        // Get the list of the files contained in the package
        String[] files = directory.list();
        ArrayList vClasses = new ArrayList();
        for (int i=0; i&lt;files.length;++i) {

            // we are only interested in .class files
            if (files[i].endsWith(&quot;.class&quot;)) {
                // removes the .class extension
                String classname = files[i].substring(0,files[i].length()-6);
                vClasses.add(Class.forName(pckg.getName()+&quot;.&quot;+classname));
            }
        }
        Class[] classes = new Class[vClasses.size()];
        for (int i=0; i&lt;vClasses.size();++i) classes[i] = (Class)vClasses.get(i);
        return classes;
    } else {
        throw new IOException(&quot;Invalid directory: &quot;+url);
    }
}
</pre>
</pre>
]]></content:encoded>
			<wfw:commentRss>http://gabriel.dromard.free.fr/blog/?feed=rss2&amp;p=270</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
