Disparition de lecteur/graveur sous windows

Technology / Uncategorized

Salutations,

En installant Windows 10 à la place du 7 sur mon pc portable, j’ai “perdu” mon graveur DVD dans la réinstallation. Ne gravant et l’utilisant pratiquement plus, je m’en suis aperçu que ce weekend.

En cherchant rapidement sur internet, je me suis aperçu que j’étais pas le seul. Et heureusement pour moi, j’ai trouvé une solution: http://fantomfou.free.fr/DisparitionCD.7z
Il s’agit d’un fichier .inf qui s’occupe de réparer le registre. il suffit de faire un clic droit installer, puis de redémarrer l’ordinateur.

D’autres point de vérifications (même si votre ordi n’est pas un HP):
http://support.hp.com/fr-fr/document/c03560375

Aide mémoire : traduction automatique

Aide mémoire (Développement) / Uncategorized
Aide mémoire sur l’utiliation d’une API de traduction automagique…

En se basant sur https://code.google.com/p/java-google-translate-text-to-speech/

Voici un bout de code permettant de traduire un fichier TXT de russe à anglais sans trop de difficulté :

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import com.gtranslate.Language;
import com.gtranslate.Translator;

/** @author pseudo555 */
public class MainTranslator {

    private static final int space = 32;
    private static final int point = 462;
    private static final Translator translate = Translator.getInstance();

    /**
     * Ask only for russian part to be translated. 
     * @param txtOri Original
     * russian line to translate 
     * @return Translated version of the given line
     */
    private static String translate(String txtOri) {
        boolean isEn = true;
        StringBuilder recomposed = new StringBuilder();
        StringBuilder toTranslate = new StringBuilder();
        for (int idx = 0; idx  1000 || ((chPos == space) && !isEn)) {
                isEn = false;
                toTranslate.append(c);
            } else {
                isEn = true;
                if (toTranslate.length() > 0) {
                    recomposed.append(translate.translate(toTranslate.toString(), Language.RUSSIAN, Language.ENGLISH));
                }
                //uncomment if " must be escaped 				
                //if(c == '"' && ! isFile) recomposed.append("\\"); 				
                recomposed.append(c);
                toTranslate = new StringBuilder();
            }
        }
        if (toTranslate.length() > 0) {
            recomposed.append(translate.translate(toTranslate.toString(), Language.RUSSIAN, Language.ENGLISH));
        }
        return recomposed.toString();
    }

    public static void main(String[] args) throws IOException {
        String path = "C:\\mon fichier.txt";
        for (String txtOri : Files.readAllLines(new File(path).toPath(), Charset.forName("UTF-8"))) {
            System.out.println(translate(txtOri));
        }
    }
}

Aide mémoire : Détections de flags…

Aide mémoire (Développement) / Uncategorized

Aide mémoire pour détecter la présence d’un flag dans un entier…
1. Introduction
2. Algèbre booléenne et Opérateurs
3. Méthodes utiles

1. Introduction

Il arrive parfois d’utiliser un entier à la place d’un tableau de byte, pour des raisons particulières que j’aborderais pas ici.

Exemple :

Flag Valeur
A 1
B 2
C 4
D 8

On notera que les valeurs sont des puissances de 2.

Si ma variable i (de type int) contient les flags, A et C, alors i = A + C <=> 1 + 4 <=> 5.
Pour paramétrer la valeur la première fois, rien de bien compliqué, il suffit d’ajouter les entiers.

Pour ajouter un flag sur un entier existant, c’est un poil plus compliqué :
Si i vaut déjà 5, et qu’on veut etre sur que le flag C soit présent, on ne peut pas simplement additionner la valeur de C à i:
i = 5 -> i = i + C -> i =5 + 4 -> i = 9 <=> i = A + D
Il faut donc vérifier que le flag ne soit pas présent avant… ou utiliser une autre méthode : l’algèbre booléene.

2. Algèbre booléenne et Opérateurs

Mon but ici n’est pas de faire un cours complet, juste un résumé de base sur l’algèbre booléenne :

A B NON A NON B A ET B A OU B
0 0 1 1 0 0
0 1 1 0 0 1
1 0 0 1 0 1
1 1 0 0 1 1

L’opérateur NON peut être écrit de de manière en Java: soit avec ! (dans le cas d’un booléen) soit avec ~. L’opérateur ~ inverse les bits d’un nombre, donc 8 (décimal) qui s’écrit 1000 en binaire (mémoire) et deviendrait 1…10111 (toujours en binaire et en mémoire) en passant par l’opérateur ~.

