Thinking in programming

Things I like to talk about programming

Archive for January 2009

Can “your” language beat this? – Part 1

with 2 comments

Important: This first post is discussed on JavaHispano.org

This series of posts is not intended to demonstrate the superiority of one language over others, the aim is to find the best way to write code snippets that a GUIs developer faces daily. When i said “the best way“, i mean a proper balance between flexibility and readability, which in my view, defines the quality of a language. The idea is that if you knows a language that allows to improve the way of codifying the snippet shown here (surely you knows), then you published that piece of code here, and then we will evaluate the best. As well are welcomes improved versions of the ones I have posted, and of course, comments in general.

The main reason why i choose JavaFX, is frankly because of i think that is the language that gives more agility to work with graphics (at the moment).

This first part aims to show how to bind two objects, in this case, the color of an object is determined by the text of a text field. If the text inside the text field is ‘aeiou’ then the circle will be filled with the green color, otherwise will be filled with the red color.

Note that understanding the processTheText function as the “controller”, so you can notice the complete separation between the view and the logic.

/*
 * DoItBetter1.fx
 *
 */

package doitbetter;

import javafx.scene.control.TextBox;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;

var theText = "";

Stage {
    title: "Binding between GUI controls"
    width: 400
    height: 200
    scene: Scene {
        content: HBox {
            spacing: 10
            content: [                
                TextBox{                    
                    text: bind theText with inverse
                }
                Circle{                    
                    radius: 10 centerY: 10
                    fill: bind processTheText(theText)
                }
            ]
        }
    }
}

function processTheText(auxText){
    if(auxText == "aeiou") Color.GREEN else Color.RED
}

Advertisements

Written by roger.padilla

January 15, 2009 at 18:11

Posted in Uncategorized

Tagged with

JavaFX, why?

with 6 comments

It’s not a secret that for a developer is a dream to be able to build an application, and without modify it, run it in the computer, in the cellphone, in the TV, in the car, in all the screens of the life.

However, why to create a new platform for this?: The main disadvantage of the languages with a high level of dissemination and longevity such as Java, is that these same qualities requires a strong backwards compatibility, which in turn limits its ability to evolve.

JavaFX was precisely designed to meet these demands, while provide a new and modern language, RIAs, developer-designer work flow in mind, multimedia, Swing 2.0, amazing Flash’s style animations, and all this without leaving Java! Version 1.0 has been focused on providing a very good support to work with animations, graphics and multimedia. In other words, has been created a very strong base on which to add graphics controls, business applications frameworks, and so on.

For some, JavaFX is coming too late, for others, this is just the beginning of a platform with a great potential. The first step was solid, from now on everything depends on Sun supports to this promising platform.

Written by roger.padilla

January 13, 2009 at 17:33

Posted in Java Swing, JavaFX

Tagged with ,

JavaFX v1.0 – Este es solo el comienzo!

with 2 comments

JavaFX 1.0 marca el primer paso de Sun en proveer una novedosa plataforma para crear Aplicaciones Sofisticadas de Internet y distribuirlas en todas las pantallas de tu vida!

JavaFX proporciona la libertad y la flexibilidad de crear RIAs (Rich Internet Aplications) y ejecutarlas en múltiples dispositivos electrónicos, incluyendo: teléfonos móviles, computadores personales, televisores, entre otros.

Principales características de la version 1.0 de JavaFX:

  • Una única plataforma RIA para todas las pantallas: Crear aplicaciones que puedan ser ejecutadas en computadores de escritorio, teléfonos móviles, navegadores de internet, empleando un modelo unificado de desarrollo y de despliegue.
  • Un Lenguaje los más cercano al Natural: JavaFX utiliza un lenguaje declarativo que permite describir fácilmente que debe hacer tu aplicación y como debe lucir.
  • Mercado más amplio: Distribuir RIAs fácilmente a través de miles de millones de dispositivos valiéndose de todo el poder de la Plataforma Java.
  • Facilitar el Flujo de Trabajo entre Diseñador y Programador: Acortar drásticamente el ciclo de producción para el diseño y el desarrollo de las aplicaciones.
  • Potente Entorno de Ejecución: Aproveche la extrema ubicuidad, el poder y la seguridad de la Maquina Virtual Java.
  • Ejecución Independiente del Navegador: Arrastrar y soltar una aplicación JavaFX desde el navegador para desplegar en el escritorio.
  • Compatibilidad con la tecnología Java: Preservar su inversión al permitir el uso de cualquier librería Java desde de una aplicación JavaFX.

