sábado, 28 de julho de 2012

ETL/RDF + CONSULTA SPARQL DO BDTICKETS

                     CLASSES PARA FAZER ETL E CONSULTAS SPARQL RESPECTIVAMENTE








SAÍDAS DAS CONSULTAS SPARQL







PARTE DO RDF GERADO PELO ETL

HELLOWORD - RDF/SPARQL

                                                                   ATIVIDADE:
CRIAR UM ARQUIVO RDF E CONSULTA-LO ATRAVÉS DA QUERY LANGUAGE SPARQL
OBS:NÓS UTILIZAMOS A API JENA.





SAÍDA DA CONSULTA SPARQL

PARA A PRÓXIMO ATIVIDADE, DEVEREMOS FAZER UM ETL DE PARTE DO BDTICKETS PARA UM RDF E REALIZAR CONSULTAS

Aplicativo Android WebService JSON

APLICATIVO ANDROID NO EMULADOR


                                    REALIZANDO BUSCA PELO NÚMERO DE DIAS

RESULTADO DA BUSCA


CLASSES DO APLICATIVO








                                                Dados do banco no dispositivo android


 

sexta-feira, 6 de julho de 2012

ATA-06-07-2012

Para a próxima etapa:
Derevemos fazer um mini-alicativo android para ver os espetaculos em exibição no momento Especificações: o aplicativo deve conter a tabela espetaculo, a consulta dos espetaculos deve aconter no web service passando um Json. Ao receber uma consulta, o aplicativo deverá carregar as consultas na tabela do SQLite.

Etapas necessárias e divisão de atividades:
  • Modelar e criar banco SqLite -Lucas
  • Conectar e realizar operações sobre o SqLite numa aplicação Android - Márcio
  • Criar um WebService em Java - João Paulo
  • Consumir um WebService em Java - Rick
  • Estudar o GSON, que é a API de utilização do JSON do Android - Diego Henrique

CONSULTA DESAFIO PENTAHO-MDX

CONSULTA DESAFIO PENTAHO-MDX

CONSULTA DESAFIO RELACIONAL

CONSULTA DESAFIO

CUBO + XML

CUBO + XML

CÓDIGO ETL

CODIGO JAVA DO ETL:

package popular;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.HashMap;

/**
 *
 * @author João Paulo
 */
public class ETL {

    private static final int COMMIT = 200;
    private static final int COMUM = 1;
    private static final int VIP = 2;
    private static final int ROWS = Integer.MIN_VALUE;

    public static void commitAndRestart() {
    }