L’opérateur ET peut être écrit de de manière en Java: soit avec && (toujours pour un booléen) soit avec &. Dans ce cas, pour chaque bit de même poids en mémoire, l’opération A ET B de la table précédente est effectuée:

12 & 4 <=> 1100 & 100 <=> 0100 <=> 4

8 & 8 <=> 1000 & 1000 <=> 1000 <=> 8

L’opérateur OU peut être écrit de de manière en Java: soit avec || (toujours pour un booléen) soit avec |. Dans ce cas, pour chaque bit de même poids en mémoire, l’opération A OU B de la table précédente est effectuée:

12 | 4 <=> 1100 | 100 <=> 1100 <=> 12

8 | 4 <=> 1000 | 100 <=> 1100 <=> 12

3. Méthodes utiles

    /**
     * Check if the given mask is used in value.
     * @param value - value to check
     * @param mask - mask to used
     * @return boolean
     */
    public static boolean isMatch(final int value, final int mask) {
        return (value & mask) != 0;
    }

    /**
     * Check if the value use only the mask ones.
     * @param value - value to check
     * @param mask - mask to used
     * @return boolean
     */
    public static boolean isMatchOnly(final int value, final int mask) {
        return ((value & mask) != 0) && (value & ~mask) == 0;
    }

    /**
     * Add or remove mask to value.
     * @param value - old value
     * @param mask - mask to add or remove
     * @param isAddition - true to add, false to remove
     * @return new value
     */
    public static int setValue(final int value, final int mask, final boolean isAddition) {
        if (isAddition) {
            return value | mask;
        }
        return value & ~mask;
    }

Aide mémoire : Détection de l’OS

Aide mémoire (Développement) / Uncategorized
Aide mémoire pour détecter l’OS sur lequel votre programme java tourne…

/**
 * Use System.getProperty("os.name") to detect which type of operating  system (OS) you are using now.
 * This code can detect Windows, Mac, Unix and Solaris. 
 * @see http://www.mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname/
 * @author http://www.mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname/
 */
public final class OsValidator {

    /**
     * Operating System (OS) you are using now.
     */
    public static String OS = System.getProperty("os.name").toLowerCase();

    private OsValidator() {
    }

    /**
     * @return true if current os is Windows based.
     */
    public static boolean isWindows() {
        return (OS.indexOf("win") >= 0);
    }

    /**
     * @return true if current os is Mac based
     */
    public static boolean isMac() {
        return (OS.indexOf("mac") >= 0);
    }

    /**
     * @return true if current os is Unix based
     */
    public static boolean isUnix() {
        return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0);
    }

    /**
     * @return true if current os is Solaris based
     */
    public static boolean isSolaris() {
        return (OS.indexOf("sunos") >= 0);
    }
}

Aide mémoire : JNA, moniteur et screen saver

Aide mémoire (Développement) / Uncategorized

Petit aide mémoire sur l’utilisation de JNA.
1. Interface Kernel32
2. Interface User32
3. Utilisation

Avant toute chose, il faut que le projet référence les librairies JNA et plateform : https://github.com/twall/jna

1. Interface Kernel32

import com.sun.jna.Native ;
import com.sun.jna.win32.StdCallLibrary ;

/**
 * Interface for kernel32 using JNA. 
 * Minimum supported client: Windows 2000 Professional [desktop apps only] 
 * Minimum supported server: Windows 2000 Server [desktop apps only] 
 * Header: Winbase.h (include Windows.h) 
 * @author Microsoft
 */
public interface Kernel32 extends StdCallLibrary {

    /**
     * Instance of Kernel32 mapped with Native library kernel32.
     */
    Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);

    /**
     * Retrieves the number of milliseconds that have elapsed since the system was started. 
     * @see http://msdn2.microsoft.com/en-us/library/ms724408.aspx 
     * @return number of milliseconds that have elapsed since the system was started.
     */
    int GetTickCount();
}

2. Interface User32

import com.sun.jna.Native ;
import com.sun.jna.platform.win32.WinDef.HWND ;
import com.sun.jna.platform.win32.WinDef.LPARAM ;
import com.sun.jna.platform.win32.WinDef.LRESULT ;
import com.sun.jna.platform.win32.WinDef.WPARAM ;
import com.sun.jna.platform.win32.WinUser.LASTINPUTINFO ;
import com.sun.jna.ptr.PointerByReference ;
import com.sun.jna.win32.StdCallLibrary ;

/**
 * Interface for user32 using JNA. 
 * Minimum supported client: Windows 2000 Professional [desktop apps only] 
 * Minimum supported server: Windows 2000 Server [desktop apps only] 
 * Header: Winbase.h (include Windows.h)
 *
 *
 * * @author Microsoft
 */
