Monday, October 13, 2014

Old Java Swing style fadeIn / fadeOut on image

As my open source project (Violet UML Editor) has a GUI developed in Swing (wich is not a problem because I massively use the Graphics2D canvas which should be portable to other tehnologies), I sometimes have to find tricks to enhance UX. That was my last challenge. I decided to implement fade effects on image. After googlings, I didn't find anything ready to use. So, I developed a quick and simple piece of code I share with you. The idea is to embed my image as an ImageIcon attached to a JLabel. Then, to trigger fade effects, I just use a mouse listener.

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.Timer;

public class FadeImage extends JLabel implements ActionListener {

    // Up to 1f
    private float opacity = 0f;
    private Timer fadeTimer;
    private int fadeIndicator = 1;

    public FadeImage(ImageIcon anImage) {

    private void initializeTimer() {
fadeTimer = new javax.swing.Timer(75, this);

    public void fadeIn() {
fadeIndicator = 1;

    public void fadeOut() {
fadeIndicator = -1;

    public void actionPerformed(ActionEvent e) {
opacity = opacity + (fadeIndicator * 0.1f);
if (opacity > 1) {
   opacity = 1;
if (opacity < 0) {
   opacity = 0;

    public void paint(Graphics g) {
((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));


Here is an example of the mouse listener :

                       final FadeImage fadeImage = new FadeImage(this.rightPanelIcon);
            getLeftTitlePanel().addMouseListener(new MouseListener() {
       public void mouseReleased(MouseEvent e) {
    // TODO Auto-generated method stub
       public void mousePressed(MouseEvent e) {
    // TODO Auto-generated method stub
       public void mouseExited(MouseEvent e) {
       public void mouseEntered(MouseEvent e) {
       public void mouseClicked(MouseEvent e) {
    // TODO Auto-generated method stub

Quite simple and easy!

Friday, October 03, 2014

Wednesday, August 06, 2014

DCcduino usb drivers (CH340 / CH341 chipset)

I've just received my first arduino platform. It's a DCcduino board (a clone of Arduino Uno). As I had some difficulties to have it recognised by my MacBook, I decided to share its drivers. This card has a CH340 USB-to-serial chip. You can find drivers for this chip on the web site of the chinese manufacturer, here :

Or download it directly from my Google Drive. The archive contains drivers for Mac, Linux and Windows platforms.

I hope this will help somebody.

UPDATE for Mac users with Yosemite :

Please, follow this extra instructions :
  1. Install the CH340 driver
  2. Run the command in Terminal: sudo nvram boot-args="kext-dev-mode=1"
  3. Reboot

Friday, June 13, 2014

Find Oracle apparent deallocks

Your application is blocked? Perhaps it is due to deadlock on database objects. So, if you have an Oracke DB Server, you can verify this with these few requests I found on the web :

  • List blocked sessions  :  select sid, serial#, username, command, lockwait, osuser from v$session where lockwait is not null
  • Find SQL requests concerned : select sql_text from v$sqltext where (address,hash_value) in (select sql_address,sql_hash_value from v$session where lockwait is not null) order by address, hash_value, piece
  • Kill concerned session (you need to have dba priviledges) : alter system kill session 'sid, serial#';

Tuesday, April 08, 2014

How to synchronized two folders with a Python script

That's what I wanted to do. So, I wrote my first Python (3) script. Don't hesitate to use or modified this code. It can synchronized two folders in two-way directions. It never deletes files or folders in its strategy. It only replicates older or missing files and folders from the two folders to synchronized.


PS : Be cool with me, this is my first steps with Python

__author__ = 'Alexandre de Pellegrin'
import os
import shutil

srcDir = '/home/user/folder1'
dstDir = '/home/user/folder2'

def main():
        print("Begin sync")
        checkIfRootDirsExist(srcDir, dstDir)
        syncDirs(srcDir, dstDir)
        syncFiles(srcDir, dstDir)
        print("End sync with success")
    except Exception as e:
        print("End sync with failure!")

def checkIfRootDirsExist(rootDir1, rootDir2) :
    if (not os.path.exists(rootDir1) and not os.path.isdir(rootDir1)) :
        raise Exception(rootDir1 + " doesn't exist")
    if (not os.path.exists(rootDir2) and not os.path.isdir(rootDir2)) :
        raise Exception(rootDir2 + " doesn't exist")

def syncDirs(rootDir1, rootDir2):
    for root1, dirs1, files1 in os.walk(rootDir1):
        for relativePath1 in dirs1 :
            fullPath1 = os.path.join(root1, relativePath1)
            fullPath2 = fullPath1.replace(rootDir1, rootDir2)
            if os.path.exists(fullPath2) and os.path.isdir(fullPath2) :
            if os.path.exists(fullPath2) and os.path.isfile(fullPath2) :
                raise Exception("Cannot perform dir sync." + str(fullPath2) + " should be a dir, not a file!")
            # Case 1 : dest dir does not exit
            shutil.copytree(fullPath1, fullPath2)
            print("Directory " + str(fullPath2) + " copied from " + str(fullPath1))
    for root2, dirs2, files2 in os.walk(rootDir2):
        for relativePath2 in dirs2:
            fullPath2 = os.path.join(root2, relativePath2)
            fullPath1 = fullPath2.replace(rootDir2, rootDir1)
            if os.path.exists(fullPath1) and os.path.isdir(fullPath1) :
            if os.path.exists(fullPath1) and os.path.isfile(fullPath1) :
                raise Exception("Cannot perform dir sync." + str(fullPath1) + " should be a dir, not a file!")
            # Case 3 : dest dir exists but not src dir, so we need to copy it
            shutil.copytree(fullPath2, fullPath1)
            print("Directory " + str(fullPath1) + " copied from" + str(fullPath2))

def syncFiles(rootDir1, rootDir2):
    for root1, dirs1, files1 in os.walk(rootDir1):
        for file1 in files1:
            fullPath1 = os.path.join(root1, file1)
            fullPath2 = fullPath1.replace(rootDir1, rootDir2)
            # Case 1 : the file does not exist in dest dir
            if (not os.path.exists(fullPath2)) :
                shutil.copy2(fullPath1, fullPath2)
                print("File " + str(fullPath2) + " copied from " + str(fullPath1))
            # Case 2 : src file is more recent than dest file
            file1LastModificationTime = round(os.path.getmtime(fullPath1))
            file2LastModificationTime = round(os.path.getmtime(fullPath2))
            if (file1LastModificationTime > file2LastModificationTime):
                shutil.copy2(fullPath1, fullPath2)
                print("File " + str(fullPath2) + " synchronized from " + str(fullPath1))
            # Case 3 : dest file is more recent than src file
            if (file1LastModificationTime < file2LastModificationTime):
                shutil.copy2(fullPath2, fullPath1)
                print("File " + str(fullPath1) + " synchronized from " + str(fullPath2))
    # Case 4 : file only exists in dest dir but not in src
    # So, we copy it back to src dir
    for root2, dirs2, files2 in os.walk(rootDir2):
        for file2 in files2:
            fullPath2 = os.path.join(root2, file2);
            fullPath1 = fullPath2.replace(rootDir2, rootDir1);
            if (os.path.exists(fullPath1)):
            shutil.copy2(fullPath2, fullPath1)
            print("File " + str(fullPath1) + " copied from " + str(fullPath2))

if __name__ == '__main__':

Friday, February 28, 2014

Automatic date stamping of Hibernate entities

That's what I was looking for today and I found it on Stackoverflow. You can do that with three elegant JPA annotations :

  • @PrePersist : automatically invoke the annoted method before persist the new entity
  • @PreUpdate : automatically invoke the annoted method before update the existing entity
  • @Temporal : very important to set the temporal type to timestamp. Otherwise, Hibernate could store date without hours, minutes and seconds (only day, month and year)

Enjoy Hibernate and JPA!!! (On small projects, this is always a pleasure. On large one, things are always different...)

Here is the example I found : 

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrePersist;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

public abstract class AbstractTimestampEntity {

    @Column(name = "created", nullable = false)
    private Date created;

    @Column(name = "updated", nullable = false)
    private Date updated;

    protected void onCreate() {
    updated = created = new Date();

    protected void onUpdate() {
    updated = new Date();
and have all your entities extend it, for instance:
@Table(name = "campaign")
public class Campaign extends AbstractTimestampEntity implements Serializable {

Wednesday, January 22, 2014

Start a java program from another java program programmatically

That's the thing I had to perform today. Let's introduce the need : I developed last year a standalone java program that I can start from command line. Now, I want to start it from a web application. As the program is complex (some Spring Batch stuffs), I don't want to make an heavy integration. So, I decided to embed its jar in my webapp (WEB-INF/lib). All I had to do was to find an elegant way to start a dedicated java virtual machine from my webapp to run my program without consequence on my web application.

The most elegant way I found was to use ANT... programmatically. In the following example, I wrote two classes. The MainProgram represents my webapp and the ProgramToRun represents my Spring Batch application. To simplify the code,  I didn't create a specific classpath for the ANT task but keep in mind that it's possible.

Look at the code, isn't it easy and cool?

public class MainProgram {

public static void main(String[] args) {
Project project = new Project();
project.setBaseDir(new File(System.getProperty("user.dir")));
DefaultLogger logger = new DefaultLogger();
Throwable caught = null;
try {
Echo echo = new Echo();
echo.setMessage("Launching Some Class");

Java javaTask = new Java();
Variable aParam = new Variable();
StringBuilder builder = new StringBuilder();
builder.append("Yeah!! I catched the param");
int ret = javaTask.executeJava();
System.out.println("java task return code: " + ret);

} catch (BuildException e) {
caught = e;

public class ProgramToRun {

public static void main(String[] args) {
System.out.println("Well done!!!");


Did you see the tip? No? I passed a parameter to my external program with a system property. Let's have a look to the console output :

     [Echo] Launching Some Class
  [runjava] Well done!!!
  [runjava] Yeah!! I catched the param
java task return code: 0

Total time: 0 seconds

A really nice ANT use case I discovered !!!