La primera versión de JavaFX está realmente destinada a proveer una solida base para todos los avances venideros. Esta versión se ha enfocado en dar muy buen soporte al trabajo con animaciones, gráficos, multimedia, en otras palabras, se está creando una base muy robusta sobre la cual poder agregar Controles Gráficos (formularios, tablas, validadores, etc.), así como Frameworks para facilitar la creación de Aplicaciones de Gestión, Persistencia de Datos, etc. En este contexto se puede hacer una analogía a lo que sucedió con Flash y Flex, Flash es la base, Flex es el Framework para construir RIAs con Flash. JavaFX tiene un mayor musculo que Flash (el gran Universo Java), muy pronto vendrán muchos Componentes y Frameworks para utilizar con JavaFX.

Un aspecto muy importante de JavaFX es que no está restringido por compatibilidades con versiones preexistentes, lo cual da la libertad a sus diseñadores de crear e implementar el mejor diseño posible para ellos, facilitando también la evolución del Lenguaje, aquí la Capacidad de Evolucionar es directamente proporcional a la Libertad.

Como es normal, las primeras versiones tienden a mostrar lo básico y tienen muchos -nice to have- pendientes. Lo que no se puede negar es que JavaFX se ve muy, pero muy prometedor! Una de los aspectos que más me impacta es que la forma de codificar me parece mucho más ágil que en Flex y AS3, no conozco Silverlight aun. Sin mencionar todo el Universo Java comparado con el Mundillo Flash/Flex.

Las próximas versiones de JavaFX saldrán mucho más rápido, en unas cuantas semanas deberíamos tener una siguiente versión de JavaFX, mucho mejor rendimiento de los applets y un mejorado soporte en los entornos de desarrollo, en pocos meses el soporte oficial para Linux, entre otros.

Lo dicho, este es apenas el comienzo!

Una lectura muy recomendada acerca del Pasado, Presente y Futuro del Mundo Desktop en Java: http://www.pushing-pixels.org/?p=922
Enlace al oficial “Acerca de” de JavaFX: http://www.javafx.com/about/overview/

He publicado la noticia en JavaHispano.

Written by roger.padilla

January 8, 2009 at 12:44

Posted in JavaFX

Tagged with

SQL to add just the New Indexes (filtering the existing ones)

with one comment

Quick background

You have several instances of a database, and you adds indexes to improve the performance. Sometimes you does not adds these indexes in all the instances, or for some other reason you need to be sure that all the databases are up to date with the same indexes.

Solution

This document expose a way to extract the indexes from an up to date database (Source Database) and to add just the new Indexes into another database (filtering the already existing ones) by comparing the indexes in each database.

The workflow should be as follows:

  1. In the below SQL scripts, replace ‘source_database_name’ and ‘destination_database_name’ with the name of the database in the source and destination database respectively.

  2. Run the query 1 in the Source Database and export the resultset as a CSV file in your local hard drive. By default the 2nd script in the query 2 look for the file ‘C:/Indexes_In_Src_DB.csv’.
  3. Run the query 2 in the Destination Database. This will create some auxiliar databases, which purpose is to store information util to find the not existing indexes.
    Be sure the you’ve named the CSV file as ‘C:/Indexes_In_Src_DB.csv’ or just change that string in the 2nd script in the query 2 by the name you’ve used.
  4. Run the query 3 in the Destination Database, export the resultset as a html file in your local hard drive. Open that html file, copy all the statements and execute those in that same database (Destination Database). This will add the new indexes.
  5. Run the query 4 in the Destination Database. This will delete the auxiliar databases.