public interface User32 extends StdCallLibrary {

    /**
     * Instance of Kernel32 mapped with Native library user32.
     */
    User32 INSTANCE = (User32) Native.loadLibrary("user32", User32.class);


    // Constants definition ---------------------------------------------------
    /*       
     * From WM_SYSCOMMAND message.      
     * @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms646360(v=vs.85).aspx      
     */ 

    /**
     * Sets the state of the display. 
     * This command supports devices that have power-saving features, 
     * such as a battery-powered personal computer. 
     * The lParam parameter can have the following values: 
     * -1 (the display is powering on) 
     * 1 (the display is going to low power)
     * 2 (the display is being shut off)
     */
    int SC_MONITORPOWER = 0xF170;
    /**
     * the display is powering on value of SC_MONITORPOWER.
     */
    int SC_MONITOR_ON = -1;
    /**
     * the display is being shut off value of SC_MONITORPOWER.
     */
    int SC_MONITOR_OFF = 2;
    /**
     * Executes the screen saver application specified in the [boot] section
     * of the System.ini file.
     */
    int SC_SCREENSAVE = 0xF140;
    /**
     * Determines whether a screen saver is currently running on the window
     * station of the calling process.
     */
    int SPI_GETSCREENSAVERRUNNING = 0x0072;

    // Methods definition ------------------------------------------------------          
    /**
     * Retrieves the time of the last input event. 
     * @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms646302(v=vs.85).aspx
     * @param result [out]: a LASTINPUTINFO structure that receives the time of the last input event. 
     * @return If the function succeeds, the return value is nonzero else the return value is zero.
     */
    boolean GetLastInputInfo(LASTINPUTINFO result);

    /**
     * Retrieves a handle to the foreground window (the window with which the user is currently working). The system assigns a slightly higher priority to the thread that creates the foreground window than it does to other threads. 
     * @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms633505(v=vs.85).aspx
     * @return handle to the foreground window. The foreground window can be NULL in certain circumstances, such as when a window is losing activation.
     */
    HWND GetForegroundWindow();

    /**
     * Sends the specified message to a window or windows (ANSI version).
     * @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms644950(v=vs.85).aspx
     * @param paramHWND [in] A handle to the window whose window procedure will receive the message. If this parameter is HWND_BROADCAST ((HWND)0xffff), the message is sent to all top-level windows in the system, including disabled or invisible unowned windows, overlapped windows, and pop-up windows; but the message is not sent to child windows. 
     * Message sending is subject to UIPI. The thread of a process can send messages only to message queues of threads in processes of lesser or equal integrity level. 
     * @param paramInt [in] The message to be sent. 
     * @param paramWPARAM [in] Additional message-specific information. 
     * @param paramLPARAM [in] Additional message-specific information. 
     * @return LRESULT - The return value specifies the result of the message processing; it depends on the message sent.
     */
    LRESULT SendMessageA(HWND paramHWND, int paramInt, WPARAM paramWPARAM, LPARAM paramLPARAM);

    /**
     * Retrieves or sets the value of one of the system-wide parameters.
     * This function can also update the user profile while setting a parameter. 
     * @see http://msdn.microsoft.com/en-us/library/windows/desktop/ms724947(v=vs.85).aspx
     * @param uiAction UINT - The system-wide parameter to be retrieved or set 
     * @param uiParam UINT - A parameter whose usage and format depends on the system parameter being queried or set 
     * @param pvParam PVOID - A parameter whose usage and format depends on the system parameter being queried or set 
     * @param fWInIni UINT - If a system parameter is being set, specifies whether the user profile is to be updated, and if so, whether the WM_SETTINGCHANGE message is to be broadcast to all top-level windows to notify them of the change
     * @return If the function succeeds, the return value is a nonzero value, else the return value is zero
     */
    boolean SystemParametersInfoA(int uiAction, int uiParam, PointerByReference pvParam, int fWInIni);
}

3. Utilisation

