Archive

Articles taggués ‘Java’

Ajouter un timeout en RMI – How to handle a timeout on RMI connections ?

29/06/2010
Commentaires fermés

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 « How to handle timeout on a RMI connection », lets try the execution of following code:

Lire la suite…

Java ,

Audio snippet code in Java

24/03/2010
Commentaires fermés

Here is an example of two simple Java classes that deals with audio streams ! One for retrieving Info, the other for playing sound …

Voici deux petits exemples de classe Java pour gérer des flux audio. L’une affichant les informations, l’autre implémentant un lecteur très minimaliste !

  1. import java.io.File;  
  2.   
  3. import javax.sound.sampled.AudioFileFormat;  
  4. import javax.sound.sampled.AudioSystem;  
  5. import javax.sound.sampled.DataLine;  
  6. import javax.sound.sampled.Line;  
  7. import javax.sound.sampled.LineUnavailableException;  
  8. import javax.sound.sampled.Mixer;  
  9. import javax.sound.sampled.Port;  
  10. import javax.sound.sampled.SourceDataLine;  
  11.   
  12. public class AudioInfo {  
  13.   
  14.     public static void main(final String[] args) {  
  15.         try {  
  16.             AudioFileFormat format = AudioSystem.getAudioFileFormat(new File("Recharger.wav"));  
  17.             System.out.println("format: " + format);  
  18.   
  19.             Mixer.Info[] infos = AudioSystem.getMixerInfo();  
  20.             Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();  
  21.             Line.Info lineInfo = null;  
  22.             for (int i = 0; i < infos.length; ++i) {  
  23.                 Mixer mixer = AudioSystem.getMixer(mixerInfo[i]);  
  24.                 System.out.println("Target lines infos");  
  25.                 Line.Info[] lineInfos = mixer.getTargetLineInfo(Port.Info.SPEAKER);  
  26.                 for (int l = 0; l < lineInfos.length; ++l) {  
  27.                     System.out.println("Line Info " + l + " - " + lineInfos[l]);  
  28.                     lineInfo = lineInfos[l];  
  29.                 }  
  30.             }  
  31.   
  32.             SourceDataLine sourceLine;  
  33.             DataLine.Info info = new DataLine.Info(SourceDataLine.class, format.getFormat()); // format is an AudioFormat object  
  34.             if (AudioSystem.isLineSupported(info)) {  
  35.                 // Obtain and open the line.  
  36.                 try {  
  37.                     sourceLine = (SourceDataLine) AudioSystem.getLine(info);  
  38.                     sourceLine.open(format.getFormat());  
  39.                 } catch (LineUnavailableException ex) {  
  40.                     // Handle the error.  
  41.                     ex.printStackTrace();  
  42.                 }  
  43.             } else {  
  44.                 // Handle the error.  
  45.                 System.out.println("Line is not supported");  
  46.             }  
  47.   
  48.             Port targetLine;  
  49.             if (AudioSystem.isLineSupported(Port.Info.SPEAKER)) {  
  50.                 try {  
  51.                     targetLine = (Port) AudioSystem.getLine(Port.Info.SPEAKER);  
  52.                     targetLine.open();  
  53.                 } catch (LineUnavailableException ex) {  
  54.                     // Handle the error.  
  55.                     ex.printStackTrace();  
  56.                 }  
  57.             } else {  
  58.                 // Handle the error.  
  59.                 System.out.println("SPEAKER Line is not supported");  
  60.             }  
  61.   
  62.         } catch (Exception ex) {  
  63.             //UnsupportedAudioFile... &amp; IO...  
  64.             ex.printStackTrace();  
  65.         }  
  66.     }  
  67. }  
  1. import java.awt.BorderLayout;  
  2. import java.awt.Container;  
  3. import java.awt.event.ActionEvent;  
  4. import java.awt.event.ActionListener;  
  5. import java.io.File;  
  6. import java.io.FilenameFilter;  
  7. import java.io.IOException;  
  8.   
  9. import javax.sound.sampled.AudioFormat;  
  10. import javax.sound.sampled.AudioInputStream;  
  11. import javax.sound.sampled.AudioSystem;  
  12. import javax.sound.sampled.DataLine;  
  13. import javax.sound.sampled.LineUnavailableException;  
  14. import javax.sound.sampled.SourceDataLine;  
  15. import javax.sound.sampled.UnsupportedAudioFileException;  
  16. import javax.swing.JButton;  
  17. import javax.swing.JComboBox;  
  18. import javax.swing.JFrame;  
  19. import javax.swing.JOptionPane;  
  20.   
  21. public class SoundPlayer extends JFrame implements Runnable {  
  22.   
  23.     private final File currentDir; // Current directory  
  24.     private String oldFilename; // Last selected file name  
  25.     private final JComboBox soundChoice; // Dropdown list of files  
  26.     private final JButton play; // PLAY button  
  27.     private AudioInputStream source; // Stream for the sound file  
  28.     private SourceDataLine sourceLine; // The speaker output line  
  29.     private byte[] soundData; // Buffer to hold samples  
  30.     private int bufferSize; // Buffer size in bytes  
  31.     private Thread thread; // Playing thread  
  32.     private boolean playing = false// Thread control  
  33.   
  34.     public SoundPlayer() {  
  35.         setDefaultCloseOperation(EXIT_ON_CLOSE);  
  36.         setTitle("Sound File Player");  
  37.         setSize(250100);  
  38.   
  39.         // Get the sounds file names from current directory  
  40.         currentDir = new File(System.getProperty("user.dir"));  
  41.         FilenameFilter filter = new FilenameFilter() {  
  42.             public boolean accept(final File directory, final String filename) {  
  43.                 String name = filename.toLowerCase();  
  44.                 return name.endsWith(".au") || name.endsWith(".aif") || name.endsWith(".wav");  
  45.             }  
  46.         };  
  47.         String soundFiles[] = currentDir.list(filter);  
  48.         if (soundFiles == null || soundFiles.length == 0) {  
  49.             JOptionPane.showMessageDialog(this"No sound files .:. terminating...""Sound Files Error", JOptionPane.ERROR_MESSAGE);  
  50.             System.exit(1);  
  51.         }  
  52.         soundChoice = new JComboBox(soundFiles);  
  53.         soundChoice.setSelectedIndex(0);  
  54.         newSound(soundFiles[0]);  
  55.         oldFilename = soundFiles[0];  
  56.   
  57.         soundChoice.addActionListener(new ActionListener() {  
  58.             public void actionPerformed(final ActionEvent e) {  
  59.                 newSound((String) soundChoice.getSelectedItem());  
  60.             }  
  61.         });  
  62.   
  63.         // Set up the PLAY button to play the current sound file  
  64.         play = new JButton("PLAY");  
  65.         play.addActionListener(new ActionListener() {  
  66.             public void actionPerformed(final ActionEvent e) {  
  67.                 if (e.getActionCommand().equals("PLAY")) {  
  68.                     startPlay();  
  69.                     play.setText("STOP");  
  70.                 } else {  
  71.                     stopPlay();  
  72.                     play.setText("PLAY");  
  73.                 }  
  74.             }  
  75.         });  
  76.         Container content = getContentPane();  
  77.         content.add(soundChoice);  
  78.         content.add(play, BorderLayout.SOUTH);  
  79.         setVisible(true);  
  80.     }  
  81.   
  82.     public static void main(final String[] args) {  
  83.         new SoundPlayer();  
  84.     }  
  85.   
  86.     public void newSound(final String filename) {  
  87.         File soundFile = new File(currentDir, filename);  
  88.   
  89.         // We may have played a file already  
  90.         if (sourceLine != null) {// If we have a line  
  91.             if (sourceLine.isActive()) {  
  92.                 sourceLine.stop(); // ...stop it  
  93.             }  
  94.             play.setText("PLAY"); // Ensure button is PLAY  
  95.         }  
  96.   
  97.         // Now try for a stream and a line  
  98.         try {  
  99.             AudioInputStream newSource = AudioSystem.getAudioInputStream(soundFile);  
  100.   
  101.             if (newSource.markSupported()) {  
  102.                 newSource.mark(Integer.MAX_VALUE); // mark the start for later reset  
  103.             }  
  104.   
  105.             AudioFormat format = newSource.getFormat(); // Get the audio format  
  106.             DataLine.Info sourceInfo = new DataLine.Info(SourceDataLine.class, format);  
  107.             if (AudioSystem.isLineSupported(sourceInfo)) { // If the line type is supported  
  108.                 // Get a new line  
  109.                 sourceLine = (SourceDataLine) AudioSystem.getLine(sourceInfo);  
  110.                 bufferSize = (int) (format.getFrameSize() * format.getFrameRate() / 2.0f);  
  111.                 sourceLine.open(format, bufferSize); // Open the line  
  112.                 source = newSource; // New line is OK so save it  
  113.                 soundData = new byte[bufferSize]; // Create the buffer for read  
  114.                 oldFilename = filename; // Save the current file name  
  115.             } else {  
  116.                 JOptionPane.showMessageDialog(null"Line not supported""Line NotSupported", JOptionPane.WARNING_MESSAGE);  
  117.                 soundChoice.setSelectedItem(oldFilename); // Restore the old selection  
  118.             }  
  119.         } catch (UnsupportedAudioFileException e) {  
  120.             JOptionPane.showMessageDialog(null"File not supported""Unsupported File Type", JOptionPane.WARNING_MESSAGE);  
  121.             soundChoice.setSelectedItem(oldFilename);  
  122.         } catch (LineUnavailableException e) {  
  123.             JOptionPane.showMessageDialog(null"Line not available""Line Error", JOptionPane.WARNING_MESSAGE);  
  124.             soundChoice.setSelectedItem(oldFilename);  
  125.         } catch (IOException e) {  
  126.             JOptionPane.showMessageDialog(null"I/O Error creating stream""I/O Error", JOptionPane.WARNING_MESSAGE);  
  127.             soundChoice.setSelectedItem(oldFilename);  
  128.         }  
  129.     }  
  130.   
  131.     // Start playing the current file  
  132.     public void startPlay() {  
  133.         if (sourceLine == null) {// Verify we have a line  
  134.             JOptionPane.showMessageDialog(null"No line available""Play Problem", JOptionPane.WARNING_MESSAGE);  
  135.             return;  
  136.         }  
  137.         thread = new Thread(this); // Create the playing thread  
  138.         playing = true// Set the control to true  
  139.         thread.start(); // Start the thread  
  140.     }  
  141.   
  142.     // Stop playing the current file  
  143.     public void stopPlay() {  
  144.         playing = false;  
  145.     }  
  146.   
  147.     // The playing thread  
  148.     public void run() {  
  149.         sourceLine.start(); // Start the line  
  150.         int byteCount = 0// Bytes read  
  151.         try {  
  152.             while (playing) { // Continue while true  
  153.                 byteCount = source.read(soundData, 0, soundData.length); // Read the stream  
  154.   
  155.                 if (byteCount == -1) { // If it's the end of input  
  156.                     if (source.markSupported()) {  
  157.                         source.reset(); // ...put it back to the start  
  158.                         sourceLine.drain(); // Play what is left in the buffer  
  159.                         playing = false// Reset the thread control  
  160.                     } else {  
  161.                         sourceLine.drain(); // Play what is left in the buffer  
  162.                         playing = false// Reset the thread control  
  163.                         source.close();  
  164.                         newSound((String) soundChoice.getSelectedItem());  
  165.                     }  
  166.                     break// then stop playing  
  167.                 }  
  168.                 sourceLine.write(soundData, 0, byteCount); // Write the array to the line  
  169.             }  
  170.         } catch (IOException e) { // For the stream read operation  
  171.             System.err.println(e);  
  172.         }  
  173.         sourceLine.stop(); // Stop the line  
  174.         play.setText("PLAY"); // Reset the button text  
  175.     }  
  176. }  

