Archive

Archives pour la catégorie ‘Source Code’

Create albums web site

28/01/2009
Commentaires fermés

#! /bin/sh
# Version 1.0

# Nom des fichiers template
TEMPLATE_PHOTO="template.photo.xsp";
TEMPLATE_INDEX="template.index.xsp";
TEMPLATE_ALBUMS="template.albums.xsp";
# Taille des images
THUMB_MAX=102
IMAGE_MAX=512
#
NB_THUMB_PER_LINE=5

# Supression du fichier de log
if [ -f warning.log ]; then date=`date '+%T-%r'`; mv warning.log warning.log.$date; fi

# Methode de recuperation des informations de l'image
# @param $1 Nom de l'image
getImageHeight() {
	identify $1 | awk '{ print $3 }' | awk -F"+" '{ print $1 }' | awk -F"x" '{ print $2 }';
}

# Methode de recuperation des informations de l'image
# @param $1 Nom de l'image
getImageWidth() {
	identify $1 | awk '{ print $3 }' | awk -F"x" '{ print $1 }';
}

# Methode de calcul du pourcentage de reduction ?  appliquer pour obtenir une image ?  la taille donn??e
# @param $1 Nom de l'image
# @param $2 Taille ?  atteindre
getPourcentage() {
	if [ "$1" != "" ] && [ "$2" != "" ]; then
		# Recup??ration de la taille de l'image
		WIDTH=`getImageWidth $1`;
		HEIGHT=`getImageHeight $1`;
		# Recup??ration du cote le plus grand
		if [ `expr $WIDTH \> $HEIGHT` = 1 ]; then SIZE="$WIDTH"; else SIZE=$HEIGHT; fi
		# Calcul du pourcentage
		POUR=`expr $2 \* 100`;
		POUR=`expr $POUR / $SIZE`;
		# Recuperation de ce qu'il y a apres la virgule
		POUR1=`expr $2 \* 10000`;
		POUR1=`expr $POUR1 / $SIZE`;
		POUR2=`expr $2 \* 100`;
		POUR2=`expr $POUR2 / $SIZE`;
		POUR2=`expr $POUR2 \* 100`;
		DIFF=`expr $POUR1 - $POUR2`;
		# Si  le reste est superieur ?  50 on arondie ?  la dixaine superieure
		if [ `expr $DIFF \> 50` = 1 ]; then POUR=`expr $POUR + 1`; fi
		# Affichage du resultat
		echo $POUR;
	fi
}

# Methode de retouche des images
# @param $1 Nom du template ?  utiliser
# @param $2 Nombre d'image ?  traiter
# @param $3 Nom du repertoire contenant les images (JPEG)
addImagesAlbum() {
	# Get user parameters
	FOLDER=$1;
	ALBUM=$2;
	OFFSET=$3;

	# Initialize variables
	c=1;

	# Verify parameters
	if [ "$1" != "" ] && [ "$2" != "" ]; then
		if [ -d $FOLDER ]; then
			if [ ! -d $ALBUM ]; then
				# Create Album folder
				mkdir $ALBUM;
				mkdir $ALBUM/photos;
				mkdir $ALBUM/thumb;

				# Get offset (if set)
				if [ "$3" != "" ]; then c=$OFFSET; fi

				# Manage all JPEG images
				for i in `find $FOLDER -iname "*.jpg"`;
				do
					if [ -f $i ]; then
						# Format image number
						if [ `expr $c \< 10` = 1 ]; then c="0$c"; fi

						printf "\r  Photo n??°${c}";

						# Retouche de l'image pour obtenir la taille souhait??e
						#getPourcentage $i $IMAGE_MAX
						#echo "Press ENTER to continue"
						#read toto;
						POUR=`getPourcentage $i $IMAGE_MAX`;
						convert -sample `echo ${POUR}%x${POUR}%` "$i" "$ALBUM/photos/${c}.jpg";

						# Making Thumbnail
						POUR=`getPourcentage "$ALBUM/photos/${c}.jpg" $THUMB_MAX`;
						convert -sample `echo ${POUR}%x${POUR}%` "$ALBUM/photos/${c}.jpg" "$ALBUM/thumb/${c}.jpg";

						# Count image number
						c=`expr $c + 1`;
					else
						WARNING=true;
						printf "\r  WARNING: File $i does not exist !";
						echo "WARNING: File $i does not exist !" >> warning.log
					fi
				done

				# Saving information about album
				NB_IMG=`expr $c - 1`
				echo "ALBUM=$ALBUM"   >  $ALBUM/$ALBUM.info
				echo "NB_IMG=$NB_IMG" >> $ALBUM/$ALBUM.info
				printf ".\n";

			else
				echo "Folder '$ALBUM' already exist !!";
				exit;
			fi
		else
			echo "Image folder '$FOLDER' does not exist !!";
			exit;
		fi
	else
		echo "Usage: $0 [Image Folder] [Album Name] [Offset]"
		exit;
	fi
}

# Methode de cr??ation des pages pour visualiser chaques images
# @param $1 Nom du template ?  utiliser
# @param $2 Nombre d'image ?  traiter
# @param $3 Nom du repertoire contenant les images (JPEG)
makePages() {
	# Verify parameters
	if [ -f $1 ] && [ "$2" != "" ] && [ -d $3 ]; then

		TEMPLATE=$1
		NB_IMG=$2
		ALBUM=$3

		NUM_IMG=1

		if [ -f $TEMPLATE ]; then
			while [ `expr $NUM_IMG \<= $NB_IMG` = 1 ]; do

		        PREV=`expr $NUM_IMG - 1`;
		        if [ `expr $NUM_IMG \<= 1` = 1 ]; then PREV=$NB_IMG; fi;

		        NEXT=`expr $NUM_IMG + 1`;
		        if [ `expr $NUM_IMG \>= $NB_IMG` = 1 ]; then NEXT=1; fi;

		        if [ `expr $NEXT    \< 10` = 1 ]; then NEXT="0$NEXT"; fi
		        if [ `expr $PREV    \< 10` = 1 ]; then PREV="0$PREV"; fi
		        if [ `expr $NUM_IMG \< 10` = 1 ]; then NUM_IMG="0$NUM_IMG"; fi

		        printf "\r  Page n??°${NUM_IMG}/${NB_IMG}"
				#printf " (prev=$PREV, next=$NEXT)"

		        cat $TEMPLATE | \
					sed "s#ALBUM#<a href='index.html'>$ALBUM</a>#" | \
					sed "s#CLASSEMENT#${NUM_IMG}/${NB_IMG}#" | \
					sed "s#PREVIMAGE#photo-${PREV}.html#g" | \
					sed "s#NEXTIMAGE#photo-${NEXT}.html#g" | \
					sed "s#IMAGE#photos/${NUM_IMG}.jpg#g" > $ALBUM/photo-${NUM_IMG}.xsp;

				 NUM_IMG=`expr $NUM_IMG + 1`;
			done
			printf ".\n";
		else
			printf "Template page '$TEMPLATE' dos not exist !!\n";
		fi

	else
		echo "Usage: $0 [Template] [nb images] [Album]"
	fi
}

