Archive

Archives pour la catégorie ‘Source Code’

Javascript Bookmark function

08/06/2011
Commentaires fermés

function bookmark(bookmarkurl, bookmarktitle) {
    try {
        if (typeof window.sidebar == "object" && typeof window.sidebar.addPanel == "function") {
            window.sidebar.addPanel(bookmarktitle, bookmarkurl, "");
        } else if (typeof window.external == "object") {
            if (typeof window.external.AddToFavoritesBar == "function") {
                window.external.AddToFavoritesBar(bookmarkurl,bookmarktitle);
            } else {
                window.external.AddFavorite(bookmarkurl,bookmarktitle);
            }
        } else {
            alert('Ooops, I do not know how to create a bookmark on your browser!\nYou have to do it your self!');
        }
    } catch(e) {
        alert('Ooops, I did not manage to create the bookmark on your browser!\nYou have to do it your self!');
    }
}

JavaScript , , ,

MessageHandler class

24/05/2011
Commentaires fermés

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

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

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

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

	showError: function(msg) {
		var div = $('mhErr');
		div.update(/*'<p align="right"><a href="#" onClick="$(\'mhErr\').hide()">[X]</a></p>'+*/msg);
		div.show();
		if (this.reqErrId != null) clearTimeout(this.reqErrId);
		this.reqErrId = setTimeout(function() { $('mhErr').hide(); }, this.messageDisplayTime);
	}
});

JavaScript

StringBuffer Class

24/05/2011
Commentaires fermés

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("");
	}
});

JavaScript

Reflect Helper class

