Wednesday, August 14, 2013

SQL Query to find all table names on database in MySQL and SQL Server Examples

How do you find names of all tables in a database is a recent SQL interview questions asked to one of my friend. There are many ways to find all table names form any database like MySQL and SQL Server. You can get table names either from INFORMATION_SCHEMA or sys.tables based upon whether you are using MySQL or Sql Server database. This is not a popular question like when to use truncate and delete or correlated vs noncorrelated subquery which you can expect almost all candidate prepare well but this is quite common if you are working on any database e.g. MySQL. In this SQL tutorial we will see examples of getting names of all tables from MySQL and SQL Server database. In MySQL there are two ways to find names of all tables, either by using "show" keyword or by query INFORMATION_SCHEMA. In case of SQL Server or MSSQL, You can either use sys.tables or INFORMATION_SCHEMA to get all table names for a database. By the way if you are new in MySQL server and exploring it , you may find this list of frequently used MySQL server commands handy.
Read more �

Monday, August 12, 2013

Swing is not thread-safe in Java - What does it mean? Event Dispatcher, SwingWorker, Multithreading and Best Practices

Couple of my reader ask question, what does it mean by Swing is not thread-safe and How does it affect coding in Swing GUI application? This post is an effort to help those readers and several other programmers to understand Swing and thread-safety in a bit more detailed way. To keep it simple, let's revise what does it mean by being thread-safe? We say an object is thread-safe, if we can call it's method, which can change it's state, from multiple thread at same time. To give you an example, java.lang.String is a thread-safe class, which means you can call any method e.g. substring(), toUpperCase() or toLowerCase() from multiple threads. By the way, String is thread-safe because it's immutable. Let's come back to Swing now, Core part of Swing is made up of different GUI component e.g. JLable, JPanel, JCombobox etc. All these components are not thread-safe, which means you can not call methods of this components e.g. JLable.setText("new title") from any thread, other than Event Dispatcher Thread(EDT). In one word, Since Swing is not thread-safe, you can not update Swing components from any random thread, they are always updated using Event Dispatcher thread. This is in fact one of the most popular Java Swing Interview Question, with lot's of interesting follow-up e.g. If Swing is not thread-safe than how do you update components from other thread? and which methods of Swing API are thread-safe? etc. We will see answer of this question in next section.
Read more �

Saturday, August 10, 2013

How to parse String to Float in Java | Convert Float to String in Java - 3 Examples

float and double are two data type which is used to store floating point values in Java and we often need to convert String to float in Java and sometime even a Float object or float primitive to String. One thing, which is worth remembering about floating point numbers in Java is that they are approximate values, a float value 100.1f may hold actual value as 100.099998, which will be clear, when we seen examples of converting float to String and vice-versa. By the way, It's easy to parse String to float and vice-versa, as rich Java API provides several ways of doing it. If you already familiar with converting String to int or may be String to double in Java, then you can extend same techniques and method to parse float String values. key methods like valueOf() and parseInt(), which is used to parse String to float are overloaded for most primitive data types. If you are particularly interested on rounding of float values, you can use RoundingMode and BigDecimal class, as float and double are always approximate values and comparing two float variable of same values may not always return true, that's why it's advised, not to use float for monetary calculation. In this Java tutorial, we will first see examples of parsing String to float in Java and later converting float to String objects. Remember, we will use float and Float, a wrapper class corresponding to float primitive, interchangeably because by using Java 1.5 autoboxing feature, they are automatically converted to each other, without any Java code. For those, who are still in Java 1.4 or lower version, then can use Float.floatValue() to convert Float wrapper object to float primitive.
Read more �

Friday, August 9, 2013

Liens pratiques de la semaine

Vous trouverez dans ce billet une s�lection de liens pratiques autour des technologies Java qui m'ont particuli�rement int�ress�es ces derni�res semaines. 

Eclipse
  • Un tutoriel tr�s simple sur la cr�ation d'une application Eclipse RCP avec E4.
  • Un billet de l'auteur du livre Eclipse 4 Plug-in Development by Example: Beginner�s Guide qui d�taille plein de choses autour de l'�criture et de la publication de son livre.
  • Un billet qui montre comment utiliser le syst�me d'�v�nements d'Eclipse 4 (EventBroker) sans l'injection de d�pendance.
  • Une solution qui montre comment utiliser le logger d'Eclipse 4 depuis une m�thode statique.
  • Un article qui montre comment utiliser le contr�leur de geste LeapMotion au sein d'une application Eclipse 4. A noter que cet article montre �galement comment cr�er ses propres annotations.
  • EScript est un langage de scripts pour Eclipse.
  • Un billet qui propose des classes utilitaires pour g�rer efficacement les agents de placement GridLayout et GridData.
  • Un tutoriel de d�marrage (Getting Started) pour EMFStore. Pour rappel ce projet permet de stocker, distribuer et collaborer � plusieurs avec des mod�les EMF (mod�les et instances).
  • Des statistiques de t�l�chargement sur la nouvelle version d'Eclipse Kepler : 1 million de t�l�chargement en 18 jours.
  • Un tutoriel qui propose de customiser l'apparence des mod�les EMF en utilisant EMF Client Platform.
  • Une astuce pour mettre en plein �cran une fen�tre d'une application Eclipse 4 RCP.