# Methode de cr??ation de l'index avec toutes les images en miniatures
# @param $1 Nom du template ?  utiliser
# @param $2 Nombre d'image ?  traiter
# @param $3 Nom du repertoire contenant les images (JPEG)
makeImagesIndex() {
	# Template pour les miniatures
	IMAGE="<td><div width='"`expr $THUMB_MAX + 5`"' height='"`expr $THUMB_MAX + 5`"'><a href='photo-NUM_IMG.html'><img src='thumb/NUM_IMG.jpg' border='0' class='chloe'/></a></div></td>";

	NUM_IMG=1;
	NUM_COL_IN_LINE=1;

	# Verify parameters
	if [ -f $1 ] && [ "$2" != "" ] && [ -d $3 ]; then

		TEMPLATE=$1;
		NB_IMG=$2;
		ALBUM=$3;
		IMAGES="<table border='0'>";

		#echo "$TEMPLATE $NB_IMG $ALBUM"; 

		if [ -f $TEMPLATE ]; then
			while [ `expr $NUM_IMG \<= $NB_IMG` = 1 ]; do
				if [ "$NUM_COL_IN_LINE" == "1" ]; then
					IMAGES="$IMAGES <tr>";
				fi
		        if [ `expr $NUM_IMG \< 10` = 1 ]; then NUM_IMG="0$NUM_IMG"; fi

				IMAGES=`echo $IMAGES; echo $IMAGE | sed "s/NUM_IMG/$NUM_IMG/g"`;

				#CONTENT=`echo $CONTENT | sed "s/\(^.*LINE_CONTENT.*$\)/$IMAGE\n\1\n/g"`;
		        printf "\r  Add image n??°${NUM_IMG}/${NB_IMG}"
				# Increment counters
				NUM_IMG=`expr $NUM_IMG + 1`;
				NUM_COL_IN_LINE=`expr $NUM_COL_IN_LINE + 1`;
				# Close line if needed
				if [ "$NUM_COL_IN_LINE" == "$NB_THUMB_PER_LINE" ]; then
					NUM_COL_IN_LINE=1;
					IMAGES="$IMAGES </tr>";
				fi
			done
			# Close line if not already done
			if [ "$NUM_COL_IN_LINE" != "$NB_THUMB_PER_LINE" ]; then IMAGES="$IMAGES </tr>"; fi
			# Close table
			IMAGES="$IMAGES </table>";
			# Make index
			cat $TEMPLATE | sed "s#ALBUM_NAME#$ALBUM#g" | sed "s#\(^.*LINE_CONTENT.*$\)#`echo $IMAGES`#g" > $ALBUM/index.xsp
			printf ".\n";
		else
			printf "Template page '$TEMPLATE' dos not exist !!\n";
		fi
	else
		echo "Usage: $0 [Template] [nb images] [Album]"
	fi
}

# Methode de cr??ation de l'index de tous les albums
# @param $1 Nom du template ?  utiliser
# @param $2 Nombre d'image ?  traiter
# @param $3 Nom du repertoire contenant les images (JPEG)
makeAlbumsIndex() {

	# Verify parameters
	if [ -f $1 ] && [ "$2" != "" ] && [ -d $3 ]; then

		TEMPLATE=$1;
		NB_IMG=$2;
		ALBUM=$3;

		#echo "$TEMPLATE $NB_IMG $ALBUM"; 

		if [ -f index.xsp ]; then
			cat index.xsp | sed "s#ALBUM_NAME#Liste des Albums#g" | sed "s#\(^.*LINE_CONTENT.*$\)#<li><a href='$ALBUM/index.html'>$ALBUM</a><br/></li>\n\1\n#g" > index.new
			mv index.new index.xsp;
			if [ "$WARNING" != "true" ]; then
				printf "Album '$ALBUM' succesfully added.\n";
			else
				printf "Album '$ALBUM' added with warnings.\nSee warnings.log for more details.\n";
			fi
		elif [ -f $TEMPLATE ]; then
			cat $TEMPLATE | sed "s#ALBUM_NAME#Liste des Albums#g" | sed "s#\(^.*LINE_CONTENT.*$\)#<h1>Liste des albums :</h1>\n<br/>\n<ul>\n<li><a href='$ALBUM/index.html'>$ALBUM</a><br/></li>\n\1\n</ul>#g" > index.xsp
			if [ "$WARNING" != "true" ]; then
				printf "Album '$ALBUM' succesfully added.\n";
			else
				printf "Album '$ALBUM' added with warnings.\nSee warnings.log for more details.\n";
			fi
		else
			printf "Template page '$TEMPLATE' dos not exist !!\n";
		fi
	else
		echo "Usage: $0 [Template] [nb images] [Album]"
	fi
}

# Lancement de toutes le methode dans le bon ordre ...
addImagesAlbum $1 $2 $3;
makePages $TEMPLATE_PHOTO $NB_IMG $ALBUM;
makeImagesIndex $TEMPLATE_INDEX $NB_IMG $ALBUM;
makeAlbumsIndex $TEMPLATE_ALBUMS $NB_IMG $ALBUM;

Shell

Some shell commands

28/01/2009
Commentaires fermés

Put current date to extracted files from a tar

# touch `tar tvf tarfile.tar | grep "extentionOfFileToBeTouch" | awk '{ print $8 }' `

Find a file

# find . -name [filename]