import com.sun.jna.platform.win32.WinDef ;
    import com.sun.jna.platform.win32.WinUser ;
    import com.sun.jna.platform.win32.WinUser.LASTINPUTINFO ;
    import com.sun.jna.ptr.PointerByReference ;

    /**
     * Get the amount of milliseconds that have elapsed since the last input event (mouse or keyboard) 
     * @return idle time in milliseconds
     */
    public static int getIdleTimeMillisWin32() {
        LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
        User32.INSTANCE.GetLastInputInfo(lastInputInfo);
        return Kernel32.INSTANCE.GetTickCount() - lastInputInfo.dwTime;
    }

    /**
     * @return true if the screensaver is displayed
     */
    public static boolean isScreenSaverDisplayed() {
        PointerByReference pointer = new PointerByReference();
        User32.INSTANCE.SystemParametersInfoA(User32.SPI_GETSCREENSAVERRUNNING, 0, pointer, 0);
        // pointer points to a BOOL variable that receives TRUE if a screen saver is currently running, or FALSE otherwise 
        return pointer.getPointer().getByte(0) == 1; 
    }

    /**
     * Force scrensaver to go away.
     */
    public static void forceScreenSaverExit() {
        User32.INSTANCE.SendMessageA(User32.INSTANCE.GetForegroundWindow(), WinUser.WM_CLOSE, new WinDef.WPARAM(0), new WinDef.LPARAM(0));
    }

    /**
     * Force scrensaver display.
     */
    public static void forceScreenSaverDisplay() {
        final WinDef.HWND lHwnd = User32.INSTANCE.GetForegroundWindow();
        User32.INSTANCE.SendMessageA(lHwnd, WinUser.WM_SYSCOMMAND, new WinDef.WPARAM(User32.SC_SCREENSAVE), new WinDef.LPARAM(0));
    }

Aide mémoire : JXTable

Aide mémoire (Développement) / Uncategorized
Petit aide mémoire sur l’utilisation d’une JXTable et de certains choses faisables avec…

1. Le modèle et ses données
2. Le panel
3. Les filtres

Avant toute chose, il faut que le projet référence la librairie swingx.

1. Le Modèle et ses données

Les données du modèle :

/**
 * Item value. 
 * @author pseudo555
 */
public class Item {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Le modèle :

import java.util.ArrayList ;
import java.util.List ;
import javax.swing.table.AbstractTableModel ;

/**
 * Model for the JXTable * @author pseudo555
 */
public class Model extends AbstractTableModel {

    private static final long serialVersionUID = 1L;
    // cache values 	
    public List items = new ArrayList();
    // Array containing column name 	
    private final String[] columnsName = new String[1];
    // Index of each column 	
    public static final int I_NAME = 0;

    public Model() {
        // fill columnsName 		
        this.columnsName[I_NAME] = "Name";
    }

    @Override
    public String getColumnName(final int index) {
        return this.columnsName[index];
    }

    @Override
    public int getColumnCount() {
        return this.columnsName.length;
    }

    /**
     * Retrieve a specific row from model data 
     * @param rowIndex index of the row to retrieve * @return Item
     */
    public Item getItem(final int rowIndex) {
        try {
            return items.get(rowIndex);
        } catch (final ArrayIndexOutOfBoundsException e) {
            return null;
        }
    }

    @Override
    public Object getValueAt(final int rowIndex, final int columnIndex) {
        final Item item = this.getItem(rowIndex);
        if (item == null) {
            return null;
        }
        // according to the column, retrieve the required value	 		
        switch (columnIndex) {
            case I_NAME:
                return item.getName();
            default:
                return "";
        }
    }

    @Override
    public Class getColumnClass(final int columnIndex) {
        // Pour chaque colonne, on définit l'objet utilisé.  		
        // On appliquera un renderer spécial dessus si nécessaire. 		
        switch (columnIndex) {
            case I_NAME:
            default:
                return String.class;
        }
    }

    @Override
    public boolean isCellEditable(final int rowIndex, final int columnIndex) {
        // Définition des colonnes éditables 		
        switch (columnIndex) {
            case I_NAME:
                return true;
            default:
                return false;
        }
    }

    @Override
    public void setValueAt(final Object value, final int rowIndex, final int columnIndex) {
        // only if isCellEditable return true 		
        switch (columnIndex) {
            case I_NAME:
                if (value instanceof String) {
                    items.get(rowIndex).setName((String) value);
                }
                break;
            default:
                break;
        }
    }

    @Override
    public int getRowCount() {
        return items.size();
    }

    /**
     * Add new emty item in model.
     */
    public void addNewItem() {
        items.add(new Item());
        fireTableDataChanged();
    }
}

2. Le panel

import java.awt.BorderLayout ;
import java.awt.GridBagConstraints ;
import java.awt.GridBagLayout ;
import java.awt.Insets ;
import java.awt.event.ActionEvent ;
import java.awt.event.ActionListener ;
import javax.swing.JButton ;
import javax.swing.JLabel ;
import javax.swing.JPanel ;
import javax.swing.JScrollPane ;
import javax.swing.JTextField ;
import javax.swing.RowSorter ;
import javax.swing.event.DocumentEvent ;
import javax.swing.event.DocumentListener ;
import javax.swing.table.TableModel ;
import org.jdesktop.swingx.JXTable ;
import org.jdesktop.swingx.sort.TableSortController ;

/**
 * Main panel, which is composed by a search panel and a filtered table.
 * @author pseudo555
 */
public class Panel extends JPanel {