Note: To export a resultset in MySQL Query Browser, execute a query, then do right click in the table -> ‘Export Resultset’ -> ‘Export as HTML File’.

Queries

  1. Produce the SQL to Create the Indexes that are in the Source Database

    SELECT
        CONCAT(
            ‘ALTER TABLE `’,
            TABLE_NAME,
            ‘` ‘,
            ‘ADD ‘,
            IF(NON_UNIQUE = 1,
                CASE UPPER(INDEX_TYPE)
                    WHEN ‘FULLTEXT’ THEN ‘FULLTEXT INDEX’
                    WHEN ‘SPATIAL’ THEN ‘SPATIAL INDEX’
                    ELSE CONCAT(‘INDEX `’, INDEX_NAME, ‘` USING ‘, INDEX_TYPE)
                END,
                IF(UPPER(INDEX_NAME) = ‘PRIMARY’,
                    CONCAT(‘PRIMARY KEY USING ‘, INDEX_TYPE),
                    CONCAT(‘UNIQUE INDEX `’, INDEX_NAME, ‘` USING ‘, INDEX_TYPE)
                )
            ),
            ‘(‘,
            GROUP_CONCAT(
                DISTINCT
                    CONCAT(‘`’, COLUMN_NAME, ‘`’)
                ORDER BY SEQ_IN_INDEX ASC
                SEPARATOR ‘, ‘
            ),
            ‘);’
         ) AS ‘Show_Add_Indexes’
    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = ‘source_database_name’
    GROUP BY TABLE_NAME, INDEX_NAME
    ORDER BY TABLE_NAME ASC, INDEX_NAME ASC

  2. Create Auxiliar Tables

    /* Temporary Table to store all the Indexes presents in the Source Database */

    DROP TABLE IF EXISTS `indexes_in_src_db`;

    CREATE TABLE `indexes_in_src_db` (
        `TABLE_NAME` VARCHAR(100) NOT NULL,
        `INDEX_NAME` VARCHAR(100) NOT NULL,
        `NON_UNIQUE` TINYINT(1) NOT NULL,
        `INDEX_TYPE` VARCHAR(100) NOT NULL,
        `COLUMNS_NAMES` VARCHAR(230) NOT NULL,
        UNIQUE KEY `table_name_index_name` USING BTREE(`TABLE_NAME`,`INDEX_NAME`),
        UNIQUE KEY `table_name_columns_names` USING BTREE(`TABLE_NAME`,`COLUMNS_NAMES`)
    ) ENGINE=MYISAM DEFAULT CHARSET=utf8;

    /* END */

    /* Load the indexes from the CSV file in the ‘indexes_in_src_db’ table */

    LOAD DATA INFILE ‘C:/Indexes_In_Src_DB.csv’
        INTO TABLE `indexes_in_src_db`
            FIELDS TERMINATED BY ‘,’
            OPTIONALLY ENCLOSED BY ‘"’
            LINES TERMINATED BY rn
            IGNORE 1 LINES;

    /* END */

    /* Temporary Table to store the Indexes presents in the Destination Database */

    DROP TABLE IF EXISTS `indexes_in_dest_db`;

    CREATE TABLE `indexes_in_dest_db` (
        `TABLE_NAME` VARCHAR(100) NOT NULL,
        `INDEX_NAME` VARCHAR(100) NOT NULL,
        `NON_UNIQUE` TINYINT(1) NOT NULL,
        `INDEX_TYPE` VARCHAR(100) NOT NULL,
        `COLUMNS_NAMES` VARCHAR(230) NOT NULL,
        UNIQUE KEY `table_name_index_name` USING BTREE(`TABLE_NAME`,`INDEX_NAME`),
        UNIQUE KEY `table_name_columns_names` USING BTREE(`TABLE_NAME`,`COLUMNS_NAMES`)
    ) ENGINE=MYISAM DEFAULT CHARSET=utf8;

    /* END */

    /* Fill the ‘indexes_in_dest_db’ table with All the Indexes presents in the Destination DB */

    INSERT INTO `indexes_in_dest_db`
    SELECT
       
            TABLE_NAME,
            INDEX_NAME,
            NON_UNIQUE,
            INDEX_TYPE,
            GROUP_CONCAT(
                DISTINCT
                    CONCAT(‘`’, COLUMN_NAME, ‘`’)
                ORDER BY SEQ_IN_INDEX ASC
                SEPARATOR ‘,’
            ) AS COLUMNS_NAMES

    FROM information_schema.STATISTICS
    WHERE TABLE_SCHEMA = ‘destination_database_name’
    GROUP BY TABLE_NAME, INDEX_NAME;

    /* END */

    /* Temporary Table to store the Indexes presents in Src Database that are not presents in the Destination Database */

    DROP TABLE IF EXISTS `indexes_in_src_db_not_in_dest_db`;

    CREATE TABLE `indexes_in_src_db_not_in_dest_db` (
        `TABLE_NAME` VARCHAR(100) NOT NULL,
        `INDEX_NAME` VARCHAR(100) NOT NULL,
        `NON_UNIQUE` TINYINT(1) NOT NULL,
        `INDEX_TYPE` VARCHAR(100) NOT NULL,
        `COLUMNS_NAMES` VARCHAR(230) NOT NULL,
        UNIQUE KEY `table_name_index_name` USING BTREE(`TABLE_NAME`,`INDEX_NAME`),
        UNIQUE KEY `table_name_columns_names` USING BTREE(`TABLE_NAME`,`COLUMNS_NAMES`)
    ) ENGINE=MYISAM DEFAULT CHARSET=utf8;

    /* Fill the ‘indexes_in_src_db_not_in_dest_db’ table with All the Indexes presents in the Src DB that are not presents in the Dest DB */

    INSERT INTO `indexes_in_src_db_not_in_dest_db`
    SELECT
            SDB.TABLE_NAME,
            SDB.INDEX_NAME,
            SDB.NON_UNIQUE,
            SDB.INDEX_TYPE,
            SDB.COLUMNS_NAMES
    FROM indexes_in_src_db SDB
    WHERE ROW(SDB.TABLE_NAME,SDB.COLUMNS_NAMES) NOT IN(SELECT DDB.TABLE_NAME,DDB.COLUMNS_NAMES FROM indexes_in_dest_db AS DDB)
    GROUP BY SDB.TABLE_NAME, SDB.INDEX_NAME
    ORDER BY SDB.TABLE_NAME ASC, SDB.INDEX_NAME ASC;

    /* END */

  3. Produce the SQL to Add the New Indexes into the Destination Database

    SELECT
        CONCAT(
            ‘ALTER TABLE `’,
            TABLE_NAME,
            ‘` ‘,
            ‘ADD ‘,
            IF(NON_UNIQUE = 1,
                CASE UPPER(INDEX_TYPE)
                    WHEN ‘FULLTEXT’ THEN ‘FULLTEXT INDEX’
                    WHEN ‘SPATIAL’ THEN ‘SPATIAL INDEX’
                    ELSE CONCAT(‘INDEX `’, INDEX_NAME, ‘` USING ‘,INDEX_TYPE)
                END,
                IF(UPPER(INDEX_NAME) = ‘PRIMARY’,
                    CONCAT(‘PRIMARY KEY USING ‘, INDEX_TYPE),
                    CONCAT(‘UNIQUE INDEX `’, INDEX_NAME, ‘` USING ‘,INDEX_TYPE)
                )
            ),
            ‘(‘,
            COLUMNS_NAMES,
            ‘);’
         ) AS ‘ADD_Not_Existing_Indexes’
    FROM `indexes_in_src_db_not_in_dest_db`
    GROUP BY TABLE_NAME, INDEX_NAME
    ORDER BY TABLE_NAME ASC, INDEX_NAME ASC;

  4. Drop the auxiliar tables

    DROP TABLE IF EXISTS `indexes_in_src_db`;
    DROP TABLE IF EXISTS `indexes_in_dest_db`;
    DROP TABLE IF EXISTS `indexes_in_src_db_not_in_dest_db`;

Written by roger.padilla

January 5, 2009 at 14:15

Posted in MySQL

Tagged with , ,