Find a file or a directory

# find . -type [filename|directoryname]

Find all the files that contain the given text

# find . -type f | xargs grep [text]

Find all files upper or lower than a given size

In byte (b) or in KiloByte (k)

# find . -size [+|-] x[b|k]

Find all the files that are newer than an other given file

# find . -newer file

Find a working processus by its name

# ps -edf [process name] | grep -v grep

Get informations of all the device disk

# df

Get the disk usage of the given files or folders

k for kilo s for summary

# du -ks [file|folder]


Shell

JForm

28/01/2009
Commentaires fermés

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * This is a swing class that handle Forms by managing lines.
 * In one line you can put a label (left), a component (auto resize - middle) and an other component (rigth)
 * @author Gabriel Dromard
 */
public class JForm extends JPanel {
    public static final long serialVersionUID = 364635478;
    private ArrayList leftComponents = new ArrayList();
    private ArrayList rightComponents = new ArrayList();
    private JPanel lastLine = null;
    private int hgap, vgap;

    private int rightWidth;
    private int leftWidth;

    /**
    * Initialization of the component
    * @param hgap the horizontal gap of the layout.
    * @param vgap the vertical gap of the layout.
    */
    public JForm(int hgap, int vgap) {
        super();
        this.hgap = hgap;
        this.vgap = vgap;
        this.setLayout(new BorderLayout(hgap, vgap));
        lastLine = this;
    }

    /**
    * Centralize creation of panels
    * @return A new instance of panel (with border layout and opaque false)
    */
    public JPanel buildPanel() {
        JPanel panel = new JPanel(new BorderLayout(hgap, vgap));
        panel.setOpaque(this.isOpaque());
        panel.setBackground(this.getBackground());
        return panel;
    }

    /**
    * Add a line to the form
    * @param label  The label (WEST)
    * @param middle A component (middle)
    * @param right  A component (EAST)
    */
    public void addLine(JLabel label, JComponent middle, JComponent right) {
        JPanel line = buildPanel();
        if(label != null) {
            leftWidth = addComponent(leftComponents, label, leftWidth);
            line.add(label, BorderLayout.WEST);
        }
        if(right != null) {
            rightWidth = addComponent(rightComponents, right, rightWidth);
            line.add(right, BorderLayout.EAST);
        }
        if(middle != null) {
            line.add(middle, BorderLayout.CENTER);
        }
        lastLine.add(line, BorderLayout.NORTH);
        JPanel nextLine = buildPanel();
        lastLine.add(nextLine, BorderLayout.CENTER);
        lastLine = nextLine;
    }

    /**
     * This methods is used to set width of left or rigth component. All the component on left must have the same width !
     * And it is the same for rigth ones.
     *
     * @param components The ArrayList of components.
     * @param component The component to add into the ArrayList.
     * @param maxSize The current max size of the components.
     * @return The new max size of the components
     */
    private int addComponent(ArrayList components, JComponent component, int maxSize) {
        int size = (int)component.getPreferredSize().getWidth();

        System.out.println("size="+size);
        System.out.println("maxSize="+maxSize);
        if (size > maxSize) {
            maxSize = size;
            adaptWidth(components, maxSize);
        } else {
            component.setPreferredSize(new Dimension(maxSize, (int)component.getPreferredSize().getHeight()));
        }

        components.add(component);

        return maxSize;
    }

    /**
     * This methods is used to adapt the prefered size of components of an array.
     *
     * @param components The components.
     * @param size The new prefered size.
     */
    private void adaptWidth(ArrayList components, int size) {
        JComponent cmp;
        // Set preferred size for left components
        for (int i=0; i<components.size(); i++) {
            cmp = ((JComponent)components.get(i));
            cmp.setPreferredSize(new Dimension(size, (int)cmp.getPreferredSize().getHeight()));
        }
    }

    /**
     * This is a way of testing this class.
     *
     * @param args Not used.
     */
    public static void main(String[] args) {
        JForm form = new JForm(5, 5);
        form.setBackground(Color.WHITE);
        form.setOpaque(true);

        for (int i = 0; i < 10; ++i) {
            if (i == 1) {
                form.addLine(new JLabel("JLabel n°" + i), new JTextField(), null);
            } else if (i == 2) {
                form.addLine(null, new JTextField(), new JButton("JButton n°" + i));
            } else if (i == 3) {
                form.addLine(null, new JTextField(), null);
            } else if (i == 4) {
                form.addLine(new JLabel("JLabel n°" + i), null, null);
            } else if (i == 5) {
                form.addLine(null, null, new JButton("JButton n°" + i));
            } else {
                form.addLine(new JLabel("JLabel n°" + i), new JTextField(), new JButton("JButton n°" + i));
            }
        }
        SwingHelper.openInFrame(form);
    }
}

Java

JTaskPane

28/01/2009
Commentaires fermés

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

/**
 * This is a J2LProd's JTaskPane like component <a href="http://www.L2FProd.com" onclick="javascript:pageTracker._trackPageview ('/outbound/www.L2FProd.com');">see L2FProd</a>.
 * Building task oriented applications
 * Lot of recent applications bring contextual item lists from which you can pick tasks related to
 * the current selection or context.
 * The JTaskPane <!--and JTaskPaneGroup--> deliver this feature to java applications.
 *
 * @author Gabriel Dromard
 */
public class JTaskPane extends JPanel {
    protected static int BUTTON_WIDTH = 18;
    protected Color borderColor = Color.GRAY;
    protected Color buttonBorderColor = Color.DARK_GRAY.brighter();
    protected Color titleGradientBeginColor = Color.WHITE;
    protected Color titleGradientEndColor = Color.LIGHT_GRAY;
    protected JPanel content;
    protected MyJLabel label;