Java , ,

Mise à jour de l’application URLPinger

19/03/2010
Commentaires fermés

URLPinger, petite application qui se met dans le systray (icônes en bas à droite sous Windows) à été mis à jour !

La version 0.3 permet de personnaliser le temps d’attentes entre deux vérifications de l’URL.

La version 0.4 permet de ne pas perdre la définition de ses services lors de la fermeture / réouverture de l’application. (Les paramètres sont stockés dans le répertoire utilisateur).


java1 Télécharger
URLPinger.jar (582)

Lire les articles sur cette application.

Java , , ,

Digester Factory

22/09/2009
Commentaires fermés

This is a DigesterFactory class that load a XML file into an object using an other XML rule file.

I like this way of loading java object from a XML file, because it’s not intrusive, you just have to give it a rule file that define the way of loading object.


  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.net.URL;  
  4.   
  5. import org.apache.commons.digester.Digester;  
  6. import org.apache.commons.digester.xmlrules.DigesterLoader;  
  7. import org.xml.sax.SAXException;  
  8.   
  9. /** 
  10.  * Digester Factory 
  11.  * This load a Java object from a XML file using Digester framework 
  12.  * 
  13.  * @author Gabriel Dromard 
  14.  */  
  15. public class DigesterFactory {  
  16.     /* 
  17.     public static Root loadRoot(File input) throws SAXException, Exception { 
  18.         // Create the digester instance 
  19.         Digester digester = new Digester(); 
  20.  
  21.         // Activate or not the DTD checking 
  22.         digester.setValidating( false ); 
  23.  
  24.         // This is needed because digester is sending errors directly to output without raising exceptions othervise 
  25.         //digester.setErrorHandler(new DefaultSAXErrorHandler()); 
  26.         digester.setErrorHandler(new ErrorHandler() { 
  27.             public void error(SAXParseException exception) throws SAXException { throw exception; } 
  28.             public void fatalError(SAXParseException exception) throws SAXException { throw exception; } 
  29.             public void warning(SAXParseException exception) throws SAXException { throw exception; } 
  30.         }); 
  31.  
  32.         // Parsing rules 
  33.         digester.addObjectCreate( "myxml", Root.class ); 
  34.         //digester.addSetProperties( "descriptor", "type", "type" ); 
  35.         //digester.addSetProperties( "myxml/a/b", new String [] {"type", "target", "header"} , new String [] {"outputType", "outputTarget", "header"} ); 
  36.  
  37.         digester.addObjectCreate( "myxml/a", A.class ); 
  38.         digester.addSetProperties( "myxml/a", "name", "name" ); 
  39.         digester.addSetProperties( "myxml/a/b", "name" , "bname" ); 
  40.         digester.addSetNext( "myxml/a", "setA"); 
  41.  
  42.         digester.addObjectCreate( "myxml/a/c", C.class ); 
  43.         digester.addSetProperties( "myxml/a/c", new String [] {"name", "value"} , new String [] {"name", "value"} ); 
  44.         digester.addBeanPropertySetter("myxml/a/c", "description"); 
  45.         digester.addSetNext( "myxml/a/c", "addC"); 
  46.  
  47.         return (Root)digester.parse( input ); 
  48.     } 
  49. */  
  50.   
  51.     /** 
  52.      * Load an object from a XML file unsing digester framwork 
  53.      * @param input The data input file defining the Java Object 
  54.      * @param rules The rules input file defininf the digester rules for loading this Java Object 
  55.      * @return Return an instance of the a Java Object (defined in rule file) 
  56.      * @throws SAXException Can be thrown while parsing files. 
  57.      * @throws Exception Can be MalformedURLException or IOException for the input or rules files. 
  58.      * @see DigesterFactory#load(File, URL) 
  59.      * @see DigesterFactory#load(URL, URL) 
  60.      */  
  61.     public static Object load(File input, File rules) throws SAXException, IOException {  
  62.         Digester digester = DigesterLoader.createDigester(rules.toURI().toURL());  
  63.         return digester.parse(input);  
  64.     }  
  65.   
  66.     /** 
  67.      * Load an object from a XML file unsing digester framwork 
  68.      * @param input The data input URL defining the Java Object 
  69.      * @param rules The rules input URL defining the digester rules for loading this Java Object 
  70.      * @return Return an instance of the a Java Object (defined in rule file) 
  71.      * @throws SAXException Can be thrown while parsing files. 
  72.      * @throws Exception Can be MalformedURLException or IOException for the input or rules files. 
  73.      * @see DigesterFactory#load(File, URL) 
  74.      * @see DigesterFactory#load(File, File) 
  75.      */  
  76.     public static Object load(URL input, URL rules) throws SAXException, IOException {  
  77.         Digester digester = DigesterLoader.createDigester(rules);  
  78.         return digester.parse(input.openStream());  
  79.     }  
  80.   
  81.     /** 
  82.      * Load an object from a XML file unsing digester framwork 
  83.      * @param input The data input file defining the Java Object 
  84.      * @param rules The rules input URL defining the digester rules for loading this Java Object 
  85.      * @return Return an instance of the a Java Object (defined in rule file) 
  86.      * @throws SAXException Can be thrown while parsing files. 
  87.      * @throws Exception Can be MalformedURLException or IOException for the input or rules files. 
  88.      * @see DigesterFactory#load(URL, URL) 
  89.      * @see DigesterFactory#load(File, File) 
  90.      */  
  91.     public static Object load(File input, URL rules) throws SAXException, IOException {  
  92.         Digester digester = DigesterLoader.createDigester(rules);  
  93.         return digester.parse(input);  
  94.     }  
  95.   
  96.     public static void main(String[] args) {  
  97.         if (args.length == 2) {  
  98.             try {  
  99.                 //Root o = loadRoot(new File( "input.xml" ));  
  100.                 //Object o = load(new File("input.xml"), new File("digester-input-rules.xml"));  
  101.                 Object o = load(new File(args[0]), new File(args[1]));  
  102.                 /*Display resulting beans*/  
  103.                 System.out.println("=================================");  
  104.                 System.out.println(o.toString());  
  105.                 System.out.println("=================================");  
  106.             } catch( SAXException saxEx) {  
  107.                 System.err.println("Error in XML parsing: "+saxEx.getMessage());  
  108.             } catch( Exception exc ) {  
  109.                 exc.printStackTrace(System.err);  
  110.             }  
  111.         } else {  
  112.             System.out.println("Usage: java "+DigesterFactory.class.getName()+" [XML input file] [XML rule]");  
  113.         }  
  114.     }  
  115. }  