Java
  • Un article qui montre comment g�rer efficacement la Stack Trace c�t� client pour GWT.
  • docx4j est une biblioth�que Java pour manipuler les formats Microsoft Open XML.
NoSQL
  • Am�lioration du langage Cassandra CQL pr�vue pour Cassandra 2. J'ai not� principalement le support des triggers et les alias au niveau des SELECT.
Divers
  • Biblioth�que JavaScript qui permet de mettre en surbrillance le texte du code de plus de 54 langages.
  • ReaderIsDead ou ZombieReader est une initiative permettant de faire revivre Google Reader. De mon c�t� je suis pass� � Feedly. Je retrouve pratiquement tous les services de Google Reader except�s la cr�ation des blogrolls.
  • BZR Player est un lecteur Audio qui g�re une multitude de formats.
  • Un historique li� � l'univers Lego. Impressionnant la machine � r�soudre les Rubik's Cube.
  • S'il y a bien une application � installer sous Windows, c'est Clover. Cet utilitaire permet d'ajouter la notion d'onglets � votre explorateur Windows.
  • WinDirStat permet de connaitre l'occupation de vos r�pertoires. Il affiche l'information sous forme de Map.

Monday, July 1, 2013

ComboBoxUIs and PopupFactories

Introduction

I recently wanted to experiment with creating my own ComboBoxUI. Using the FilledButtonUI model as a starting point: I created the FilledComboBoxUI. (See the demo here.) It wasn't as straight-forward as I'd expected it to be: but the current draft weighs in at only 500 lines of code.

Unfortunately this highlighted a bug regarding applets in many browsers: JPopupMenus would be positioned relative to the top-left corner of the display, and not the applet. The result is that you would click a combobox and the popup menu would appear several pixels above and to the left. The same problem was also observed for tooltips.

To the right is a screenshot of this bug in the Wordle applet: although I clicked the "Font" menu, the popup that displayed is several pixels away from where it should be.

Solution

After a couple of hours of experimentation: I gave up trying to reposition the heavyweight popup.

Instead: as a work-around I decided to try displaying the popup as a lightweight component. It's not very common that we need to use the powerful complexity of the JLayeredPane: but it has the potential to display JComponent above everything (it even has a layer specifically designated for popups).

Originally my goal was only to implement a lightweight model for my new FilledComboBoxUI class (because I had such explicit control over how the popup would be invoked), but as I rummaged around I realized the javax.swing.PopupFactory is an existing architecture that may let me intercept all popups (including tooltips).

The final result is the new AppletPopupFactory (source here). After you invoke the static initialize() method: it will handle all popups. If a popup is requested outside of an applet: then the original PopupFactory is used instead (so if it's invoked in an application vs an applet: then the fancy new code isn't touched).