    public JTaskPane(final String title, final JComponent component) {
        super(new BorderLayout());
        this.setOpaque(false);
        // Title
        label = new MyJLabel(title);
        label.setBorder(BorderFactory.createLineBorder(borderColor));
        add(label, BorderLayout.NORTH);
        // Content Panel
        content = new JPanel(new BorderLayout()) {
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(borderColor);
                g.drawRect(0, -1, getWidth()-1, getHeight());
            }
        };
        content.setBorder(new LineBorder(borderColor) {
            public Insets getBorderInsets(Component c) {
                Insets insets = super.getBorderInsets(c);
                insets.top = insets.top-1;
                return insets;
            }
        });
        content.add(component, BorderLayout.CENTER);
        add(content, BorderLayout.CENTER);
        // Hide/show content
        label.setButtonActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                content.setVisible(!content.isVisible());
            }
        });
    }

    public void paintComponent(final Graphics g) {
        // Set the background color of the content panel
        content.setBackground(JTaskPane.this.getBackground());
        super.paintComponent(g);
    }

    /**
    * Set the JTaskPane opened or closed
    */
    public void setOpened(boolean opened)
    {
        label.button.up = opened;
        content.setVisible(opened);
    }

    /**
    * Is the JTaskPane opened ?
    * @return True if it is opened
    */
    public boolean isOpened()
    {
        return content.isVisible();
    }

    /**
    * @return the titleGradientBeginColor
    */
    public Color getTitleGradientBeginColor() {
        return titleGradientBeginColor;
    }

    /**
    * @param titleGradientBeginColor the titleGradientBeginColor to set
    */
    public void setTitleGradientBeginColor(Color titleGradientBeginColor) {
        this.titleGradientBeginColor = titleGradientBeginColor;
    }

    /**
    * @return the titleGradientEndColor
    */
    public Color getTitleGradientEndColor() {
        return titleGradientEndColor;
    }

    /**
    * @param titleGradientEndColor the titleGradientEndColor to set
    */
    public void setTitleGradientEndColor(Color titleGradientEndColor) {
        this.titleGradientEndColor = titleGradientEndColor;
    }

    /**
    * Title of JTaskPane
    */
    class MyJLabel extends JLabel {
        protected MyJButton button;
        protected ActionListener currentActionListener;

        public MyJLabel(final String title) {
            super("  "+title);
            setPreferredSize(new Dimension(getWidth(), 30));
            button = new MyJButton();
            int yPos = (getHeight() - BUTTON_WIDTH)/2;
            int xPos = getWidth() - yPos - BUTTON_WIDTH;
            button.setBounds(xPos, yPos, BUTTON_WIDTH, BUTTON_WIDTH);
            add(button);
        }

        public void setButtonActionListener(final ActionListener action) {
            // Remove action listeners
            button.removeActionListener(currentActionListener);
            button.addActionListener(action);
            currentActionListener = action;
        }

        public void paintComponent(final Graphics g) {
            // Re set position of button
            int yPos = (getHeight() - BUTTON_WIDTH)/2;
            int xPos = getWidth() - yPos - BUTTON_WIDTH;
            button.setBounds(xPos, yPos, BUTTON_WIDTH, BUTTON_WIDTH);

            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            Paint oldPainter = g2.getPaint();
            g2.setPaint(new GradientPaint(0, 0, titleGradientBeginColor, (float)getSize().getWidth(), (float)getSize().getHeight(), titleGradientEndColor));
            //g2.fill(new RoundRectangle2D.Double(0, 0, (double)getWidth(), (double)getHeight(), 12, 12));
            g2.fill(new Rectangle2D.Double(0, 0, getWidth(), getHeight()));
            g2.setPaint(oldPainter);
            super.paintComponent(g);
        }
    }

    /**
    * Button on left of JTaskPane title
    */
    class MyJButton extends JButton {
        protected boolean up = true;

        public MyJButton() {
            super();
            setOpaque(false);
            setBorderPainted(false);
            setFocusPainted(false);
            setContentAreaFilled(false);
            setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
            addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    up = !up;
                }
            });
        }

        public void paintComponent(final Graphics g) {
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            Paint oldPainter = g2.getPaint();
            g2.setPaint(new GradientPaint(0, 0, titleGradientEndColor.brighter(), getWidth()/2, getHeight()/2, titleGradientEndColor, true));
            g2.fillOval(0, 0, getWidth()-1, getHeight()-1);
            g2.setColor(buttonBorderColor);
            g2.drawOval(0, 0, getWidth()-1, getHeight()-1);
            g2.setColor(Color.DARK_GRAY);
            if(up) paintUpArrows(g2);
            else paintDownArrows(g2);
            g2.setPaint(oldPainter);
        }

        public void paintUpArrows(Graphics2D g2) {
            g2.translate(0, -1);
            g2.drawLine(5, getHeight()/2, getWidth()/2, 5);
            g2.drawLine(6, getHeight()/2, getWidth()/2, 6);
            g2.drawLine(getWidth()/2, 5, getWidth() - 5, getHeight()/2);
            g2.drawLine(getWidth()/2, 6, getWidth() - 6, getHeight()/2);
            g2.translate(0, +1);

            g2.translate(0, getHeight()/4-1);
            g2.drawLine(5, getHeight()/2, getWidth()/2, 5);
            g2.drawLine(6, getHeight()/2, getWidth()/2, 6);
            g2.drawLine(getWidth()/2, 5, getWidth() - 5, getHeight()/2);
            g2.drawLine(getWidth()/2, 6, getWidth() - 6, getHeight()/2);
            g2.translate(0, -getHeight()/4+1);
        }

        public void paintDownArrows(Graphics2D g2) {
            g2.drawLine(5, getHeight()/2, getWidth()/2, getHeight() - 5);
            g2.drawLine(6, getHeight()/2, getWidth()/2, getHeight() - 6);
            g2.drawLine(getWidth()/2, getHeight() - 5, getWidth() - 5, getHeight()/2);
            g2.drawLine(getWidth()/2, getHeight() - 6, getWidth() - 6, getHeight()/2);

            g2.translate(0, -getHeight()/4);
            g2.drawLine(5, getHeight()/2, getWidth()/2, getHeight() - 5);
            g2.drawLine(6, getHeight()/2, getWidth()/2, getHeight() - 6);
            g2.drawLine(getWidth()/2, getHeight() - 5, getWidth() - 5, getHeight()/2);
            g2.drawLine(getWidth()/2, getHeight() - 6, getWidth() - 6, getHeight()/2);
            g2.translate(0, +getHeight()/4);
        }
    }

    /**
    * Demo main methods that display JTaskPane, JForm, ShadowBorder
    */
    public static void main(String[] args) {
        //
        JForm root = new JForm(10, 10);
        root.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        //root.setBackground(Color.WHITE);
        // Initialize JForm
        JForm form1 = new JForm(5, 5);
        form1.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        form1.setBackground(Color.WHITE);

        //form.setOpaque(false);
        for(int i=0; i<10; ++i) {
           JTextField txt = new JTextField();
           txt.setPreferredSize(new Dimension(150, (int)txt.getPreferredSize().getHeight()));
            if(i == 3) form1.addLine(new JLabel("label plus long"+i), txt, new JButton("Select"+i));
            else form1.addLine(new JLabel("label"+i), txt, new JButton("Select"+i));
        }
        JForm form2 = new JForm(5, 5);
        form2.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        form2.setBackground(Color.WHITE);
        for(int i=0; i<5; ++i) {
           JTextField txt = new JTextField();
           txt.setPreferredSize(new Dimension(150, (int)txt.getPreferredSize().getHeight()));
            if(i >= 3) form2.addLine(new JLabel("label plus long"+i), txt, null);
            else form2.addLine(new JLabel("label"+i), txt, new JButton("Select"+i));
        }
        // Add form in panel
        JPanel myPanel1 = new JTaskPane("JTaskPane containing a JForm", form1);
        ShadowBorder shadowBorder = new ShadowBorder(Color.GRAY);
        myPanel1.setBorder(shadowBorder);

        // Add form in panel
        JTaskPane myPanel2 = new JTaskPane("Same with different options", form2);
        myPanel2.titleGradientBeginColor = Color.LIGHT_GRAY;
        myPanel2.titleGradientEndColor = Color.WHITE;
        shadowBorder = new ShadowBorder(Color.GRAY);
        shadowBorder.setType(ShadowBorder.TOP_LEFT);
        myPanel2.setBorder(shadowBorder);
        //myPanel.setBackground(Color.WHITE);
        root.addLine(null, myPanel1, null);
        root.addLine(null, myPanel2, null);
        JMemoryMonitor mem = new JMemoryMonitor();
        mem.setPreferredSize(new Dimension(200, 200));
        root.addLine(null, mem, null);
        // Show frame
        JFrame frame = SwingHelper.openInFrame(root);
        frame.setSize(frame.getWidth()+300, frame.getHeight());
        myPanel2.setOpened(false);
        SwingUtilities.updateComponentTreeUI(frame);
    }
} 