Java , ,

Exemple/Tutoriel: Utiliser un agent java …

14/09/2009
Commentaires fermés

Même s’il n’existe pas beaucoup de documentation sur cette possibilité offerte dans Java depuis le JDK 1.5, il existe de bon articles comme cette introduction de « Soft qui peut » ainsi que celle de Xebia.

En condensé, un JavaAgent est déployé sous forme de jar (contenant un Manifest spécifique: Premain-Class: my.package.MyAgent) et utilisé via une option donnée à la JVM (-javaagent:path/mayagent.jar).Voir la documentation Sun pour plus de détails sur les options.

Un Agent  Java est un composant qui s’interconnecte entre la machine virtuelle Java et le logiciel. Il est appelé à chaque chargement d’une classe. Il peut donc écouter tous les appels. Son utilisation la plus simple et la plus courante est le profiling, logging …

Il peut également être utilisé pour faire de l’AOP (Programmation orientée Aspect).

Ici je vous propose une implémentation d’un agent permettant de mettre en œuvre un petit outil de monitoring en utilisant l’AOP. Lire la suite…

Java , , , ,

Un serveur qui tombe …

22/07/2009
Commentaires fermés

Vous voulez écouter vos serveur web pour vérifier qu’ils soient bien disponible ? URLPinger.jar (582) est une petite application fait pour !