24/03/2010
Commentaires fermés

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 = "set";

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

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

    /**
     * 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'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 <= 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 (<code>methodName</code>) from an <code>object</code> with <code>arguments</code> of <code>types</code>.
     * @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 (<code>methodName</code>) from an <code>object</code> with <code>arguments</code> of <code>types</code>.
     * @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 (<code>methodName</code>) from an <code>object</code> with <code>arguments</code> of <code>types</code>.
     * @param clazz      The <code>clazz</code> 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 (<code>methodName</code>) from an <code>object</code> with <code>arguments</code>.
     * @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 < arguments.length; ++i) {
            types[i] = arguments[i].getClass();
        }
        return invokeMethod(object, methodName, arguments, types);
    }

    /**
     * This method invoke the setter according to the <code>fieldName</code> on the <code>toFill</code> object with as argument.
     * <code>valueToSet</code> of type <code>valueToSetType</code>
     * @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 <code>fieldName</code> on the <code>toFill</code> object with as argument.
     * <code>valueToSet</code> of type <code>valueToSetType</code>
     * @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('[') > -1) {
            // Invoke getter to retreive the child element
            instance = invokeGetter(instance, field.substring(0, field.indexOf('[')));
            // 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('[') + 1, field.indexOf(']')));
            instance = Array.get(instance, index);
            field = field.substring(field.indexOf(']') + 1);
        }
        // In the case that you want to retrieve in one time the field of a child object
        while (field.indexOf('.') > 0) {
            // Invoke getter to retreive the child element
            instance = invokeGetter(instance, field.substring(0, field.indexOf('.')));
            // 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('.') + 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'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 = "";
        } else {
            message += " - ";
        }
        String args = "";
        for (int i = 0; i < arguments.length; ++i) {
            args += arguments[i].getClass().getName();
            // Concat each element
            args += arguments[i];
            // Add separator if necessary
            if ((i < arguments.length - 1)) {
                args += ", ";
            }
        }
        return message + "Error occured while tyring to invoke " + object.getClass().getName() + "." + method + "(" + args + ") method.";
    }

    /**
     * Get the field (<code>filedName</code>) value of an <code>object</code>.
     * @param object The <code>object</code> on which to retreive the field value.
     * @param fieldName The <code>fieldName</code> 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 (<code>filedName</code>) of a class (<code>clazz</code>).
     * @param clazz The <code>clazz</code> on which to retreive the field.
     * @param fieldName The <code>fieldName</code> 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 < methods.length; i++) {
                if (methods[i].getDeclaringClass().equals(clazz)) {
                    if ((methods[i].getName().startsWith(GETTER) || methods[i].getName().startsWith(BOOLEAN_GETTER)) &amp;&amp; methods[i].getParameterTypes().length == 0) {
                        getters.add(methods[i]);
                    }
                }
            }
        }
        return getters;
    }

    /**
     * Return all getter of a class (even parent'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 < methods.length; i++) {
                    if (methods[i].getDeclaringClass().equals(current)) {
                        if ((methods[i].getName().startsWith(GETTER) || methods[i].getName().startsWith(BOOLEAN_GETTER)) &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 < methods.length; i++) {
                if (methods[i].getDeclaringClass().equals(clazz)) {
                    if (methods[i].getName().startsWith(SETTER) &amp;&amp; methods[i].getName().length() > SETTER.length() &amp;&amp; methods[i].getParameterTypes().length == 1) {
                        getters.add(methods[i]);
                    }
                }
            }
        }
        return getters;
    }

    /**
     * Return all getter of a class (even parent'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 < methods.length; i++) {
                    if (methods[i].getDeclaringClass().equals(current)) {
                        if (methods[i].getName().startsWith(SETTER) &amp;&amp; methods[i].getName().length() > SETTER.length() &amp;&amp; methods[i].getParameterTypes().length == 1) {
                            getters.add(methods[i]);
                        }
                    }
                }
                current = current.getSuperclass();
            }
        }
        return getters;
    }

    /**
     * Retreive the method (<code>methodName</code>) of a class (<code>clazz</code>) using parameters <code>types</code>.
     * @param clazz The <code>clazz</code> on which to retreive the method.
     * @param methodName The method name to retreive.
     * @param types The types of the method'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 <code>accessorType</code> and <code>fieldName</code>.
     * @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; !accessorType.equals(GETTER) &amp;&amp; !accessorType.equals(BOOLEAN_GETTER)) {
            throw new IllegalArgumentException("Accessor Type : " + accessorType + " isn't correct");
        }
        if (null == fieldName || "".equals(fieldName)) {
            throw new IllegalArgumentException("fieldName migth not be null or empty");
        }
        return accessorType + fieldName.replaceFirst("" + fieldName.charAt(0), ("" + 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 ("" + method.getName().charAt(prefix.length())).toLowerCase() + method.getName().substring(prefix.length() + 1);
    }
}

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 !


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("Recharger.wav"));
            System.out.println("format: " + format);

            Mixer.Info[] infos = AudioSystem.getMixerInfo();
            Mixer.Info[] mixerInfo = AudioSystem.getMixerInfo();
            Line.Info lineInfo = null;
            for (int i = 0; i < infos.length; ++i) {
                Mixer mixer = AudioSystem.getMixer(mixerInfo[i]);
                System.out.println("Target lines infos");
                Line.Info[] lineInfos = mixer.getTargetLineInfo(Port.Info.SPEAKER);
                for (int l = 0; l < lineInfos.length; ++l) {
                    System.out.println("Line Info " + l + " - " + 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("Line is not supported");
            }

            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("SPEAKER Line is not supported");
            }

        } catch (Exception ex) {
            //UnsupportedAudioFile... &amp; IO...
            ex.printStackTrace();
        }
    }
}

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("Sound File Player");
        setSize(250, 100);

        // Get the sounds file names from current directory
        currentDir = new File(System.getProperty("user.dir"));
        FilenameFilter filter = new FilenameFilter() {
            public boolean accept(final File directory, final String filename) {
                String name = filename.toLowerCase();
                return name.endsWith(".au") || name.endsWith(".aif") || name.endsWith(".wav");
            }
        };
        String soundFiles[] = currentDir.list(filter);
        if (soundFiles == null || soundFiles.length == 0) {
            JOptionPane.showMessageDialog(this, "No sound files .:. terminating...", "Sound Files Error", 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("PLAY");
        play.addActionListener(new ActionListener() {
            public void actionPerformed(final ActionEvent e) {
                if (e.getActionCommand().equals("PLAY")) {
                    startPlay();
                    play.setText("STOP");
                } else {
                    stopPlay();
                    play.setText("PLAY");
                }
            }
        });
        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("PLAY"); // 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, "Line not supported", "Line NotSupported", JOptionPane.WARNING_MESSAGE);
                soundChoice.setSelectedItem(oldFilename); // Restore the old selection
            }
        } catch (UnsupportedAudioFileException e) {
            JOptionPane.showMessageDialog(null, "File not supported", "Unsupported File Type", JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        } catch (LineUnavailableException e) {
            JOptionPane.showMessageDialog(null, "Line not available", "Line Error", JOptionPane.WARNING_MESSAGE);
            soundChoice.setSelectedItem(oldFilename);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "I/O Error creating stream", "I/O Error", 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, "No line available", "Play Problem", 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'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("PLAY"); // Reset the button text
    }
}

Java , ,

Get classes contained in a package

24/03/2010
Commentaires fermés

En Anglais: This is a java code snipplet that retrieve the package’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 = "/" + pckg.getName().replace('.','/');

    // 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<files.length;++i) {

            // we are only interested in .class files
            if (files[i].endsWith(".class")) {
                // removes the .class extension
                String classname = files[i].substring(0,files[i].length()-6);
                vClasses.add(Class.forName(pckg.getName()+"."+classname));
            }
        }
        Class[] classes = new Class[vClasses.size()];
        for (int i=0; i<vClasses.size();++i) classes[i] = (Class)vClasses.get(i);
        return classes;
    } else {
        throw new IOException("Invalid directory: "+url);
    }
}

Java

Function that get the variables from the URL query

30/11/2009
Commentaires fermés

/**
 * You can call it as 'getFieldFromURL('variableName')'
 * @param The variable's name from the query
 * @return the variable's value
 */