Java

JMemoryMonitor

28/01/2009
Commentaires fermés

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.util.Date;
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;

/**
 * Tracks Memory allocated & used, displayed in graph form.
 */
public class JMemoryMonitor extends JPanel {

    private static final long serialVersionUID = -347102535481575324L;
    private static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp");
    private Surface surf;
    private JPanel controls;
    private boolean doControls;
    private JTextField tf;

    public JMemoryMonitor() {
        setLayout(new BorderLayout());
        setBorder(new TitledBorder(new EtchedBorder(), "Memory Monitor"));
        add(surf = new Surface());
        controls = new JPanel();
        controls.setPreferredSize(new Dimension(135,80));
        Font font = new Font("serif", Font.PLAIN, 10);
        JLabel label = new JLabel("Sample Rate");
        label.setFont(font);
        label.setForeground(Color.black);
        controls.add(label);
        tf = new JTextField("1000");
        tf.setPreferredSize(new Dimension(45,20));
        controls.add(tf);
        controls.add(label = new JLabel("ms"));
        label.setFont(font);
        label.setForeground(Color.black);
        controls.add(dateStampCB);
        dateStampCB.setFont(font);
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
               removeAll();
               doControls = !doControls;
               if (doControls) {
                   surf.stop();
                   add(controls);
               } else {
                   try {
                       surf.sleepAmount = Long.parseLong(tf.getText().trim());
                   } catch (Exception ex) {
                       ex.printStackTrace();
                   }
                   surf.start();
                   add(surf);
               }
               validate();
               repaint();
            }
        });
    }

    private class Surface extends JPanel implements Runnable {

        private static final long serialVersionUID = -4298072680026629003L;
        private Thread thread;
        private long sleepAmount = 1000;
        private int w, h;
        private BufferedImage bimg;
        private Graphics2D big;
        private Font font = new Font("Times New Roman", Font.PLAIN, 11);

        private int columnInc;
        private int pts[];
        private int ptNum;
        private int ascent, descent;
        //private float freeMemory, totalMemory;
        //private Rectangle graphOutlineRect = new Rectangle();
        private Rectangle2D mfRect = new Rectangle2D.Float();
        private Rectangle2D muRect = new Rectangle2D.Float();
        private Line2D graphLine = new Line2D.Float();
        private Color graphColor = new Color(46, 139, 87);
        private Color mfColor = new Color(0, 100, 0);
        private String usedStr;

        public Surface() {
            setBackground(Color.black);
            addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    if (thread == null) start(); else stop();
                }
            });
        }

        public Dimension getMinimumSize() {
            return getPreferredSize();
        }

        public Dimension getMaximumSize() {
            return getPreferredSize();
        }

        public Dimension getPreferredSize() {
            return new Dimension(135,80);
        }

        public void paint(Graphics g) {

            if (big == null) {
                return;
            }

            big.setBackground(getBackground());
            big.clearRect(0,0,w,h);

            float freeMemory  = Runtime.getRuntime().freeMemory();
            float totalMemory = Runtime.getRuntime().totalMemory();
            //float totalMemory = Runtime.getRuntime().maxMemory();

            // .. Draw allocated and used strings ..
            big.setColor(Color.green);
            big.drawString(String.valueOf((int) totalMemory/1024) + "Ko allocated",  4.0f, ascent+0.5f);
            usedStr = String.valueOf(((int) (totalMemory - freeMemory))/1024) + "Ko used";
            big.drawString(usedStr, 4, h-descent);

            // Calculate remaining size
            float ssH = ascent + descent;
            float remainingHeight = (h - (ssH*2) - 0.5f);
            int nbBlocks = 20;
            float blockHeight = remainingHeight/nbBlocks;
            float blockWidth = 20.0f;
            //float remainingWidth = (w - blockWidth - 10);

            // .. Memory Free ..
            big.setColor(mfColor);
            int MemUsage = (int) ((freeMemory / totalMemory) * nbBlocks);
            int i = 0;
            for ( ; i < MemUsage ; i++) {
                mfRect.setRect(5,  ssH+i*blockHeight, blockWidth, blockHeight-1);
                big.fill(mfRect);
            }

            // .. Memory Used ..
            big.setColor(Color.green);
            for ( ; i < nbBlocks; i++)  {
                muRect.setRect(5, ssH+i*blockHeight, blockWidth, blockHeight-1);
                big.fill(muRect);
            }

            // .. Draw History Lines ..
            big.setColor(graphColor);
            int graphX = 30;
            int graphY = (int) ssH;
            int graphW = w - graphX - 5;
            int graphH = (int) remainingHeight;
            for (i = 0 ; i < nbBlocks; i++)  {
                muRect.setRect(graphX, graphY+i*blockHeight-0.5f, graphW, blockHeight);
                big.draw(muRect);
            }

            // .. Draw History columns ..
            int graphColumn = graphW/15;

            if (columnInc == 0) {
                columnInc = graphColumn;
            }
            for (int j = graphX+columnInc; j < graphW+graphX; j+=graphColumn) {
                graphLine.setLine(j,graphY,j,graphY+graphH);
                big.draw(graphLine);
            }

            --columnInc;

            if (pts == null) {
                pts = new int[graphW];
                ptNum = 0;
            } else if (pts.length != graphW) {
                int tmp[] = null;
                if (ptNum < graphW) {
                    tmp = new int[ptNum];
                    System.arraycopy(pts, 0, tmp, 0, tmp.length);
                } else {
                    tmp = new int[graphW];
                    System.arraycopy(pts, pts.length-tmp.length, tmp, 0, tmp.length);
                    ptNum = tmp.length - 2;
                }
                pts = new int[graphW];
                System.arraycopy(tmp, 0, pts, 0, tmp.length);
            } else {
                big.setColor(Color.yellow);
                pts[ptNum] = (int)(graphY+graphH*(freeMemory/totalMemory));
                for (int j=graphX+graphW-ptNum, k=0;k < ptNum; k++, j++) {
                    if (k != 0) {
                        if (pts[k] != pts[k-1]) {
                            big.drawLine(j-1, pts[k-1], j, pts[k]);
                        } else {
                            big.fillRect(j, pts[k], 1, 1);
                        }
                    }
                }
                if (ptNum+2 == pts.length) {
                    // throw out oldest point
                    for (int j = 1;j < ptNum; j++) {
                        pts[j-1] = pts[j];
                    }
                    --ptNum;
                } else {
                    ptNum++;
                }
            }
            g.drawImage(bimg, 0, 0, this);
        }

        public void start() {
            thread = new Thread(this);
            thread.setPriority(Thread.MIN_PRIORITY);
            thread.setName("MemoryMonitor");
            thread.start();
        }

        public synchronized void stop() {
            thread = null;
            notify();
        }

        public void run() {

            Thread me = Thread.currentThread();

            while (thread == me && !isShowing() || getSize().width == 0) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) { return; }
            }

            while (thread == me && isShowing()) {
                Dimension d = getSize();
                if (d.width != w || d.height != h) {
                    w = d.width;
                    h = d.height;
                    bimg = (BufferedImage) createImage(w, h);
                    big = bimg.createGraphics();
                    big.setFont(font);
                    FontMetrics fm = big.getFontMetrics(font);
                    ascent = fm.getAscent();
                    descent = fm.getDescent();
                }
                repaint();
                try {
                    Thread.sleep(sleepAmount);
                } catch (InterruptedException e) { break; }
                if (JMemoryMonitor.dateStampCB.isSelected()) {
                     System.out.println(new Date().toString() + " " + usedStr);
                }
            }
            thread = null;
        }
    }

    public static void main(String s[]) {
        final JMemoryMonitor demo = new JMemoryMonitor();
        WindowListener l = new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
            public void windowDeiconified(WindowEvent e) { demo.surf.start(); }
            public void windowIconified(WindowEvent e) { demo.surf.stop(); }
        };
        JFrame f = new JFrame("Memory Monitor");
        f.addWindowListener(l);
        f.getContentPane().add("Center", demo);
        f.pack();
        f.setSize(new Dimension(200,200));
        f.setVisible(true);
        demo.surf.start();
    }
} 