Ecrite en Java, elle se loge dans le ‘Systray’ (barre des taches). Vous pourrez y ajouter des services qui écoute une URL, et vous serez informé dès que l’URL n’est plus accessible !

Elle est même en mesure de suivre l’historique des états du service web ! (pour les services qui tombent souvent ça peut-être utile)

Java ,

La premiére du JUG Toulousain

12/05/2009
Commentaires fermés

Bonjour !

Juste, un petit post pour vous rappeler que c’est ce soir à 18h à l’Université Paul Sabatier que le JUG Toulousain fait sa première conférence.

A programme nous écouterons Bruno Marchesson (consultant sénior Valtech) qui nous parlera du framework GWT, puis Sylvain Wallez (CTO Goojet) qui traitera des sujets relatifs aux développements sur mobile (JavaME).

A ce soir.

Java , , ,

Le Test Driven Development (ou TDD pour les intimes)

08/04/2009

Qu’est que le TDD ? Bonne question ?

Prenons un petit exemple de réalisation d’une méthode en suivant la méthode du TDD (Test Driven Developpement ou en français le développement piloté par les tests).

Lire la suite…

Java , , , , ,

Que d’outils pour inciter à un code ‘de qualité’ !

08/04/2009

eclipseTestNG, EclEmma, Checkstyle, sont des outils intéressant à mettre dans notre boite à outil qu’est Eclipse !