function getFieldFromURL(name) {
	var query = self.location.search;
	if(query.length > 0) {
		name = name+"=";
		var str = query.substring(1);
		var start = str.indexOf(name);
		if(start == -1) return null;
		start += name.length;
		var end = str.indexOf("&amp;", start);
		if(end == -1) end = str.length;
		return unescape(str.substring(start,end));
	} else {
		return null;
	}
}

JavaScript

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.



import java.io.File;
import java.io.IOException;
import java.net.URL;

import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.xml.sax.SAXException;

/**
 * Digester Factory
 * This load a Java object from a XML file using Digester framework
 *
 * @author Gabriel Dromard
 */
public class DigesterFactory {
	/*
	public static Root loadRoot(File input) throws SAXException, Exception {
		// Create the digester instance
		Digester digester = new Digester();

		// Activate or not the DTD checking
		digester.setValidating( false );

		// This is needed because digester is sending errors directly to output without raising exceptions othervise
		//digester.setErrorHandler(new DefaultSAXErrorHandler());
		digester.setErrorHandler(new ErrorHandler() {
			public void error(SAXParseException exception) throws SAXException { throw exception; }
			public void fatalError(SAXParseException exception) throws SAXException { throw exception; }
			public void warning(SAXParseException exception) throws SAXException { throw exception; }
		});

		// Parsing rules
		digester.addObjectCreate( "myxml", Root.class );
		//digester.addSetProperties( "descriptor", "type", "type" );
		//digester.addSetProperties( "myxml/a/b", new String [] {"type", "target", "header"} , new String [] {"outputType", "outputTarget", "header"} );

		digester.addObjectCreate( "myxml/a", A.class );
		digester.addSetProperties( "myxml/a", "name", "name" );
		digester.addSetProperties( "myxml/a/b", "name" , "bname" );
		digester.addSetNext( "myxml/a", "setA");

		digester.addObjectCreate( "myxml/a/c", C.class );
		digester.addSetProperties( "myxml/a/c", new String [] {"name", "value"} , new String [] {"name", "value"} );
		digester.addBeanPropertySetter("myxml/a/c", "description");
		digester.addSetNext( "myxml/a/c", "addC");

		return (Root)digester.parse( input );
	}
*/