Java

Shadow Border

28/01/2009
Commentaires fermés

/*
 * Created on 17 oct. 06
 * By Gabriel DROMARD
 */

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;

import javax.swing.JPanel;
import javax.swing.border.AbstractBorder;

/**
 * A class which implements a shadow border.
 *
 * <p>Code Example: </p>
 * <pre>
 *        JPanel root = new JPanel();
 *        // Generate 4 example for each TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT and BOTTOM_RIGHT configurations
 *        for(int i=0; i<4; ++i) {
 *            JPanel test = new JPanel();
 *            test.setPreferredSize(new Dimension(100, 100));
 *            test.setBackground(Color.WHITE);
 *            test.setOpaque(false);
 *            test.setBorder(new ShadowBorder(Color.GRAY, Color.GRAY, 10, i));
 *            root.add(test);
 *        }
 *        //SwingHelper.openInFrame(root);
 *        JFrame frame = new JFrame();
 *        frame.getContentPane().setLayout(new BorderLayout());
 *        frame.getContentPane().add(root, BorderLayout.CENTER);
 *        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
 *        frame.pack();
 *        frame.setVisible(true);
 * </pre>
 */
public class ShadowBorder extends AbstractBorder {
    private int shadowWidth = 10;
    private int inset = 5;
    protected Color lineBorderColor = null;
    protected Color shadowColor = null;
    protected int type = 2;
    public static final int TOP_LEFT = 0;
    public static final int TOP_RIGHT = 1;
    public static final int BOTTOM_LEFT = 2;
    public static final int BOTTOM_RIGHT = 3;

    /**
     * Auto-generated main method to display this
     * JPanel inside a new JFrame.
     */
    public static void main(String[] args) {
        JPanel root = new JPanel();
        for(int i=0; i<4; ++i) {
            JPanel test = new JPanel();
            test.setPreferredSize(new Dimension(100, 100));
            test.setBackground(Color.WHITE);
            test.setOpaque(false);
            test.setBorder(new ShadowBorder(Color.GRAY, Color.GRAY, 10, i));
            root.add(test);
        }
        SwingHelper.openInFrame(root);
    }