    private static final long serialVersionUID = 2456293673128172821L;
    // searchPanel definition 	
    private final JPanel searchPanel;
    private final JTextField textField;
    // tablePanel definition 	
    private final JPanel tablePanel;
    private final JXTable table;
    private final Model model;

    /**
     * Create the panel.
     */
    public Panel() {
        model = new Model();
        /* layout management */ {
            GridBagLayout gridBagLayout = new GridBagLayout();
            gridBagLayout.columnWidths = new int[]{0};
            gridBagLayout.rowHeights = new int[]{40, 0};
            gridBagLayout.columnWeights = new double[]{Double.MIN_VALUE};
            gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
            setLayout(gridBagLayout);
        }
        /* add search panel */ {
            //init required component 			
            textField = new JTextField();
            // get panel 			
            searchPanel = getSearchPanel();
            //set layout constraint 			
            GridBagConstraints gbc_panel_1 = new GridBagConstraints();
            gbc_panel_1.insets = new Insets(0, 0, 5, 0);
            gbc_panel_1.fill = GridBagConstraints.BOTH;
            gbc_panel_1.gridx = 0;
            gbc_panel_1.gridy = 0;
            add(searchPanel, gbc_panel_1);
        }
        /* add table panel */ {
            //init required component 			
            table = new JXTable();
            // get panel 			
            tablePanel = getTablePanel();
            //set layout constraint 		
            GridBagConstraints gbc_panel = new GridBagConstraints();
            gbc_panel.fill = GridBagConstraints.BOTH;
            gbc_panel.gridx = 0;
            gbc_panel.gridy = 1;
            add(tablePanel, gbc_panel);
        }
    }

    /**
     * * @return Table panel.
     */
    private JPanel getTablePanel() {
        JPanel tablePanel = new JPanel();
        // layout 		
        tablePanel.setLayout(new BorderLayout());
        //content 		
        JScrollPane scrollPane = new JScrollPane();
        tablePanel.add(scrollPane, BorderLayout.CENTER);
        table.setModel(model);
        scrollPane.setViewportView(table);
        return tablePanel;
    }

    /**
     * * @return Search panel.
     */
    private JPanel getSearchPanel() {
        JPanel search = new JPanel();
        /* search panel Layout */
        {
            GridBagLayout gridBagLayout = new GridBagLayout();
            gridBagLayout.columnWidths = new int[]{50, 250, 30, 20};
            gridBagLayout.rowHeights = new int[]{20};
            gridBagLayout.columnWeights = new double[]{0.0, Double.MIN_VALUE, 0.0, 0.0};
            gridBagLayout.rowWeights = new double[]{1.0};
            search.setLayout(gridBagLayout);
        }
        /* First a search label */ {
            JLabel lblNewLabel = new JLabel("Search:");
            //set layout constraint 			
            GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
            gbc_lblNewLabel.insets = new Insets(5, 5, 5, 5);
            gbc_lblNewLabel.anchor = GridBagConstraints.EAST;
            gbc_lblNewLabel.gridx = 0;
            gbc_lblNewLabel.gridy = 0;
            search.add(lblNewLabel, gbc_lblNewLabel);
        }
        /* Then a textfield to manage user input */ {
            //set layout constraint 			
            GridBagConstraints gbc_textField = new GridBagConstraints();
            gbc_textField.insets = new Insets(5, 5, 5, 5);
            gbc_textField.fill = GridBagConstraints.BOTH;
            gbc_textField.gridx = 1;
            gbc_textField.gridy = 0;
            search.add(textField, gbc_textField);
            // set automatic filtering on user typing 			
            textField.getDocument().addDocumentListener(new DocumentListener() {
                @Override
                public void removeUpdate(DocumentEvent e) {
                    filter();
                }

                @Override
                public void insertUpdate(DocumentEvent e) {
                    filter();
                }

                @Override
                public void changedUpdate(DocumentEvent e) {
                    filter();
                }
            });
        }
        /* A button which will be used to launch the search */ {
            JButton btnFilter = new JButton("Filter");
            //set layout constraint 			
            GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
            gbc_btnNewButton.insets = new Insets(5, 5, 5, 5);
            gbc_btnNewButton.gridx = 2;
            gbc_btnNewButton.gridy = 0;
            search.add(btnFilter, gbc_btnNewButton);
            // add action on click 			
            btnFilter.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    filter();
                }
            });
        }
        /* A button to add data in the table */ {
            JButton btnNew = new JButton("+");
            //set layout constraint 			
            GridBagConstraints gbc_btnNewButton_1 = new GridBagConstraints();
            gbc_btnNewButton_1.insets = new Insets(5, 5, 5, 5);
            gbc_btnNewButton_1.gridx = 3;
            gbc_btnNewButton_1.gridy = 0;
            search.add(btnNew, gbc_btnNewButton_1);
            // add action on click 			
            btnNew.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    model.addNewItem();
                }
            });
        }
        return search;
    }

    /**
     * * Filter table according to textField.getText().
     */
    private void filter() {
        RowSorter s = table.getRowSorter();
        if (s instanceof TableSortController) {
            @SuppressWarnings("unchecked")
            final TableSortController sorter = (TableSortController) s;
            sorter.setRowFilter(new TextCaseInsensitiveFilter(textField.getText(), Model.I_NAME));
            table.setRowSorter(sorter);
        }
    }
}

