Package com.GestDB.convert

Source Code of com.GestDB.convert.Importar

/*
* Importar.java
*
* Created on 2004
* Created by Arsenio Molinero
* Copyright (C) 2004, 2005 Arsenio Molinero
*
* GestDB - a Java multi database client
*
* This file is part of GestDB.
*
* GestDB is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* GestDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GestDB; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

package com.GestDB.convert;

import com.GestDB.swing.*;
import com.GestDB.Gestor;
import com.GestDB.general.Trackbug;
import com.utils.FiltroArchivos;
import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import javax.swing.*;

/**
*
* @author  amolinero
*/
public class Importar extends java.lang.Thread {
   
    /** Creates a new instance of Importar */
    public Importar(boolean esDirectorio, boolean esQuery, File Archivo,
        boolean tienePrimeraLineaConNombres, String SepColumnas,
        String DelimitadorTexto, boolean EliminarRegistros,
        boolean conCommit, int RegistrosCommit, String jdbcDriverClass,
        String jdbcDriverURL, String user, String password, Properties propiedades, iframeProgressBar pbar)
    {
        this.esDirectorio = esDirectorio;
        this.esQuery = esQuery;
        this.Archivo = Archivo;
        this.tienePrimeraLineaConNombres = tienePrimeraLineaConNombres;
        if(SepColumnas != null && SepColumnas.trim().length() > 0 && SepColumnas.trim().equals("\\t"))
            this.SepColumnas = "\t";
        else
            this.SepColumnas = SepColumnas;
        this.DelimitadorTexto = DelimitadorTexto;
        this.EliminarRegistros = EliminarRegistros;
        this.conCommit = conCommit;
        this.RegistrosCommit = RegistrosCommit;
        this.jdbcDriverClass = jdbcDriverClass;
        this.jdbcDriverURL = jdbcDriverURL;
        this.user = user;
        this.password = password;
        this.propiedades = propiedades;
        this.pbar = pbar;
    }
   
    public Importar() {
    }
   
    public void setTexto(boolean estexto)
    {
        esTexto = estexto;
    }
   