    /**
     * Creates a shadow border with the specified shadow width and whose
     * colors will be derived from the background color of the
     * component passed into the paintBorder method.
     * @param shadowWidth the length of shadow
     * @param
     * @param
     * @param
     */
    public ShadowBorder(Color shadowColor, Color lineBorderColor, int shadowWidth, int type) {
        super();
        this.shadowWidth = shadowWidth;
        this.shadowColor = shadowColor;
        this.lineBorderColor = lineBorderColor;
        this.type = type;
    }

    /**
     * Returns the insets of the border.
     * @param c the component for which this border insets value applies
     */
    public Insets getBorderInsets(Component c) {
        int hPosition = shadowWidth;
        int vPosition = shadowWidth;

        if(type == TOP_LEFT) {
            hPosition = 0;
            vPosition = 0;
        } else if(type == TOP_RIGHT) {
            hPosition = shadowWidth;
            vPosition = 0;
        } else if(type == BOTTOM_LEFT) {
            hPosition = 0;
            vPosition = shadowWidth;
        } else if(type == BOTTOM_RIGHT) {
            hPosition = shadowWidth;
            vPosition = shadowWidth;
        }
        return new Insets((shadowWidth - hPosition)+inset, (shadowWidth - vPosition)+inset, hPosition+inset, vPosition+inset);
    }

    /**
     * Reinitialize the insets parameter with this Border's current Insets.
     * @param c the component for which this border insets value applies
     * @param insets the object to be reinitialized
     */
    public Insets getBorderInsets(Component c, Insets insets) {
        insets.left = insets.top = insets.right = insets.bottom = shadowWidth+2;
        return insets;
    }

    /**
     * Returns the shadow color of the border
     * when rendered on the specified component.  If no shadow
     * color was specified at instantiation, the shadow color
     * is derived from the specified component's background color.
     * @param c the component for which the shadow may be derived
     */
    public Color getShadowColor(Component c) {
        Color shadow = getShadowColor();
        if(shadow == null) shadow = c.getBackground().darker().darker();
        return shadow;
    }

    /**
     * Returns the shadow color of the border.
     * Will return null if no shadow color was specified at instantiation.
     */
    public Color getShadowColor() {
        return shadowColor;
    }

    /**
     * Returns whether or not the border is opaque.
     */
    public boolean isBorderOpaque() {
        return true;
    }

    /**
     * Paints the border for the specified component with the specified position and size.
     * @param c the component for which this border is being painted
     * @param g the paint graphics
     * @param x the x position of the painted border
     * @param y the y position of the painted border
     * @param width the width of the painted border
     * @param height the height of the painted border
     */
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
        int hPosition = shadowWidth;
        int vPosition = shadowWidth;

        if(type == TOP_LEFT) {
            hPosition = 0;
            vPosition = 0;
        } else if(type == TOP_RIGHT) {
            hPosition = shadowWidth;
            vPosition = 0;
        } else if(type == BOTTOM_LEFT) {
            hPosition = 0;
            vPosition = shadowWidth;
        } else if(type == BOTTOM_RIGHT) {
            hPosition = shadowWidth;
            vPosition = shadowWidth;
        }
        width = width - 1;
        height = height - 1;
        Graphics2D gg = (Graphics2D) g;
        // backup old color to be able to restore it at the end of paint
        Color oldColor = gg.getColor();
        // Translate position
        gg.translate(x, y);
        // paint shadow
        paintShadow(c, gg, getShadowColor(c), hPosition, vPosition, width-shadowWidth, height-shadowWidth, shadowWidth);
        // Fill with background color the panel
        gg.setColor(c.getBackground());
        gg.fillRect(shadowWidth - hPosition, shadowWidth - vPosition, width-shadowWidth, height-shadowWidth);
        // Draw line border
        if (lineBorderColor != null) {
           gg.setColor(lineBorderColor);
           gg.drawRect(shadowWidth - hPosition, shadowWidth - vPosition, width-shadowWidth, height-shadowWidth);
        }
        // Reset position
        gg.translate(-x, -y);
        // Re put oldColor
        gg.setColor(oldColor);
    }

    /**
     *
     * @param c           the component for which this border is being painted
     * @param gg          the paint graphics
     * @param shadowColor The color of the shadow
     * @param x           the x position of the painted border
     * @param y           the y position of the painted border
     * @param width       the width of the painted border
     * @param height      the height of the painted border
     * @param shadowWidth The shadow width
     */
    public static void paintShadow(Component c, Graphics2D gg, Color shadowColor, int x, int y, int width, int height, int shadowWidth) {
        // Set anti aliasing
        gg.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);
        // Draw shadow
        AlphaComposite ac = null;
        gg.setColor(shadowColor);
        // Initial shadow width:
        int sw = width - 2*shadowWidth;
        // Initial shadow height:
        int sh = height - 2*shadowWidth;
        // Draw shadow
        for(int i=0; i<shadowWidth; ++i) {
            ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f/(i+1));
            gg.setComposite(ac);
            gg.fillRoundRect(x+shadowWidth-i, y+shadowWidth-i, sw + 2*i, sh + 2*i, i*2, i*2);
        }
        // Reset transparency
        ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1);
        gg.setComposite(ac);
    }
}

Java

ExecuteSQLUpdates.groovy

28/01/2009
Commentaires fermés

import groovy.text.*
import groovy.sql.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import java.text.*;

boolean debug = false;

void printUsage() {
	println "Usage: ExecuteUpdates.groovy [-debug] [-url URL] [SQL File]"
	println "       ExecuteUpdates.groovy [-debug] [-url URL] [SQL UPDATE/INSERT/DELETE Query]"
	println ""
	println "       NOTE: For executing more than one query you can use character / to separate them."
	println ""
	println "   This script is able to execute any type of queries, (usefull to create stored procedures)"
	System.exit(1);
}

// Prepare connection ------------------------------------------
driver = "oracle.jdbc.OracleDriver";
url  = "jdbc:oracle:thin:USER/PASS@HOST:1521:DB"
// -------------------------------------------------------------