    public static void main(String[] args) {
        try {
            //Conn Modelo Relacional
            Connection connBd1 = DriverManager.getConnection("jdbc:mysql://localhost/bd_tickets_desenv?user=root&password=");
            Statement stmtBd1 = connBd1.createStatement();
            stmtBd1.setFetchSize(ROWS);

            //Conn Modelo Estrela
            Connection connBd2 = DriverManager.getConnection("jdbc:mysql://localhost/data_mart_reservas?user=root&password=");
            Statement stmtBd2 = connBd2.createStatement();
            stmtBd2.setFetchSize(ROWS);
            connBd2.setAutoCommit(false);

            //Configurações Adicionais
            stmtBd2.executeUpdate("SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO'");

            /*
             * -- DIMENSÃO CLIENTE --
             */
            stmtBd2.executeUpdate("INSERT INTO cliente (id_cliente, nome, id_cliente_neg) VALUES (0, 'Nenhum', 0)");
            ResultSet rsCli = stmtBd1.executeQuery("SELECT id_cliente, nome FROM cliente");
            int count_cliente = 1;
            while (rsCli.next()) {
                int id_cliente = rsCli.getInt("id_cliente");
                String nome = rsCli.getString("nome");

                stmtBd2.executeUpdate("INSERT INTO cliente (id_cliente, nome, id_cliente_neg) VALUES (" + count_cliente + ", '" + nome + "', " + id_cliente + ")");
                System.out.println("Cliente: " + count_cliente);
                count_cliente++;
                if (count_cliente % COMMIT == 0) {
                    connBd2.commit();
                }
            }
            connBd2.commit();



            /*
             * -- DIMENSÃO TEMPO --
             */
            stmtBd2.executeUpdate("INSERT INTO tempo (id_tempo, ano, mes, dia) VALUES (0, -1, -1, -1)");
            HashMap<String, Integer> datas = new HashMap<String, Integer>();
            int count_tempo = 1;
            //Parte 1 - Datas de Reserva:
            ResultSet rsTmp = stmtBd1.executeQuery("SELECT horario_reserva FROM reserva");
            while (rsTmp.next()) {
                String[] tempoSplit = rsTmp.getString("horario_reserva").split("-");

                String strAux[] = tempoSplit[2].split(" ");

                int dia = Integer.parseInt(strAux[0]);
                int mes = Integer.parseInt(tempoSplit[1]);
                int ano = Integer.parseInt(tempoSplit[0]);

                //Controle datas repetidas:
                String keyData = ano + "-" + mes + "-" + dia;
                if (!datas.containsKey(keyData)) {
                    datas.put(keyData, dia);

                    stmtBd2.executeUpdate("INSERT INTO tempo (id_tempo, ano, mes, dia) VALUES (" + count_tempo + ", " + ano + ", " + mes + ", " + dia + ")");
                    System.out.println("Tempo: " + count_tempo);
                    count_tempo++;
                    if (count_tempo % COMMIT == 0) {
                        connBd2.commit();
                    }
                }
            }
            //Parte 2 - Datas de Compra no Horario da Peça:
            rsTmp = stmtBd1.executeQuery("SELECT horario_inicio FROM espetaculo");
            while (rsTmp.next()) {
                String[] tempoSplit = rsTmp.getString("horario_inicio").split("-");

                String strAux[] = tempoSplit[2].split(" ");

                int dia = Integer.parseInt(strAux[0]);
                int mes = Integer.parseInt(tempoSplit[1]);
                int ano = Integer.parseInt(tempoSplit[0]);

                //Controle datas repetidas:
                String keyData = ano + "-" + mes + "-" + dia;
                if (!datas.containsKey(keyData)) {
                    datas.put(keyData, dia);

                    stmtBd2.executeUpdate("INSERT INTO tempo (id_tempo, ano, mes, dia) VALUES (" + count_tempo + ", " + ano + ", " + mes + ", " + dia + ")");
                    System.out.println("Tempo: " + count_tempo);
                    count_tempo++;
                    if (count_tempo % COMMIT == 0) {
                        connBd2.commit();
                    }
                }
            }
            connBd2.commit();



            /*
             * -- DIMENSÃO LUGAR --
             */
            stmtBd2.executeUpdate("INSERT INTO lugar (id_lugar, bairro, cep, logradouro, id_lugar_neg) VALUES (0, 'Nenhum', 'Nenhum', 'Nenhum', 0)");
            ResultSet rsLug = stmtBd1.executeQuery("SELECT id_endereco, bairro, cep, logradouro FROM endereco");
            int count_lugar = 1;
            while (rsLug.next()) {
                int id_lugar = rsLug.getInt("id_endereco");
                String bairro = rsLug.getString("bairro");
                String cep = rsLug.getString("cep");
                String logradouro = rsLug.getString("logradouro");

                stmtBd2.executeUpdate("INSERT INTO lugar (id_lugar, bairro, cep, logradouro, id_lugar_neg) VALUES (" + count_lugar + ", '" + bairro + "', '" + cep + "', '" + logradouro + "', " + id_lugar + ")");
                System.out.println("Lugar: " + count_lugar);
                count_lugar++;
                if (count_lugar % COMMIT == 0) {
                    connBd2.commit();
                }
            }
            connBd2.commit();


            /*
             * -- DIMENSÃO ESPETACULO --
             */
            stmtBd2.executeUpdate("INSERT INTO espetaculo (id_espetaculo, id_espetaculo_neg) VALUES (0, 0)");
            ResultSet rsEsp = stmtBd1.executeQuery("SELECT id_espetaculo, titulo FROM espetaculo");
            int count_espetaculo = 1;
            while (rsEsp.next()) {
                int id_espetaculo = rsEsp.getInt("id_espetaculo");
                String titulo = rsEsp.getString("titulo");

                stmtBd2.executeUpdate("INSERT INTO espetaculo (id_espetaculo, titulo, id_espetaculo_neg) VALUES (" + count_espetaculo + ", '" + titulo + "', " + id_espetaculo + ")");
                System.out.println("Espetaculo: " + count_espetaculo);
                count_espetaculo++;
                if (count_espetaculo % COMMIT == 0) {
                    connBd2.commit();
                }
            }
            connBd2.commit();



            /*
             * -- DIMENSÃO PERFIL_CLIENTE --
             */
            stmtBd2.executeUpdate("INSERT INTO perfil_cliente (id_perfil_cliente, perfil) VALUES (0, 'Nenhum')");
            stmtBd2.executeUpdate("INSERT INTO perfil_cliente (id_perfil_cliente, perfil) VALUES (" + COMUM + ", 'Comum')");
            stmtBd2.executeUpdate("INSERT INTO perfil_cliente (id_perfil_cliente, perfil) VALUES (" + VIP + ", 'VIP')");
            System.out.println("Perfil Cliente OK!");
            connBd2.commit();

            /*
             * -- DIMENSÃO PREÇO --
             */
            stmtBd2.executeUpdate("INSERT INTO preco (id_preco, preco_base) VALUES (0, 0)");
            ResultSet rsPrc = stmtBd1.executeQuery("SELECT distinct preco_base FROM espetaculo");
            int count_preco = 1;
            while (rsPrc.next()) {
                Double preco = rsPrc.getDouble("preco_base");

                stmtBd2.executeUpdate("INSERT INTO preco (id_preco, preco_base) VALUES (" + count_preco + ", " + preco + ")");
                System.out.println("Preço: " + count_preco);
                count_preco++;
                if (count_preco % COMMIT == 0) {
                    connBd2.commit();
                }
            }
            connBd2.commit();


            /*
             * -- TABELA FATO - VENDAS BILHETES --
             */
            //Query que irá buscar os dados da stagind da tabela fato
            StringBuilder qryFato = new StringBuilder();
            qryFato.append("  SELECT");
            qryFato.append("    !ISNULL(bl.id_reserva) as qtd_reservas,");
            qryFato.append("    1 as qtd_vendidos,");
            qryFato.append("    es.preco_base as val_faturamento,");
            qryFato.append("    es.id_espetaculo,");
            qryFato.append("    IFNULL(bl.id_cliente, 0) as id_cliente,");
            qryFato.append("    IF(ISNULL(bl.id_reserva), es.horario_inicio, rs.horario_reserva) as tempo,");
            qryFato.append("    IF(ISNULL(bl.id_cliente), 0, en.id_endereco) as id_lugar,");
            qryFato.append("    es.preco_base as preco,");
            qryFato.append("    bl.tipo_bilhete as perfil_cliente");
            qryFato.append("  FROM");
            qryFato.append("    bilhete bl");
            qryFato.append("    JOIN espetaculo es ON bl.id_espetaculo = es.id_espetaculo");
            qryFato.append("    LEFT JOIN reserva rs ON bl.id_reserva = rs.id_reserva");
            qryFato.append("    JOIN cliente cl ON IF(ISNULL(bl.id_cliente), rs.id_cliente, bl.id_cliente) = cl.id_cliente");
            qryFato.append("    JOIN endereco en ON cl.id_endereco = en.id_endereco");
            qryFato.append("  WHERE");
            qryFato.append("    bl.status_vendido = 'S'");

            ResultSet rsVendas = stmtBd1.executeQuery(qryFato.toString());
           
            ResultSet rsLookup = null;
            int count_vendas = 1;

            while (rsVendas.next()) {
                //Lookup em espetáculo
                int id_espetaculo_neg = rsVendas.getInt("id_espetaculo");
                rsLookup = stmtBd2.executeQuery("SELECT id_espetaculo FROM espetaculo WHERE id_espetaculo_neg = " + id_espetaculo_neg + " LIMIT 1");
                rsLookup.next();
                int id_espetaculo = rsLookup.getInt("id_espetaculo");
                rsLookup.next();
                //rsLookup.close();

                //Lookup em cliente
                int id_cliente_neg = rsVendas.getInt("id_cliente");
                rsLookup = stmtBd2.executeQuery("SELECT id_cliente FROM cliente WHERE id_cliente_neg = " + id_cliente_neg + " LIMIT 1");
                rsLookup.next();
                int id_cliente = rsLookup.getInt("id_cliente");
                rsLookup.next();
                //rsLookup.close();

                //Lookup em tempo
                String[] tempoSplit = rsVendas.getString("tempo").split("-");
                String strAux[] = tempoSplit[2].split(" ");
                int dia = Integer.parseInt(strAux[0]);
                int mes = Integer.parseInt(tempoSplit[1]);
                int ano = Integer.parseInt(tempoSplit[0]);
                rsLookup = stmtBd2.executeQuery("SELECT id_tempo FROM tempo WHERE dia = " + dia + " AND mes = " + mes + " AND ano = " + ano + " LIMIT 1");
                rsLookup.next();
                int id_tempo = rsLookup.getInt("id_tempo");
                rsLookup.next();
                //rsLookup.close();

                //Lookup em lugar
                int id_lugar_neg = rsVendas.getInt("id_lugar");
                rsLookup = stmtBd2.executeQuery("SELECT id_lugar FROM lugar WHERE id_lugar_neg = " + id_lugar_neg + " LIMIT 1");
                rsLookup.next();
                int id_lugar = rsLookup.getInt("id_lugar");
                rsLookup.next();
                //rsLookup.close();

                //Lookup em perfil_cliente
                String perfil_cliente = rsVendas.getString("perfil_cliente");
                int id_perfil_cliente = perfil_cliente.equals("C") ? COMUM : VIP;
                rsLookup.next();
                //rsLookup.close();

                //Lookup em preco
                int id_preco;
                if (id_perfil_cliente == VIP) {
                    id_preco = 0;
                } else {
                    double preco = rsVendas.getDouble("preco");
                    rsLookup = stmtBd2.executeQuery("SELECT id_preco FROM preco WHERE preco_base = " + preco + " LIMIT 1");
                    rsLookup.next();
                    id_preco = rsLookup.getInt("id_preco");
                }
                //rsLookup.close();
                rsLookup.next();
                //Measure valFaturamento
                double val_faturamento = id_perfil_cliente == COMUM ? rsVendas.getDouble("val_faturamento") : 0;

                //Measure qtdVendidos
                int qtd_vendidos = 1;

                //Measure qtdReservas
                int qtd_reservas = rsVendas.getInt("qtd_reservas");


                //Verifica se ja existe uma venda para as dimensões da iteração:
                rsLookup = stmtBd2.executeQuery("SELECT * FROM vendas_bilhetes WHERE id_espetaculo = " + id_espetaculo + " AND id_cliente = " + id_cliente + " AND id_tempo = " + id_tempo + " AND id_lugar = " + id_lugar + " AND id_preco = " + id_preco + " AND id_perfil_cliente = " + id_perfil_cliente + " LIMIT 1");
                if (rsLookup.next()) {
                    //se ja houver, incrementa os valores deste fato
                    double val_faturamento_acumul = rsLookup.getDouble("val_faturamento") + val_faturamento;
                    int qtd_vendidos_acumul = rsLookup.getInt("qtd_vendidos") + 1;
                    int qtd_reservas_acumul = rsLookup.getInt("qtd_reservas") + qtd_reservas;
                    stmtBd2.executeUpdate("UPDATE vendas_bilhetes SET val_faturamento = " + val_faturamento_acumul + ", qtd_vendidos = " + qtd_vendidos_acumul + ", qtd_reservas = " + qtd_reservas_acumul + " WHERE id_espetaculo = " + id_espetaculo + " AND id_cliente = " + id_cliente + " AND id_tempo = " + id_tempo + " AND id_lugar = " + id_lugar + " AND id_preco = " + id_preco + " AND id_perfil_cliente = " + id_perfil_cliente);

                    //rsLookup.next();
                } else {
                    //senão, insere o novo fato
                    stmtBd2.executeUpdate("INSERT INTO vendas_bilhetes (id_espetaculo, id_cliente, id_tempo, id_lugar, id_preco, id_perfil_cliente, val_faturamento, qtd_vendidos, qtd_reservas) VALUES (" + id_espetaculo + ", " + id_cliente + ", " + id_tempo + ", " + id_lugar + ", " + id_preco + ", " + id_perfil_cliente + ", " + val_faturamento + ", " + qtd_vendidos + ", " + qtd_reservas + ")");
                }

                System.out.println("Vendas: " + count_vendas);
                count_vendas++;
                if (count_vendas % COMMIT == 0) {
                    System.out.println("Commit");
                    connBd2.commit();
                }
            }
            connBd2.commit();

        } catch (Exception ex) {
            ex.printStackTrace();
            System.err.println(ex.getMessage());
        }

    }
}

STARSCHEMA

DIAGRAMA ENTIDADE RELACIONAMENTO
MODELO STARSCHEMA