    public void run() {
        Connection connection = null;
        DatabaseMetaData dmd = null;
        Statement stmt = null;

        if(esTexto)
            System.out.println(Gestor.GetLiteral("importar.importing_data","Importando datos"));

        try {
            Class.forName(jdbcDriverClass);
            if(user != null && user.trim().length() != 0)
                connection = DriverManager.getConnection(jdbcDriverURL, user, password);
            else
                connection = DriverManager.getConnection(jdbcDriverURL);

            dmd = connection.getMetaData();
            connection.setAutoCommit(false);

            if(esQuery)
                stmt = connection.createStatement();
           
            if(!esDirectorio)
            {
                if(esTexto)
                    System.out.println(Gestor.GetLiteral("importar.process","Procesando") + " " + Archivo.getName());
                else
                {
                    pbar.setMaximum(1);
                    pbar.setMensaje(Gestor.GetLiteral("importar.process","Procesando") + " " + Archivo.getName());
                }
               
                if(esQuery)
                    procesaTablaQuery(connection, stmt, Archivo);
                else
                    procesaTablaTXT(connection, dmd, Archivo);
                if(esTexto)
                    System.out.println(Gestor.GetLiteral("importar.process_finish","Fin proceso"));
                else
                {
                    pbar.setValue(1);
                }
                try {
                    connection.commit();
                } catch(java.sql.SQLException sqle4)
                {
                    ;
                } // fin del catch
            }
            else
            {
                String extension = ".dat";
                if(esQuery)
                    extension = ".sql";
                FiltroArchivos fa = new FiltroArchivos(extension);
                File archivos[] = Archivo.listFiles(fa);
                if( archivos != null || archivos.length > 0)
                {
                    if(!esTexto)
                        pbar.setMaximum(archivos.length);
                    if(esQuery)
                    {
                        for(int i = 0; i < archivos.length; i++)
                        {
                            if(esTexto)
                                System.out.println(Gestor.GetLiteral("importar.process","Procesando") + "(" + (i+1) +
                                    "/" + archivos.length + ") " + archivos[i].getName());
                            else
                            {
                                pbar.setMensaje(Gestor.GetLiteral("importar.process","Procesando") + " " + archivos[i].getName());
                                pbar.setValue(i);
                            }
                            procesaTablaQuery(connection, stmt, archivos[i]);
                            try {
                                connection.commit();
                            } catch(java.sql.SQLException sqle4)
                            {
                                ;
                            } // fin del catch
                        }
                    }
                    else
                    {
                        for(int i = 0; i < archivos.length; i++)
                        {
                            if(esTexto)
                                System.out.println(Gestor.GetLiteral("importar.process","Procesando") + "(" + (i+1) +
                                    "/" + archivos.length + ") " + archivos[i].getName());
                            else
                            {
                                pbar.setMensaje(Gestor.GetLiteral("importar.process","Procesando") + " " + archivos[i].getName());
                                pbar.setValue(i);
                            }
                            procesaTablaTXT(connection, dmd, archivos[i]);
                            try {
                                connection.commit();
                            } catch(java.sql.SQLException sqle4)
                            {
                                ;
                            } // fin del catch
                        }
                    }
                } // fin del if( archivos != null || archivos.length > 0)
            } // fin del else de if(!esDirectorio)
           
            if(esQuery)
            {
                if(ResultadosQuerys.size() > 0)
                {
                    if(esTexto)
                    {
                        System.out.println(Gestor.GetLiteral("importar.error_1","Errores producidos Durante la importaci�n."));
                        System.out.println("Error saved in " + sArchivoErrores);
                    }
                    else
                    {
                        // tiene que mostar una tabla con los errores.
                        JDialog jd = new JDialog();
                        jd.setModal(false);
                        jd.setTitle(Gestor.GetLiteral("importar.error_1","Errores producidos Durante la importaci�n.") + " " + numQuerysError + " " + Gestor.GetLiteral("importar.error_2","errores de") + " " + numQuerys + " querys");
                        javax.swing.JScrollPane jsp = new JScrollPane();
                        javax.swing.JTable JTable1 = new javax.swing.JTable();
                        tmodelTabla tmt1 = new tmodelTabla();
                        String [] columnas = { Gestor.GetLiteral("importar.file","Archivo"),"SQL",
                            Gestor.GetLiteral("gestor.error_1","Error") };
                        Class [] tipoColumnas = { String.class,String.class,String.class };
                        tmt1.CargaDatos(columnas, tipoColumnas ,ResultadosQuerys);
                        JTable1.setModel(tmt1);
                        JTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
                        jsp.setViewportView(JTable1);
                        jd.getContentPane().setLayout(new java.awt.BorderLayout());
                        jd.getContentPane().add(jsp,java.awt.BorderLayout.CENTER);
                        if(numQuerysError > 1000)
                        {
                            JLabel jl1 = new JLabel(Gestor.GetLiteral("importar.error_7","Se est\u00E1n visualizando los 1000 primeros errores. Para verlos todos visualice el archivo") + ": " + sArchivoErrores);
                            jd.getContentPane().add(jl1,java.awt.BorderLayout.NORTH);
                        }
                        /*
                        JButton jb = new JButton(Gestor.GetLiteral("conexion.button_save","Guardar"));
                        jb.addActionListener(new java.awt.event.ActionListener() {
                            public void actionPerformed(java.awt.event.ActionEvent evt) {
                                // Tiene que crear un archivo con los datos del vector
                                try {
                                    String sArchivo = "ErroresSqlImportar.txt";
                                    javax.swing.JFileChooser jfc = new javax.swing.JFileChooser();
                                    jfc.setFileSelectionMode(jfc.FILES_ONLY);
                                    jfc.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
                                    if(propiedades.containsKey("conexion.importar.ultimo_dir"))
                                        jfc.setCurrentDirectory(new File((String)propiedades.get("conexion.importar.ultimo_dir")));
                                    if(jfc.showOpenDialog(((JButton)evt.getSource())) == javax.swing.JFileChooser.APPROVE_OPTION)
                                    {
                                        propiedades.put("conexion.importar.ultimo_dir", jfc.getCurrentDirectory().getAbsolutePath());
                                        sArchivo = jfc.getSelectedFile().getAbsolutePath();
                                    }                               
                                    FileOutputStream fout = new FileOutputStream(sArchivo);
                                    Vector vRow = null;
                                    String stemp = null;
                                    for(int i=0,j=ResultadosQuerys.size();i<j;i++)
                                    {
                                        vRow = (Vector)ResultadosQuerys.elementAt(i);
                                        stemp = ((String)vRow.elementAt(0)) + "|" + ((String)vRow.elementAt(1)) + "|" +
                                            ((String)vRow.elementAt(2)) + ((char)13) + ((char)10);
                                        fout.write(stemp.getBytes());
                                    }
                                    fout.close();
                                }catch(Exception e)
                                {
                                    System.out.println(Gestor.GetLiteral("gestor.error_1","Error") + ": " + e.getMessage());
                                }
                            }
                        });
                        jd.getContentPane().add(jb,java.awt.BorderLayout.NORTH);
                         */
                        jd.pack();
                        jd.setVisible(true);
                    }
                }
                else
                {
                    if(esTexto)
                        System.out.println(Gestor.GetLiteral("importar.import_ok","La importaci�n ha sido satisfactorio. Se han importado") + " " + numQuerys + " querys");
                    else
                    {
                        al = new Alerta(new javax.swing.JDialog(),Gestor.GetLiteral("gestor.alert","Atenci�n"),true,
                            Gestor.GetLiteral("importar.import_ok","La importaci�n ha sido satisfactorio. Se han importado") +
                            " " + numQuerys + " querys",Alerta.OK);
                        al.setVisible(true);
                    }
                }
            }
            else
            {
                if(esTexto)
                    System.out.println(sMensaje);
                else
                {
                    al = new Alerta(new javax.swing.JDialog(),Gestor.GetLiteral("importar.import_result","Resultados de la importacion de datos"),
                        true,sMensaje,Alerta.OK);
                    al.setVisible(true);
                }
            }           
           
            connection.commit();
        } catch(java.sql.SQLException ex)
        {
            if(esTexto)
                System.out.println(Gestor.GetLiteral("gestor.error_1","Error") + ": " + ex.getMessage());
            else
            {
                al = new Alerta(new javax.swing.JDialog(),Gestor.GetLiteral("gestor.error_1","Error"),true,ex.getMessage(),Alerta.OK);
                al.setVisible(true);
            }
            ex.printStackTrace();
        } catch(java.lang.ClassNotFoundException cnfe)
        {
            if(esTexto)
                System.out.println(Gestor.GetLiteral("gestor.error_1","Error") + ": " + cnfe.getMessage());
            else
            {
                al = new Alerta(new javax.swing.JDialog(),Gestor.GetLiteral("gestor.error_1","Error"),true,cnfe.getMessage(),Alerta.OK);
                al.setVisible(true);
            }
        }
        try {
            if(esQuery && stmt != null)
          stmt.close();
            if(connection != null)
                connection.close();
        } catch(java.sql.SQLException ex1)
        {
            if(esTexto)
                System.out.println(Gestor.GetLiteral("gestor.error_1","Error") + ": " + ex1.getMessage());
            else
            {
                al = new Alerta(new javax.swing.JDialog(),Gestor.GetLiteral("gestor.error_1","Error"),true,ex1.getMessage(),Alerta.OK);
                al.setVisible(true);
            }
        }
        if(!esTexto)
        {
            pbar.hide();
            pbar.dispose();
            pbar = null;
        }
       
        closeErrors();
    } // fin de run()