// Verify inputs
if(args == null || args.length == 0 || args[0].length() == 0) printUsage()
switch(args[0]) {
	case ["-debug", "--debug", "debug", "-d"]:
		debug = true
		if(args.length == 1 || args[1].length() == 0) printUsage()
		args[0] = args[1]
		if(args.length >= 3 && args[2].length() > 0) args[1] = args[2]
		if(args.length >= 4 && args[3].length() > 0) args[2] = args[3]
	break;
	case ["-url", "--url", "url"]:
		if(args.length < 3 || args[1].length() == 0 || args[2].length() == 0)
			printUsage()
		url = args[1]
		args[0] = args[2]
		if(args.length > 3 && args[3].length() > 0) args[1] = args[3]
	break;
	default:
		if(args[0].startsWith("-")) printUsage()
	break;
}

switch(args[0]) {
	case ["-debug", "--debug", "debug", "-d"]:
		debug = true
		if(args.length == 1 || args[1].length() == 0) printUsage()
		args[0] = args[1]
		if(args.length >= 3 && args[2].length() > 0) args[1] = args[2]
		if(args.length >= 4 && args[3].length() > 0) args[2] = args[3]
	break;
	case ["-url", "--url", "url"]:
		if(args.length < 3 || args[1].length() == 0 || args[2].length() == 0 || args[3].length() == 0)
			printUsage()
		url = args[1]
		args[0] = args[2]
	break;
	default:
		if(args[0].startsWith("-")) printUsage()
	break;
}

println "Using URL: "+url

// ------- This script is not finish because I did not manage to add the entire code in -------

Groovy

DBShow.groovy

28/01/2009
Commentaires fermés

import groovy.sql.*;
import java.io.*;
import java.text.*;

/*
 * ====================================================
 *                    FUNCTIONS
 * ====================================================
 */

/**
 * Transform one date to a comprehensive String
 * @param timestamp The timestamp (as string) to convert.
 */
public static String dateToString(String timestamp) {
	try {
		return dateToString(new Date(Long.parseLong(timestamp)));
	} catch(Exception ex) {
		return timestamp;
	}
}

/**
 * Transform one date to a comprehensive String
 * @param date The date (as long or timestamp) to convert.
 */
public static String dateToString(long date) {
	return dateToString(new Date(date));
}

/**
 * Transform one date to a comprehensive String
 * @param date The date to convert.
 */
public static String dateToString(Date date) {
    DateFormat formater = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    return formater.format(date);
}

/**
 * Transform one date to a comprehensive String
 * @param date The date to convert.
 */
public static String format(String columnName, Object columnValue, int colIndex, int nbCol, int defaultLen = 19, boolean trunc = true) {
    String value = ((columnValue==null)?"":columnValue.toString().replace('n', '
').replace('r', '
'));
    if(columnName!=null &amp;&amp; value.length() > 0) {
        switch(columnName) {
            case ["BIDDINGEND", "BIDDINGSTART", "LASTACTIVITYFORCLOSE"]:
                value = dateToString(value);
            break;
            case "STATUS":
                switch(value) {
                    case "1" : value = "Open"; break;
                    case "11": value = "Pending Next Stage"; break;
                }
            break;
            default:
                if(columnName.indexOf("TIME") > -1) value = dateToString(value);
            break;
        }
    }
    if(defaultLen > 0) {
	    int minLen = (columnName == null)?value.length():columnName.length();
	    if(defaultLen > minLen) minLen = defaultLen;
	    if(trunc &amp;&amp; value.length() > minLen) value = value.substring(0, minLen-2)+"..";
	    while(value.length() < minLen) value += " ";
	    return " "+value+((colIndex+1==nbCol)?"n":" |");
	} else {
	    return value+((colIndex+1==nbCol)?"n":"|");
	}
}

/*
 * ====================================================
 *                    GROOVY SCRIPT
 * ====================================================
 */
// Verify inputs
if(args == null || args.length == 0 || args[0].length() == 0) {
	println "usage: groovyFile.groovy [filename] [column lenght]";
	return
}

// Get queries
query = null
if((new File(args[0])).exists()) query = (new File(args[0])).getText();
else query = args[0];

start = new Date();
defaultLen = 19;
if(args.length >= 2 &amp;&amp; args[1].length() > 0 &amp;&amp; !args[0].equals(args[1])) defaultLen = Integer.parseInt(args[1])

// Prepare Connection
driver = "oracle.jdbc.OracleDriver";
url  = "jdbc:oracle:thin:USER/PASS@HOST:1521:DB"

sql = Sql.newInstance(url, driver)
nbRow = 0; nbCol = 0;
sql.eachRow(query) { row |
	len = 0;
	++nbRow;
	if(nbCol==0) {
		nbCol = row.getMetaData().getColumnCount();
		header = "";
		//for(i in 1..nbCol) header += format("null", row.getMetaData().getColumnName(i), i-1, nbCol, row.getMetaData().getColumnDisplaySize(i));
		for(i in 1..nbCol) header += format(null, row.getMetaData().getColumnName(i), (i-1), nbCol, defaultLen);
		print header
		if(defaultLen > 0) {
			for(i in 1..header.length()) print "-";
			print "n";
		}
	}
	for(i in 0..<nbCol) {
		value = row.getAt(i);
		column = row.getMetaData().getColumnName(i+1);
		//------------------
		/*
		value = ((value==null)?"":value.toString());
		if(value.length() > 0) {
			switch(column) {
				case "LASTACTIVITYFORCLOSE":
					value = dateToString(value);
				break;
			}
		}
		while(value.length() < column.length()) value += " ";
		value = value+((i+1==nbCol)?"n":"t");
		print value;
		/**/
		//------------------
		//print format(column, value, i, nbCol, row.getMetaData().getColumnDisplaySize(i))
		print format(column, value, i, nbCol, defaultLen)
	}
}
println "n"
println "Number of column: "+nbCol
println "Number of result: "+nbRow
end = new Date();
println "Executed in "+(end.getTime()-start.getTime())/1000+" s"

Groovy

NowToTimeStamp.groovy

28/01/2009
Commentaires fermés

date = new Date();
println date.getTime();

Groovy

TimestampToDate.groovy

28/01/2009
Commentaires fermés

println new Date(Long.parseLong(args[0]));

Groovy