	/**
	 * Load an object from a XML file unsing digester framwork
	 * @param input The data input file defining the Java Object
	 * @param rules The rules input file defininf the digester rules for loading this Java Object
	 * @return Return an instance of the a Java Object (defined in rule file)
	 * @throws SAXException Can be thrown while parsing files.
	 * @throws Exception Can be MalformedURLException or IOException for the input or rules files.
	 * @see DigesterFactory#load(File, URL)
	 * @see DigesterFactory#load(URL, URL)
	 */
	public static Object load(File input, File rules) throws SAXException, IOException {
		Digester digester = DigesterLoader.createDigester(rules.toURI().toURL());
		return digester.parse(input);
	}

	/**
	 * Load an object from a XML file unsing digester framwork
	 * @param input The data input URL defining the Java Object
	 * @param rules The rules input URL defining the digester rules for loading this Java Object
	 * @return Return an instance of the a Java Object (defined in rule file)
	 * @throws SAXException Can be thrown while parsing files.
	 * @throws Exception Can be MalformedURLException or IOException for the input or rules files.
	 * @see DigesterFactory#load(File, URL)
	 * @see DigesterFactory#load(File, File)
	 */
	public static Object load(URL input, URL rules) throws SAXException, IOException {
		Digester digester = DigesterLoader.createDigester(rules);
		return digester.parse(input.openStream());
	}

	/**
	 * Load an object from a XML file unsing digester framwork
	 * @param input The data input file defining the Java Object
	 * @param rules The rules input URL defining the digester rules for loading this Java Object
	 * @return Return an instance of the a Java Object (defined in rule file)
	 * @throws SAXException Can be thrown while parsing files.
	 * @throws Exception Can be MalformedURLException or IOException for the input or rules files.
	 * @see DigesterFactory#load(URL, URL)
	 * @see DigesterFactory#load(File, File)
	 */
	public static Object load(File input, URL rules) throws SAXException, IOException {
		Digester digester = DigesterLoader.createDigester(rules);
		return digester.parse(input);
	}

	public static void main(String[] args) {
		if (args.length == 2) {
			try {
				//Root o = loadRoot(new File( "input.xml" ));
				//Object o = load(new File("input.xml"), new File("digester-input-rules.xml"));
				Object o = load(new File(args[0]), new File(args[1]));
				/*Display resulting beans*/
				System.out.println("=================================");
				System.out.println(o.toString());
				System.out.println("=================================");
			} catch( SAXException saxEx) {
				System.err.println("Error in XML parsing: "+saxEx.getMessage());
			} catch( Exception exc ) {
				exc.printStackTrace(System.err);
			}
		} else {
			System.out.println("Usage: java "+DigesterFactory.class.getName()+" [XML input file] [XML rule]");
		}
	}
}

Java , ,

Write and read to a samba shared directory using java (JCIFS)

11/09/2009
Commentaires fermés

This is a little example of a code that write to a file that is on a SMB folder.

Do not forget to add jcifs-1.2.25.jar to your classpath, see http://jcifs.samba.org.


import jcifs.smb.*;
public class SMBClient {
  public static void main(String[] args) {
    try{
      // jcifs.Config.setProperty( "jcifs.netbios.wins", "192.168.1.220" );
      //smb://[[[domain;]username[:password]@]server[:port]/[[share/[dir/]file]][?[param=value[param2=value2[...]]]
      String url="smb://domain;user_name:user_password@server_name/directory/test_file.txt";
      String content="hello !";
      SmbFileOutputStream out = new SmbFileOutputStream(url);
      out.write(content.getBytes());

      System.out.println("File written, now trying to re-read it:");
      SmbFileInputStream in = new SmbFileInputStream(url);
      byte[] b = new byte[10000];
      int n;
      while(( n = in.read( b )) > 0 ) {
        System.out.write( b, 0, n );
      }
    }catch(Exception e){
  System.out.println(e);
  }
 }
}

Java , ,

A Text Wrapper Class

18/05/2009
Commentaires fermés

This is a code snipplet which aim is to wrap text.

There’s two methods, one that wrap text simply, keeping existing wrapped lines into account, and the other that wrap words.

Lire la suite…

Java