3. Les filtres

La classe TextCaseInsensitiveFilter est une classe permettant de filter les données de la table. Voici quelques exemples :

BooleanFilter :

import javax.swing.RowFilter ;

/**
 * Boolean filter for table.
 */
public class BooleanFilter extends RowFilter {

    private final int index;
    private final boolean state;

    /**
     * Constructor. 
     * @param state Boolean state of item to display
     * @param columns Index of column to check
     */
    public BooleanFilter(final boolean state, final int columns) {
        index = columns;
        this.state = state;
    }

    @Override
    public boolean include(final Entry value) {
        final Object tr = value.getValue(index);
        if (!(tr instanceof Boolean)) {
            return false;
        }
        return state == (Boolean) tr;
    }
}

IgnoreCaseFilter:

import javax.swing.RowFilter ;

/**
 * Unsensitive text filter for table.
 */
public class IgnoreCaseFilter extends RowFilter {

    private final String matcher;
    private final int index;
    private final boolean state;

    /**
     * Constructor. 
     * @param lookFor String to look for 
     * @param state state of item to display 
     * @param columns Index of column to check
     */
    public IgnoreCaseFilter(final String lookFor, final int columns, final boolean state) {
        if (lookFor == null) {
            throw new IllegalArgumentException("LookFor must be non-null");
        }
        matcher = FilterToolkit.unaccent(lookFor.toUpperCase());
        index = columns;
        this.state = state;
    }

    @Override
    public boolean include(final Entry value) {
        final String text = FilterToolkit.unaccent(value.getStringValue(index).toUpperCase());
        final boolean result = -1 == text.indexOf(matcher);
        if (state) {
            return result;
        }
        return !result;
    }
}

RegexFilter:

/**
 * RegexFilter for table.
 */
public class RegexFilter extends RowFilter {

    private final Pattern pattern;
    private final int index;

    /**
     * Constructor. 
     * @param lookFor String to look for 
     * @param commentRegexChar Escape regex char 
     * @param columns Index of column to check
     */
    public RegexFilter(final String lookFor, final int columns, final boolean commentRegexChar) {
        if (lookFor == null) {
            throw new IllegalArgumentException("LookFor must be non-null");
        }
        pattern = Pattern.compile(commentRegexChar ? fixPatern(lookFor) : lookFor.replace("*", ".*"));
        index = columns;
    }

    @Override
    public boolean include(final Entry value) {
        final String text = FilterToolkit.unaccent(value.getStringValue(index).toUpperCase());
        return pattern.matcher(text).find();
    }

    /**
     * Comment all char that are used in regex, but not in our case.
     * @param lookFor pattern to fix 
     * @return fixed pattern
     */
    private String fixPatern(final String lookFor) {
        return FilterToolkit.escapeRegex(FilterToolkit.unaccent(lookFor.toUpperCase()));
    }
}

MinMaxFilter :

import javax.swing.RowFilter ;

/**
 * Filter on number using range.
 */
public class MinMaxFilter extends RowFilter {

    private final int index;
    private final int start;
    private final int stop;

    /**
     * Constructor. 
     * @param start Min value allowed 
     * @param stop Max value allowed 
     * @param columns Index of column to check
     */
    public MinMaxFilter(final int start, final int stop, final int columns) {
        index = columns;
        this.start = start;
        this.stop = stop;
    }

    @Override
    public boolean include(final Entry value) {
        final Object tr = value.getValue(index);
        if (tr instanceof Integer) {
            final int val = ((Integer) tr).intValue();
            return start <= val && val = stop;
        }
        return false;
    }
}

FilterToolkit :

import java.text.Normalizer ;

/**
 * Toolkit for Filter class.
 */
public final class FilterToolkit {

    /**
     * Private constructor.
     */
    private FilterToolkit() {
    }