    private void procesaTablaQuery(Connection connection, Statement stmt, File archivo)
    {
        byte buffer[] = new byte[5002];
        int leido = 0;
        int QuerysPro = 0;
        Vector vtemp = null;
        FileInputStream fin = null;
        String tabla = "";

        try {
            if(EliminarRegistros)
            {
                tabla = archivo.getName();
                if(tabla.indexOf("_D.sql") != -1)
                    tabla = tabla.substring(0,tabla.indexOf("_D.sql"));
                if(tabla.indexOf("_S.sql") != -1)
                    tabla = tabla.substring(0,tabla.indexOf("_S.sql"));
                if(tabla.indexOf(".") != -1)
                    tabla = tabla.substring(0,tabla.indexOf("."));
                   
                if(this.jdbcDriverClass.indexOf("oracle") != -1)
                    stmt.executeUpdate("truncate table " + tabla);
                else
                    stmt.executeUpdate("delete from " + tabla);
                connection.commit();
            }
        } catch(java.sql.SQLException sqle)
        {
            if(!esTexto)
                Trackbug.error(sqle, Gestor.GetLiteral("gestor.error_1","Error") + " delete from " + tabla + ": " + sqle.getMessage());
            else
                System.out.println(Gestor.GetLiteral("gestor.error_1","Error") + " delete from " + tabla + ": " + sqle.getMessage());
        }
       
        try {
            fin = new FileInputStream(archivo);

            String sQueryTemp = "";
            String stemp = "";
            String cadena = "";
            String laquery2 = "";
            String stemp2 = null;
            int posseparador = 0;
            int posIni = 0, posFin = 0;
            String sDelimiter = ";";
            boolean hayDelimiter = false;
            int iLimit = 0;
           
            while( (leido = fin.read(buffer,0,5000)) != -1)
            {
                stemp += new String(buffer,0,leido);

                iLimit = stemp.length();
               
                // mientras encuentre delimitadores procesa stemp
                while(posseparador != -1)
                {
                    // miramos si emprezamos con un cambiador de delimitador, si es asi, lo cambiamos.
                    hayDelimiter = false;
                    if(iLimit > 14)
                    {
                        sQueryTemp = stemp.substring(0, 14).trim().toLowerCase();
                        if(sQueryTemp.startsWith("delimiter"))
                        {
                            hayDelimiter = true;
                            // cambiamos el delimitador
                            String sValores[] = sQueryTemp.substring(10).split("[\\f\\s\\n]");
                            if(sValores.length > 0)
                                sDelimiter = sValores[0];
                        }
                    }
                    if((posseparador = stemp.indexOf(sDelimiter)) == -1)
                        break;
                   
                    if(esTexto)
                        System.out.println("Query " + numQuerys + " " + Gestor.GetLiteral("importar.process","Procesando") + " " + archivo.getName());
                    else
                    {
                        pbar.setMensaje("Query " + numQuerys + " " + Gestor.GetLiteral("importar.process","Procesando") + " " + archivo.getName());
                    }
                    cadena = stemp.substring(0,posseparador);

                    // tiene que comprobar si hay comentarios para eliminarlos
                    // quita los comentarios que empiezan pos "#" o por doble gui�n "--"
                    posIni = 0;
                    laquery2 = "";
                    while((posFin = cadena.indexOf('\n',posIni)) != -1)
                    {
                        stemp2 = cadena.substring(posIni,posFin+1);
                        // tiene que quitar los intros de delante
                        while(stemp2.length() > 0 && (stemp2.charAt(0) == '\r' || stemp2.charAt(0) == '\n'))
                            stemp2 = stemp2.substring(1);
                       
                        if(((stemp2.length() > 1 && stemp2.substring(0,2).equals("--") == false) || stemp2.length() == 1) && stemp2.charAt(0) != '#')
                            laquery2 += stemp2;

                        posIni = posFin + 1;
                    }

                    if(posIni < cadena.length())
                    {
                        stemp2 = cadena.substring(posIni,cadena.length());
                        // tiene que quitar los intros de delante
                        while(stemp2.length() > 0 && (stemp2.charAt(0) == '\r' || stemp2.charAt(0) == '\n'))
                            stemp2 = stemp2.substring(1);
                       
                        if(((stemp2.length() > 1 && stemp2.substring(0,2).equals("--") == false) || stemp2.length() == 1) && stemp2.charAt(0) != '#')
                            laquery2 += stemp2;
                    }

                    if(laquery2.trim().length() > 0 && !hayDelimiter)
                    {
                        numQuerys++;
                        try {
                            stmt.executeUpdate(laquery2);
                        } catch(java.sql.SQLException sqle3)
                        {
                            hayError = true;
                            numQuerysError++;
                            vtemp = new Vector(3);
                            // pone el nombre del archivo
                            vtemp.addElement(archivo.getName());
                            // pone la query que la tiene que sacar del archivo
                            vtemp.addElement(cadena);
                            // a�ade el error
                            vtemp.addElement(Gestor.GetLiteral("gestor.error_1","Error") + ": " + sqle3.getErrorCode() +
                                    ", sqlcode: " + sqle3.getSQLState() +
                                    ", " + Gestor.GetLiteral("importar.message","Mensaje") + ": " + sqle3.getMessage());
                            addErrorQuery(vtemp);
                        }
                        QuerysPro++;
                    }
                    if(stemp.length() > (posseparador+sDelimiter.length()))
                        stemp = stemp.substring(posseparador+sDelimiter.length());
                    else
                        stemp = "";

                    iLimit = stemp.length();

                    // si hemos llegado al limite del numero de registros por commit
                    // lanzamos el commit
                    if(QuerysPro > RegistrosCommit)
                    {
                        try {
                            connection.commit();
                        } catch(java.sql.SQLException sqle4)
                        {
                            ;
                        } // fin del catch
                        QuerysPro = 0;
                    }
                } // fin del while ;
            }

            // hay que mirar si sobra algo en stemp
            if(stemp.trim().length() > 0)
            {
                // mientras encuentre puntos y coma procesa stemp
                while((posseparador = stemp.indexOf(sDelimiter)) != -1)
                {
                    cadena = stemp.substring(0,posseparador);

                    // tiene que comprobar si hay comentarios para eliminarlos
                    // quita los comentarios que empiezan pos "#" o por doble gui�n "--"
                    posIni = 0;
                    laquery2 = "";
                    while((posFin = cadena.indexOf('\n',posIni)) != -1)
                    {
                        stemp2 = cadena.substring(posIni,posFin+1);
                        // tiene que quitar los intros de delante
                        while(stemp2.length() > 0 && (stemp2.charAt(0) == '\r' || stemp2.charAt(0) == '\n'))
                            stemp2 = stemp2.substring(1);

                        if(((stemp2.length() > 1 && stemp2.substring(0,2).equals("--") == false) || stemp2.length() == 1) && stemp2.charAt(0) != '#')
                            laquery2 += stemp2;

                        posIni = posFin + 1;
                    }

                    if(posIni < cadena.length())
                    {
                        stemp2 = cadena.substring(posIni,cadena.length());
                        // tiene que quitar los intros de delante
                        while(stemp2.length() > 0 && (stemp2.charAt(0) == '\r' || stemp2.charAt(0) == '\n'))
                            stemp2 = stemp2.substring(1);

                        if(((stemp2.length() > 1 && stemp2.substring(0,2).equals("--") == false) || stemp2.length() == 1) && stemp2.charAt(0) != '#')
                            laquery2 += stemp2;
                    }

                    if(laquery2.trim().length() > 0)
                    {
                        numQuerys++;
                        try {
                            stmt.executeUpdate(laquery2);
                        } catch(java.sql.SQLException sqle3)
                        {
                            hayError = true;
                            numQuerysError++;
                            vtemp = new Vector(3);
                            // pone el nombre del archivo
                            vtemp.addElement(" " + archivo.getName());
                            // pone la query que la tiene que sacar del archivo
                            vtemp.addElement(cadena);
                            // a�ade el error
                            vtemp.addElement(Gestor.GetLiteral("gestor.error_1","Error") + ": " + sqle3.getErrorCode() +
                                    ", sqlcode: " + sqle3.getSQLState() +
                                    ", " + Gestor.GetLiteral("importar.message","Mensaje") + ": " + sqle3.getMessage());
                            addErrorQuery(vtemp);
                        }
                        QuerysPro++;
                    }
                    if(stemp.length() > (posseparador+sDelimiter.length()))
                        stemp = stemp.substring(posseparador+sDelimiter.length());
                    else
                        stemp = "";

                    // si hemos llegado al limite del numero de registros por commit
                    // lanzamos el commit
                    if(QuerysPro > RegistrosCommit)
                    {
                        try {
                            connection.commit();
                        } catch(java.sql.SQLException sqle4)
                        {
                            ;
                        } // fin del catch
                        QuerysPro = 0;
                    }
                } // fin del while ;
            } // fin del if que mira si sobra algo en stemp.
           
            // Se lanza el commit
            try {
                connection.commit();
            } catch(java.sql.SQLException sqle4)
            {
                ;
            } // fin del catch
        } catch(java.io.IOException ioe)
        {
            vtemp = new Vector(3);
            vtemp.addElement(archivo.getName());
            vtemp.addElement("-");
            vtemp.addElement(Gestor.GetLiteral("importar.error_3","Error. el archivo no se puede procesar.") + " " + ioe.getMessage());
            addErrorQuery(vtemp);
        }
       
        if(fin != null)
        {
            try {
                fin.close();
            } catch(java.io.IOException ioe2)
            { ; }
        }
    }
   