Additional problems included:

  • Originally for the new PopupFactory I tried calling JPopupMenu.setVisible(..) to help control visibility, because it is still a JComponent. Unfortunately: this is a complex invocation that ultimately defers to the current PopupFactory. The result (if I try to use setVisible(..)) is a recursive loop that never actually alters visibility. The solution was to simply avoid interacting with the visibility. (The JPopupMenu is a strange creature, and now I know it can function as a normal lightweight JComponent as long as you don't touch its visibility.) Instead: adding it and removing it from the parent JLayeredPane can achieve the necessary effect.

  • Clicking outside the popup needs to dismiss the popup. So behind the popup: we install a giant invisible panel that consumes MouseEvents. This means we notice when the user clicks in this area (so we can hide the popup), and we prevent the user from clicking any other component while the popup is visible.

  • The popup generally rendered correctly, but it needed decoration. By "decoration" I mean: a border and a shadow. The shadow is more of an indulgence, but I'll explain it first: since we already have a giant panel used to intercept MouseEvents: I tweaked this so it rendered a small shadow around the popup. The border proved a stranger problem: when the AquaComboBoxUI was being used on Mac 10.7.5 (Java 1.7): the border was never rendered. It was correctly defined as a simple LineBorder -- and the same LineBorder rendered correctly with the FilledComboBoxUI -- but with the Aqua model it never appeared. The (strange) work-around here was to remove the border and render it along with the shadow in the background pane. This is an unusual separation of a component from its border: but it should be visually indistinguishable for the user.

  • Because this popup exists only within the applet: it is constrained to the bounds of the applet. The original heavyweight model could appear anywhere on the monitor. (In fact: that was the original bug I'm trying to resolve -- it was appearing too far away.) So in this implementation we have to reposition the popup if it runs into the edge of the applet. In my experience this is not a major inconvenience to the user if the applet is large enough, but if you are working with a very small applet it might feel strange.
  • Conclusion

    I expect to further tweak the FilledComboBoxUI in coming weeks as I try to further improve it, but overall everything is shaping up well. There is no applet accompanying this article, but you can see these changes in action in this applet by interacting with the tooltips and comboboxes.

    This article focuses specifically on the PopupFactory and creating a lightweight alternative: and that effort appears to be finished.

    As a sidenote: you could also argue, "Who cares about applets?" The primary bug this article addresses only occurred in applets, but not in applications: so why fuss about applets? I attended a talk last week led by Roger Brinkley titled "Java Platform Now and the Future", and it seems safe to say the future of Java UI development is (at best) concentrated towards JavaFX. But this (my java.net repository) is not a business -- it's a hobby. And for the time being I'm not giving up on Swing quite yet. And in the mean time: this bug affected several of my articles/applets. So for those users brave enough to click through the security warnings and actually run my applets: I wanted to at least give them a decent experience.

    Monday, June 17, 2013

    Atelier EMF - Cr�ation et instanciation de mod�les avec Eclipse Modeling Framework (EMF)

    Un nouvel atelier consacr� � la cr�ation et l'instanciation de mod�les avec Eclipse Modeling Framework (EMF) est disponible � cette adresse : http://mbaron.developpez.com/tutoriels/eclipse/emf/creation-instanciation-modeles/

    L'atelier se d�compose en cinq exercices :
    • Exercice 1 : Cr�ation du mod�le EMF d'un carnet d'adresses
    • Exercice 2 : G�n�ration de codes Java
    • Exercice 3 : Cr�ation d'instances via l'�diteur g�n�r�
    • Exercice 4 : Cr�ation d'instances via l'API EMF : EarlyBinding
    • Exercice 5 : Manipulation du m�tamod�le Ecore : LateBinding

    Les trois premiers exercices sont basiques et rien de r�volutionnaires par rapport � ce que l'on peut trouver sur le net. Pour les exercices quatre et cinq, j'ai tent� d'�tre moins d�pendant de l'outil Eclipse. J'ai pr�f�r� explorer l'APIs d'EMF. C'est ainsi que pour l'exercice 5, je montre comment charger un mod�le Ecore et ses instances.

    N'h�sitez pas � me faire des retours s'il y a des choses que vous ne comprenez pas.

    Sunday, June 2, 2013

    Liens pratiques de la semaine

    Vous trouverez dans ce billet une s�lection de liens pratiques autour des technologies Java qui m'ont particuli�rement int�ress�es ces derni�res semaines. 

    Eclipse
    • Le deuxi�me billet sur quatre concernant l'internationalisation des applications Eclipse RCP pour la plateforme Eclipse 4.
    • L'�quipe d'OBEO vous propose un retour d'EclipseCon 2013 via une vid�o.
    • Un billet de Lars Vogel qui explique comment r�cup�rer les sources de la page Web d�di�e aux nouveaut�s de la plateforme Eclipse.
    • Si vous d�butez avec la plateforme Eclipse, ce billet est fait pour vous. Il pr�sente toutes les ressources documentaires pour d�buter et r�soudre ces probl�mes.
    • Une astuce qui explique comment nommer ces Workspaces afin de facilement les identifier quand plusieurs Eclipse sont ouverts.
    • NatTable du projet Eclipse Nebula fournit une version tr�s am�lior�e de la Table SWT. La version de NatTable est sortie en 1.0 (fonctionnalit�s de la version).
    • Une astuce pour am�liorer la rapidit� de la compl�tion de code. Par d�faut, il faut attendre 200ms, en r�duisant � 40ms vous devriez am�liorer vos performances ;-)
    Java
    • Une pr�sentation de GwtQuery (JQuery pour GWT) qui date mais peut �tre utile. Vous trouverez �galement la vid�o lors du Google I/O 2009.
    • Lors d'une session GWT au Google I/O 2013, il a �t� pr�sent� le futur de GWT. Notamment le nouveau site, le nouveau logo, l'int�gration continue via Jenkins. La vid�o est disponible ainsi que les transparents. Des debriefings de la conf�rence peuvent �tre trouv�s ici : Developpez.com, Sami Jaber, Zenika.
    NoSQL
    • Un article qui permet d'avoir les id�es claires sur les diff�rentes distributions Hadoop.
    • Angelo Zerr vous propose une s�rie de billet consacr� � l'utilisation de MongoDB dans une application Java EE.
    Divers
    • Un site qui permet d'apprendre GIT via l'exemple.
    • Un memento en image pour les outils de recherche de Google (moteur de recherche, Google Scholar...).
    • Un billet qui montre comment utiliser les modules XBee via une application Java.
    • Instagram permet d'embellir vos image. Instacode permettra quant � lui d'embellir vos codes.