    /**
     * Remove all accents from the given string. 
     * @param text String to unaccent 
     * @return fixed input
     */
    public static String unaccent(final String text) {
        final String normalized = Normalizer.normalize(text, Normalizer.Form.NFD);
        return normalized.replaceAll("[^\p{ASCII}]", "");
    }

    /**
     * * Escape Regex special characters from a String. * @param text
     * String to escape * @return fixed input
     */
    public static String escapeRegex(final String text) {
        final StringBuffer sb = new StringBuffer();
        final int n = text.length();
        for (int i = 0; i < n; i++) {
            final char c = text.charAt(i);
            switch (c) {
                case '(':
                    sb.append("\\(");
                    break;
                case ')':
                    sb.append("\\)");
                    break;
                case '[':
                    sb.append("\\[");
                    break;
                case ']':
                    sb.append("\\]");
                    break;
                case '^':
                    sb.append("\\^");
                    break;
                case '$':
                    sb.append("\\$");
                    break;
                case '+':
                    sb.append("\\+");
                    break;
                case '*':
                    sb.append(".*");
                    break;
                case '.':
                    sb.append("\\.");
                    break;
                case '?':
                    sb.append("\\?");
                    break;
                case '\\': 
                    sb.append("\\\\");
                    break;
                case '|':
                    sb.append("\\|");
                    break;
                case '{':
                    sb.append("\\{");
                    break;
                case '}':
                    sb.append("\\}");
                    break;
                default:
                    sb.append(c);
                    break;
            }
        }
        return sb.toString();
    }
}

Aide mémoire : Exploration de dossier

Aide mémoire (Développement) / Uncategorized
Petit aide mémoire pour explorer le contenu d’un dossier de manière récursive.

1. Java 6
2. Java 7
3. Sources

1. Java 6

    public void run() {
        File f = new File(fileOrFolderPath);
        if (f.isDirectory()) {
            parseFolder(f);
        } else {
            parseFile(f);
        }
    }

    /**
     * Recursively parse given folder.
     */
    protected void parseFolder(File directory) {
        doAtStartOfEachFolder(directory);
        for (File file : directory.listFiles()) {
            if (file.isDirectory()) {
                parseFolder(file);
            } else {
                parseFile(file);
            }
        }
        doAtEndOfEachFolder(directory);
    }

    /**
     * Read given file, line by line.
     */
    protected void parseFile(File file) {
        FileReader fr = null;
        BufferedReader br = null;
        try {
            doAtStartOfEachFile(file);
            String line;
            fr = new FileReader(file);
            br = new BufferedReader(fr);
            while ((line = br.readLine()) != null) {
                parseLigne(line);
                // because it will be too fast 				
                Thread.sleep(timeout);
            }
        } catch (Exception e) {
            LOGGER.error("Parsing File failed : " + e.getMessage());
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (Exception ex) {
                LOGGER.error("Can't close bufferReader: " + ex.getMessage());
            }
            doAtEndOfEachFile(file);
        }
    }

    /**
     * Send given line to consumer. Override it if you need to do specific modification before sending it to consumer.
     */
    protected void parseLigne(String line) {
        this.getConsumer().consume(line);
    }

    /**
     * Specific code to do before reading a file.
     */
    protected void doAtStartOfEachFile(File file) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Read file: " + file.getName());
        }
    }

    /**
     * Specific code to do when file as no more line to read.
     */
    protected void doAtEndOfEachFile(File file) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("end of file: " + file.getName());
        }
    }

    /**
     * Specific code to do before reading through a folder.
     */
    protected void doAtStartOfEachFolder(File folder) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Read through folder: " + folder.getName());
        }
    }

    /**
     * Specific code to do when all files/sub-folder are read.
     */
    protected void doAtEndOfEachFolder(File folder) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("No more file to read in folder: " + folder.getName());
        }
    }

2. Java 7

    public static void main(String[] args) {
        for (String s : fileList("D:\\___DL\\_new\\bd\\")) {
            System.out.println(s);
        }
    }

    public static List fileList(String directory) {
        List fileNames = new ArrayList();
        try (DirectoryStream directoryStream = Files.newDirectoryStream(Paths.get(directory))) {
            for (Path path : directoryStream) {
                File f = path.toFile();
                if (f.isDirectory()) {
                    fileNames.addAll(fileList(f.getAbsolutePath()));
                } else {
                    fileNames.add(path.toString());
                }
            }
        } catch (IOException ex) {
        }
        return fileNames;
    }

3. Sources
http://www.adam-bien.com/roller/abien/entry/listing_directory_contents_with_jdk
http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403