    private void procesaTablaTXT(Connection connection, DatabaseMetaData dmd, File archivo)
    {
        String sarchivo = archivo.getName();
        String tabla = sarchivo;
        BufferedReader fin = null;
        int registros = 0;
        int updateCounts[] = null;
        PreparedStatement stmt = null;

        try {
            // saca el nombre de la tabla del nombre del archivo quitando la extensi�n
            int pos1 = sarchivo.lastIndexOf(".");
            if(pos1 != -1)
            {
                tabla = sarchivo.substring(0, pos1);
            }

            if(dmd.getDatabaseProductName().equals("Oracle"))
                tabla = tabla.toUpperCase();

            sMensaje += Gestor.GetLiteral("exportardatos.table","Tabla") + ": " + tabla + "\n-------------------------\n";
            String query;
            boolean correcto;
            query = "insert into " + tabla + " values (";
            pos1 = 0;
            ResultSet rs = dmd.getColumns(null, null, tabla, null);
            int tipos[] = new int[255];
            while(rs.next())
            {
                tipos[pos1] = rs.getShort("DATA_TYPE");
                if(pos1 > 0)
                    query = query + ",";
                query = query + "?";
                pos1++;
            }
            rs.close();

            if(pos1 == 0)
                sMensaje += Gestor.GetLiteral("importar.error_4","Error: No se encuentra la tabla") + " " + tabla + "\n";
            else
            {
                query = query + ")";

                String contArchivo = "";
                boolean primeralinea = true;
                int ncampos = pos1;
                int tamdelimitador = DelimitadorTexto.length();
                int tamdelimitadorf = DelimitadorFecha.length();
                int ninicio = 0;
                int nfin = 0;
                int longi = 0;
                int posSeparador = 0;
                int posSeparador2 = 0;
                int longSeparador = 0;
                String stemp = null;
                String stemp2 = null;
                boolean bEsOracle = this.jdbcDriverClass.indexOf("oracle") != -1;

                if(!tienePrimeraLineaConNombres)
                    primeralinea = false;
                fin = new BufferedReader(new FileReader(archivo));
                // si tiene que eliminar los datos existentes los elimina
                try {
                    if(EliminarRegistros)
                    {
                        Statement stmt2 = connection.createStatement();
                        if(bEsOracle)
                            stmt2.addBatch("truncate table " + tabla);
                        else
                            stmt2.addBatch("delete from " + tabla);
                        int updateCounts2[] = stmt2.executeBatch();
                        stmt2.close();
                    }

                    // prepara la sentencia
                    stmt = connection.prepareStatement(query);
                    ninicio = 0;
                    nfin = 0;
                    longi = 0;
                    // se recorre linea a linea y va metiendo los registros
                    while(contArchivo != null)
                    {
                        if(esTexto)
                            System.out.print(".");
                        contArchivo = fin.readLine();
                        if(primeralinea || contArchivo == null)
                        {
                            primeralinea = false;
                        } else
                        {
                            if(tamdelimitador > 0) // quita el delimitador
                                while((pos1 = contArchivo.indexOf(DelimitadorTexto)) != -1)
                                    contArchivo = contArchivo.substring(0, pos1) + (pos1 + tamdelimitador >= contArchivo.length() ? "" : contArchivo.substring(pos1 + tamdelimitador));

                            // lo mismo para el delimitador de fecha
                            if(tamdelimitadorf > 0) // quita el delimitador
                                while((pos1 = contArchivo.indexOf(DelimitadorFecha)) != -1)
                                    contArchivo = contArchivo.substring(0, pos1) + (pos1 + tamdelimitadorf >= contArchivo.length() ? "" : contArchivo.substring(pos1 + tamdelimitadorf));
                           
                            pos1 = 0;
                            ninicio = 0;
                            nfin = 0;
                            longi = contArchivo.length();
                            // procesa todas las columnas
                            while((nfin = contArchivo.indexOf(SepColumnas, ninicio)) != -1 && pos1 < ncampos)
                            {
                                // coge el contenidos de la columna
                                if(ninicio == nfin)
                                    stemp = "";
                                else
                                    stemp = contArchivo.substring(ninicio, nfin);
                                if(stemp.toUpperCase().equals("NULL"))
                                    stmt.setNull(pos1 + 1,tipos[pos1]);
                                else if(tipos[pos1] == 3 && !bEsOracle)
                                    stmt.setInt(pos1 + 1, (int)Long.parseLong(stemp));
                                else if(tipos[pos1] == 12)
                                    stmt.setString(pos1 + 1, stemp);
                                else if(tipos[pos1] == -5 || (tipos[pos1] == 3 && bEsOracle))
                                {
                                    try {
                                        stmt.setBigDecimal(pos1 + 1, new BigDecimal(stemp));
                                    } catch(Exception e)
                                    {
                                    if(!esTexto)
                                        Trackbug.error(e, Gestor.GetLiteral("gestor.error_1","Error") + e.getMessage() + ". [" + stemp + "]");
                                    else
                                        System.out.println("Error: " + e.getMessage() + ". [" + stemp + "]");
                                    }
                                }
                                else if(tipos[pos1] == -2)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == -7)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == 2004)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == 2005)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == 1)
                                    stmt.setString(pos1 + 1, stemp);
                                else if(tipos[pos1] == 91)
                                    stmt.setTimestamp(pos1 + 1, java.sql.Timestamp.valueOf(stemp));
//                                    stmt.setDate(pos1 + 1, java.sql.Date.valueOf(stemp));
                                else if(tipos[pos1] == 8)
                                    stmt.setDouble(pos1 + 1, Double.valueOf(stemp).doubleValue());
                                else if(tipos[pos1] == 6)
                                    stmt.setFloat(pos1 + 1, Float.valueOf(stemp).floatValue());
                                else if(tipos[pos1] == 4)
                                    stmt.setInt(pos1 + 1, (int)Long.parseLong(stemp));
                                else if(tipos[pos1] == -4)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == -1)
                                {
                                    // lo tratamos como un clob
                                    if(bEsOracle)
                                    {
                                        stmt.setCharacterStream(pos1 + 1, new StringReader(stemp),stemp.length());
                                       
                                        // StringReader re = new StringReader(stemp);
                                        // stmt.setCharacterStream(pos1 + 1, re);

                                        // ByteArrayInputStream bin = new ByteArrayInputStream(stemp.getBytes());
                                        // stmt.setAsciiStream(pos1 + 1, bin, stemp.length());

                                        // stmt.setClob(pos1 + 1, new oracle.sql.CLOB((OracleConnection) connection,stemp.getBytes()));
                                       
                                        // stmt.setBytes(pos1 + 1, stemp.getBytes());
                                        // stmt.setString(pos1 + 1, stemp);
                                    }
                                    else
                                        stmt.setString(pos1 + 1, stemp);
                                }
                                else if(tipos[pos1] == 2)
                                    stmt.setInt(pos1 + 1, (int)Long.parseLong(stemp));
                                else if(tipos[pos1] == 7)
                                    stmt.setDouble(pos1 + 1, Double.valueOf(stemp).doubleValue());
                                else if(tipos[pos1] == 5)
                                    stmt.setShort(pos1 + 1, Short.valueOf(stemp).shortValue());
                                else if(tipos[pos1] == 92)
                                    stmt.setTime(pos1 + 1, Time.valueOf(stemp));
                                else if(tipos[pos1] == 93)
                                {
                                    if(estaPersonalizadoTimestamp)
                                    {
                                        if((posSeparador = stemp.indexOf(SepFecha)) != -1) // vamos con el a�o
                                        {
                                            longSeparador = SepFecha.length();
                                            stemp2 = stemp.substring(0,posSeparador) + "-";
                                            posSeparador2 = posSeparador;
                                           
                                            if((posSeparador = stemp.indexOf(SepFecha,posSeparador2 + longSeparador)) != -1 ) // el mes
                                            {
                                                stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + "-";
                                                posSeparador2 = posSeparador;

                                                if((posSeparador = stemp.indexOf(SepFechaHora,posSeparador2 + longSeparador)) != -1 ) // el dia
                                                {
                                                    stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + " ";
                                                    posSeparador2 = posSeparador;
                                                    longSeparador = SepFechaHora.length();

                                                    if((posSeparador = stemp.indexOf(SepHora,posSeparador2 + longSeparador)) != -1 ) // la hora
                                                    {
                                                        stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + ":";
                                                        posSeparador2 = posSeparador;
                                                        longSeparador = SepHora.length();

                                                        if((posSeparador = stemp.indexOf(SepHora,posSeparador2 + longSeparador)) != -1 ) // el minuto
                                                        {
                                                            stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + ":";
                                                            posSeparador2 = posSeparador;

                                                            if((posSeparador = stemp.indexOf(SepDecimales,posSeparador2 + longSeparador)) != -1 ) // los segundos
                                                            {
                                                                stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + ".";
                                                                posSeparador2 = posSeparador;
                                                                longSeparador = SepDecimales.length();

                                                                if((posSeparador2 + longSeparador) < stemp.length() ) // las decimas
                                                                {
                                                                    stemp2 += stemp.substring(posSeparador2 + longSeparador);
                                                                }
                                                                else
                                                                    stemp2 += "000000";
                                                            }
                                                            else
                                                                stemp2 += "00.000000";
                                                        }
                                                        else
                                                            stemp2 += "00:00.000000";
                                                    }
                                                    else
                                                        stemp2 += "00:00:00.000000";
                                                }
                                                else
                                                    stemp2 += "01 00:00:00.000000";
                                            }
                                            else
                                                stemp2 += "01-01 00:00:00.000000";
                                        }
                                        else
                                            stemp2 = "1900-01-01 00:00:00.000000";
                                       
                                        stmt.setTimestamp(pos1 + 1, Timestamp.valueOf(stemp2));
                                    }
                                    else
                                    {
                                        stmt.setTimestamp(pos1 + 1, Timestamp.valueOf(stemp));
                                    }
                                }
                                else if(tipos[pos1] == -6)
                                    stmt.setShort(pos1 + 1, Short.valueOf(stemp).shortValue());
                                else if(tipos[pos1] == -3)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                pos1++;
                                ninicio = nfin + SepColumnas.length();
                                if(ninicio >= longi)
                                    break;
                            } // fin del while((nfin = contArchivo.indexOf(SepColumnas, ninicio)) != -1 && pos1 < ncampos)

                            // mira si queda informaci�n por procesar.
                            if(contArchivo.length() > ninicio && pos1 < ncampos)
                                stemp = contArchivo.substring(ninicio);
                            else if(pos1 < ncampos)
                                stemp = "";
                           
                            if(pos1 < ncampos)
                            {
                                if(stemp.toUpperCase().equals("NULL"))
                                    stmt.setNull(pos1 + 1,tipos[pos1]);
                                else if(tipos[pos1] == 3)
                                    stmt.setInt(pos1 + 1, (int)Long.parseLong(stemp));
                                else if(tipos[pos1] == 12)
                                    stmt.setString(pos1 + 1, stemp);
                                else if(tipos[pos1] == -5)
                                    stmt.setBigDecimal(pos1 + 1, new BigDecimal(stemp));
                                else if(tipos[pos1] == -2)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == -7)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == 2004)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == 2005)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == 1)
                                    stmt.setString(pos1 + 1, stemp);
                                else if(tipos[pos1] == 91)
                                    stmt.setTimestamp(pos1 + 1, java.sql.Timestamp.valueOf(stemp));
                                else if(tipos[pos1] == 8)
                                    stmt.setDouble(pos1 + 1, Double.valueOf(stemp).doubleValue());
                                else if(tipos[pos1] == 6)
                                    stmt.setFloat(pos1 + 1, Float.valueOf(stemp).floatValue());
                                else if(tipos[pos1] == 4)
                                    stmt.setInt(pos1 + 1, (int)Long.parseLong(stemp));
                                else if(tipos[pos1] == -4)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                                else if(tipos[pos1] == -1)
                                    stmt.setString(pos1 + 1, stemp);
                                else if(tipos[pos1] == 2)
                                    stmt.setInt(pos1 + 1, (int)Long.parseLong(stemp));
                                else if(tipos[pos1] == 7)
                                    stmt.setDouble(pos1 + 1, Double.valueOf(stemp).doubleValue());
                                else if(tipos[pos1] == 5)
                                    stmt.setShort(pos1 + 1, Short.valueOf(stemp).shortValue());
                                else if(tipos[pos1] == 92)
                                    stmt.setTime(pos1 + 1, Time.valueOf(stemp));
                                else if(tipos[pos1] == 93)
                                {
                                    if(estaPersonalizadoTimestamp)
                                    {
                                        if((posSeparador = stemp.indexOf(SepFecha)) != -1) // vamos con el a�o
                                        {
                                            longSeparador = SepFecha.length();
                                            stemp2 = stemp.substring(0,posSeparador) + "-";
                                            posSeparador2 = posSeparador;
                                           
                                            if((posSeparador = stemp.indexOf(SepFecha,posSeparador2 + longSeparador)) != -1 ) // el mes
                                            {
                                                stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + "-";
                                                posSeparador2 = posSeparador;

                                                if((posSeparador = stemp.indexOf(SepFechaHora,posSeparador2 + longSeparador)) != -1 ) // el dia
                                                {
                                                    stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + " ";
                                                    posSeparador2 = posSeparador;
                                                    longSeparador = SepFechaHora.length();

                                                    if((posSeparador = stemp.indexOf(SepHora,posSeparador2 + longSeparador)) != -1 ) // la hora
                                                    {
                                                        stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + ":";
                                                        posSeparador2 = posSeparador;
                                                        longSeparador = SepHora.length();

                                                        if((posSeparador = stemp.indexOf(SepHora,posSeparador2 + longSeparador)) != -1 ) // el minuto
                                                        {
                                                            stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + ":";
                                                            posSeparador2 = posSeparador;

                                                            if((posSeparador = stemp.indexOf(SepDecimales,posSeparador2 + longSeparador)) != -1 ) // los segundos
                                                            {
                                                                stemp2 += stemp.substring(posSeparador2 + longSeparador,posSeparador) + ".";
                                                                posSeparador2 = posSeparador;
                                                                longSeparador = SepDecimales.length();

                                                                if((posSeparador2 + longSeparador) < stemp.length() ) // las decimas
                                                                {
                                                                    stemp2 += stemp.substring(posSeparador2 + longSeparador);
                                                                }
                                                                else
                                                                    stemp2 += "000000";
                                                            }
                                                            else
                                                                stemp2 += "00.000000";
                                                        }
                                                        else
                                                            stemp2 += "00:00.000000";
                                                    }
                                                    else
                                                        stemp2 += "00:00:00.000000";
                                                }
                                                else
                                                    stemp2 += "01 00:00:00.000000";
                                            }
                                            else
                                                stemp2 += "01-01 00:00:00.000000";
                                        }
                                        else
                                            stemp2 = "1900-01-01 00:00:00.000000";
                                       
                                        stmt.setTimestamp(pos1 + 1, Timestamp.valueOf(stemp2));
                                    }
                                    else
                                    {
                                        stmt.setTimestamp(pos1 + 1, Timestamp.valueOf(stemp));
                                    }
                                }
                                else if(tipos[pos1] == -6)
                                    stmt.setShort(pos1 + 1, Short.valueOf(stemp).shortValue());
                                else if(tipos[pos1] == -3)
                                    stmt.setBytes(pos1 + 1, stemp.getBytes());
                            }
                           
                            // a�ade la sentencia a un batch
                            stmt.addBatch();
                            registros++;
                        } // fin del else de if(primeralinea || contArchivo == null)
                    } // fin del while(contArchivo != null)
                } catch(IOException ioe)
                {
                    connection.rollback();
                    sMensaje += Gestor.GetLiteral("gestor.error_1","Error") + ": " + ioe.getMessage() + "\n";
                } catch(SQLException sqle2)
                {
                    connection.rollback();
                    sMensaje += Gestor.GetLiteral("importar.error_5","Error: procesando la l�nea") + " " + (registros +1) + " " +
                        Gestor.GetLiteral("importar.error_6","del archivo") + " " + sarchivo + ": " + sqle2.getMessage() + "\n";
sqle2.printStackTrace();
                } catch(Exception e2)
                {
                    connection.rollback();
                    sMensaje += Gestor.GetLiteral("importar.error_5","Error: procesando la l�nea") + " " + (registros +1) + " " +
                        Gestor.GetLiteral("importar.error_6","del archivo") + " " + sarchivo + ": " + e2.getMessage() + "\n";
e2.printStackTrace();
                }

                fin.close();

                // ya tenemos preparado el batch lo lanzamos
                updateCounts = stmt.executeBatch();
                connection.commit();
                sMensaje += Gestor.GetLiteral("importar.tot_lines","Total l�neas procesadas") + ": " + registros + "\n";
                int lcorrectas = 0;
                String sMensaje2 = "";
                for(int i = 0; i < updateCounts.length; i++)
                {
                    if(updateCounts[i] > 0 || updateCounts[i] == -2)
                        ++lcorrectas;
                    else
                        sMensaje2 += Gestor.GetLiteral("importar.line","l�nea") + " " + i + ", " +
                            Gestor.GetLiteral("importar.result","resultado") + ": " + updateCounts[i] + "\n";
                }

                sMensaje += Gestor.GetLiteral("importar.tot_lines_ok","L�neas procesadas correctamente") + ": " +
                    lcorrectas + "\n";
                sMensaje += Gestor.GetLiteral("importar.tot_lines_ko","L�neas procesadas incorrectamente") + ": " +
                    (registros - lcorrectas) + "\n" + sMensaje2 + "\n";
            } // fin del else de no se encuentra la tabla
        } catch(IOException e)
        {
            try {
                fin.close();
            } catch(java.io.IOException ioe2)
            {
                ;
            }
            try {
                connection.rollback();
            } catch(SQLException sqle3)
            {
                ;
            }
            sMensaje += Gestor.GetLiteral("gestor.error_1","Error") + ": " + e.getMessage() + "\n";
        } catch(SQLException sqle)
        {
            try {
                fin.close();
            } catch(java.io.IOException ioe2)
            {
                ;
            }
            try {
                connection.rollback();
            } catch(SQLException sqle3)
            {
                ;
            }
            sMensaje += Gestor.GetLiteral("importar.error_7","Error: insertando registros en") + " " +
                tabla + ": " + sqle.getMessage() + "\n";
        }
        try {
            if(stmt != null)
                stmt.close();
        } catch(SQLException sqle3)
        {
            ;
        }
    } // fin de procesaTablaTXT()

    public void setSeparadoresTimestamp(boolean estaPersonalizadoTimestamp,
            String SepFecha, String SepHora, String SepFechaHora, String SepDecimales, String DelimitadorFecha)
    {
        this.estaPersonalizadoTimestamp = estaPersonalizadoTimestamp;
        this.SepFecha = SepFecha;
        this.SepHora = SepHora;
        this.SepFechaHora = SepFechaHora;
        this.SepDecimales = SepDecimales;
        this.DelimitadorFecha = DelimitadorFecha;
    }

    private void addErrorQuery(Vector elVector)
    {
        try {
            // si no se ha creado el fichero de errores lo creamos
            if(foutErr == null)
                foutErr = new FileOutputStream(sArchivoErrores);
           
            String stemp = null;
            stemp = ((String)elVector.elementAt(0)) + "|" + ((String)elVector.elementAt(1)) + "|" +
                ((String)elVector.elementAt(2)) + ((char)13) + ((char)10);
            foutErr.write(stemp.getBytes());

        }catch(Exception e)
        {
            if(!esTexto)
                Trackbug.error(e, e.getMessage());
            else
            {
                System.out.println(Gestor.GetLiteral("gestor.error_1","Error") + ": " + e.getMessage());
                e.printStackTrace();
            }
        }
       
        if(ResultadosQuerys.size() < 1000)
        {
            ResultadosQuerys.addElement(elVector);
        }
    }

    private void closeErrors()
    {
        try {
            if(foutErr != null)
                foutErr.close();
        }catch(Exception e)
        {
            if(!esTexto)
                Trackbug.error(e, e.getMessage());
            else
                System.out.println(Gestor.GetLiteral("gestor.error_1","Error") + ": " + e.getMessage());
        }
    }
   
    private boolean esDirectorio = false;
    private boolean esQuery = false;
    private File Archivo = null;
    private boolean tienePrimeraLineaConNombres = false;
    private String SepColumnas = "|";
    private String DelimitadorTexto = "";
    private boolean EliminarRegistros = false;
    private boolean conCommit = true;
    private int RegistrosCommit = 1000;
    private String jdbcDriverClass=null;
    private String jdbcDriverURL=null;
    private String user=null;
    private String password=null;
    private String sMensaje = "";
    private Alerta al = null;
    private Vector ResultadosQuerys = new Vector(1000,1000); // vector de dos dimensiones
    private String sArchivoErrores = "./SqlImportErr.txt";
    private FileOutputStream foutErr = null;
    private long numQuerys = 0;
    private long numQuerysError = 0;
    private boolean Cancelado = false;
    private boolean hayError = false;
    private iframeProgressBar pbar = null;
    private boolean esTexto = false;
    private Properties propiedades = null;
    // las siguientes variables es para la gesti�n de los timestamp personalizados
    private boolean estaPersonalizadoTimestamp = false;
    private String SepFecha = "-";
    private String SepHora = ":";
    private String SepFechaHora = " ";
    private String SepDecimales = ".";
    private String DelimitadorFecha = "";
}
TOP

Related Classes of com.GestDB.convert.Importar

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.