Le plugin TestNG, un concurrent sérieux de JUnit qui se base sur les annotations, permet de développer des tests unitaires. Et le plugin EclEmma permet de visualiser très rapidement la couverture de notre test écrit à l’aide de TestNG (il fonctionne également avec JUnit).

Les actions de sauvegardes d’eclipse, peuvent elle aussi nous permettre de réaliser certaine taches/actions avant la sauvegarde, comme l’ajout du mot clef ‘final’ sur les attributs de méthode, formater le code, organiser les import…

Java , , , , ,

Une très petite application

11/11/2008
Commentaires fermés

Après avoir écris un petit post sur comment télécharger un album picasaweb … quelques mois ont passés et iPhoto (sur mac) à été mis à jours et permet d’orénavant de s’abonner à un flux RSS.

Pour les Windowsiens je conseille très vivement Picasa 2.

Malheureusement, certaine personnes, comme ma belle grand mère n’a pas une version récente de Mac et n’a pas pu privilégier des mises à jour d’iPhoto.

J’ai donc pris un peu de temps pour développer une très petite application (Picasaweb Album Downloader) permettant de télécharger l’ensemble d’un album picasaweb.

Cette petite application est dévelopée en Java, elle peut donc être utilisée aussi bien sur windows que sur Mac.

Je serais heureux que vous me laissiez un petit commentaire pour me dire que vous l’utilisez et si vous en êtes satisfait.

Java, Mac , , , , , , , ,