Aide mémoire : JMX de base

Aide mémoire (Développement) / Uncategorized
Petit aide mémoire pour utiliser un MBean avec une connexion JMX

1. Interface MBean
2. L’implémentation MBean
3. Lanceurs
4. Sources

1. Interface MBean

public interface BaseMBean {

    String OBJECT_NAME = "com.opera.my.jmx:type=BaseMBean";

    int getValeur();

    void setValeur(int valeur);
}

2. L’implémentation MBean

public class Base implements BaseMBean {

    int valeur = 0;

    @Override
    public int getValeur() {
        return valeur;
    }

    @Override
    public synchronized void setValeur(int val) {
        this.valeur = val;
    }
}

3. Lanceurs
Serveur :

    public static void main(String[] args) {
        try {
            MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
            ObjectName name = new ObjectName(BaseMBean.OBJECT_NAME);
            BaseMBean mbean = new Base();
            // enregistrement 		
            mbs.registerMBean(mbean, name);
            System.out.println("Lancement ...");
            while (true) {
                Thread.sleep(1000);
                mbean.setValeur(mbean.getValeur() + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

/!\ il faut ajouter les options suivantes à la VM :

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=12345 
-Dcom.sun.management.jmxremote.authenticate=false 
-Dcom.sun.management.jmxremote.ssl=false

Client :

    public static final String HOST = "127.0.0.1";
    public static final String PORT = "12345";

    public static void main(String[] args) throws IOException, MalformedObjectNameException {
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + HOST + ":" + PORT + "/jmxrmi");
        JMXConnector jmxConnector = JMXConnectorFactory.connect(url);
        MBeanServerConnection mbeanServerConnection = jmxConnector.getMBeanServerConnection();
        ObjectName mbeanName = new ObjectName(BaseMBean.OBJECT_NAME);
        //Get MBean proxy instance that will be used to make calls to registered MBean 	
        BaseMBean mbeanProxy = (BaseMBean) MBeanServerInvocationHandler.newProxyInstance(mbeanServerConnection, mbeanName, BaseMBean.class, true);
        //let's make some calls to mbean through proxy and see the results. 	
        System.out.println("ancienne valeur :" + mbeanProxy.getValeur());
        mbeanProxy.setValeur(5);
        System.out.println("nouvelle valeur :" + mbeanProxy.getValeur());
        //close the connection 	
        jmxConnector.close();
    }

4. Sources
http://www.jmdoudoux.fr/java/dej/chap-jmx.htm
http://www.journaldev.com/1359/java-jmx-client-example-and-jmx-authentication-with-config-files-for-role-based-access

Aide mémoire : pattern producteur/consommateur en java

Aide mémoire (Développement) / Uncategorized
Petit aide mémoire pour l’implémentation du pattern producteur/consommateur en java.

1. Le producteur
2. Le consommateur
3. Exemple de lanceur
4. Source & notes

1. Le producteur

import java.util.concurrent.BlockingQueue ;

public class Producteur implements Runnable {

    private final BlockingQueue sharedQueue;

    public Producteur(BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        // la génération d'objet de type T 		
        sharedQueue.put(object);
    }
}

2. Le consommateur

import java.util.concurrent.BlockingQueue ;

public class Consommateur implements Runnable {

    private final BlockingQueue sharedQueue;

    public Consommateur(BlockingQueue sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    @Override
    public void run() {
        while (true) {
            try {
                T object = sharedQueue.take();
                // l'utilisation de l'object reste a coder 			
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

3. Exemple de lanceur

    public static void main(String args[]) {
        //Creating shared object 	
        BlockingQueue sharedQueue = new LinkedBlockingQueue();
        //Creating Producer and Consumer Thread 	
        Thread prodThread = new Thread(new Producteur(sharedQueue));
        Thread consThread = new Thread(new Consommateur(sharedQueue));  	
        //Starting producer and Consumer thread 	
        prodThread.start(); 	
        consThread.start(); }
    }

4. Source & notes
Dans certains cas, le lanceur et le producteur sont fusionnés.
Dans ce cas :

  • Le constructeur du producteur créée l’instance du consommateur, lui donne la sharedQueue en paramètre, et finit par appeler la méthode start() du consommateur.
  • Le producteur n’implémente pas runnable, mais dispose quand même d’une fonction permettant d’ajouter des éléments à la sharedQueue .
  • Le consommateur dispose en général d’une méthode d’arrêt, appelé par le lanceur.

Source :
http://javarevisited.blogspot.fr/2012/02/producer-consumer-design-pattern-with.html

Pour en savoir plus :
http://blog.paumard.org/cours/java-api/chap05-concurrent-queues.html