Xbase Source java File




/*
 Nixbase.java     Agosto 1.999   Copyright()  N. Betancort
 Applet que contiene un visor de ficheros Xbase
 */

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
import java.net.URL;
import java.io.*;

 // Clase  principal  -- Main class

 public class Nixbase extends Applet implements Runnable{ //Constructor

   private int x = 400;                                   //ancho--width
   private int y = 300;                                   //alto--height
   int id = 0;               //language parameter (0-spanish / 1- english)

   Thread proce1;
   Panel marco;
   Infbase info1;
   Preinfo preinf = new Preinfo( RegXB.COL_INFO);    //Panel con info  
   private Panel ptitu = new Panel();                //Panel para cabecera
   private Label ltitu;                              //titulo
   private TextField mensabar = new TextField(40);   // barra de mensajes
   private List datalist = new List(8);              //lista de registros
   private String sfile = RegXB.DEF_FILE;            //datafile default name
   private String stitu = RegXB.DEF_TITLE;           //default title

   public Dimension getPreferredSize() { return new Dimension(x,y);}


   public void  init(){
      setLayout(null);
      setSize(getPreferredSize());
      setBackground(RegXB.COL_FONDO);

      //Captura de par metros--getting parameters

      String sx = getParameter("an");           //dimensiones
      String sy = getParameter("al");
      if (sx != null & sy != null){
           x = (Integer.valueOf(sx)).intValue();
           y = (Integer.valueOf(sy)).intValue();
      }

      String idiom = getParameter("idioma");        //Idioma ingl‚s-espa¤ol
      if (idiom != null & idiom.equals("eng")) {id = 1 ;}  //Language param.

      String stx = getParameter("title");   //Asignar t¡tulo--title param. 
      if ( stx != null)  { stitu = stx; }
      ltitu = new Label(stitu);             //Etiqueta con t¡tulo--title label

      String sfx = getParameter("datafile");  //Archivo de datos--datafile 
      if ( sfx != null)  { sfile = sfx; }

      marco = new Tapiz( RegXB.COL_FONDO);
      marco.setBounds(0,0, x, y);
      add(marco);
                         //panel con titulo del Applet
      ptitu.setBackground(RegXB.COL_FONDO);
      ptitu.setBounds(10,10,x-40,y/10);
      ltitu.setForeground(RegXB.COL_TITLE);
      ltitu.setFont(new Font("Serif",Font.BOLD, 16));     //title font
      ptitu.add("Center",ltitu);
      marco.add(ptitu);
                           //panel con datos del fichero
      preinf.setBounds(10, 10+y/10, x-20, y/10);
      marco.add(preinf);
                            //Lista de registros
      datalist.setFont(new Font("Courier", Font.PLAIN, 12));
      datalist.setForeground(Color.red);
      datalist.setBounds(20, 20+y/5, x-40, 3*y/5);
                            //barra de status
      mensabar.setEditable(false);
      mensabar.setBackground(RegXB.COL_BARRA);
      mensabar.setBounds(6, 14*y/15 - 6 , x-12, y/15);
      marco.add(mensabar);
      setVisible(true);
   }

 //---------------------------------------------------------------------

   public void start(){
      repaint();
      //comprobar que tiene extensi¢n dbf
      String extens = sfile.substring(sfile.length()-3, sfile.length());

      if( ! extens.equalsIgnoreCase ("dbf") ){      //check file extension
           mensabar.setText(RegXB.mensa[id][3]);    //not dbf file
      }
      leer1();
      if( info1.error == 0 ){   leer2();    }
      else{
           mensabar.setText(mensabar.getText() + RegXB.errores[info1.error]);
      }
      if(info1.error == 0 ){  mensabar.setText(RegXB.mensa[id][8]); }

      repaint();

   }
 //--------------------------------------------------------------------------
   public void run(){

   }
 //--------------------------------------------------------------------------

  public void leer1(){

     try {
         mensabar.setText(RegXB.mensa[id][0]);   // Apertura fichero de datos
         InputStream is = new URL(getCodeBase(), sfile).openStream();
         BufferedInputStream bis = new BufferedInputStream(is, 1024);
         //llamada a lectura
         info1 = new Infbase(bis);
         //presentacion resultados
         preinf.dispinfo( sfile, info1.ver, info1.fecha, info1.snumreg,
                         info1.snumcam, info1.slfilesize );
         mensabar.setText(RegXB.mensa[id][4]);   // Apertura fichero de datos
         bis.close();
         is.close();
     }
     catch(Exception e) {
         //error apertura fichero de datos xxxx  no accesible
         mensabar.setText(RegXB.mensa[id][1] + sfile + RegXB.mensa[id][2]);
     }
  }
  //----------------------------------------------------------------------

  public void leer2(){

     try {

         marco.add(datalist);
         datalist.addItem(RegXB.SEPAR);
         datalist.addItem(info1.encabezado());
         datalist.addItem(RegXB.SEPAR);

         mensabar.setText(RegXB.mensa[id][0]);  // Apertura fichero de datos  **
         InputStream is = new URL(getCodeBase(), sfile).openStream();
         BufferedInputStream bis = new BufferedInputStream(is, info1.logfilesize);
         info1.infodata(bis, datalist);           // llamada a lectura datos
         bis.close();
         is.close();

     }
     catch(Exception e) {
         //error apertura fichero de datos xxxx  no accesible
         mensabar.setText(RegXB.mensa[id][1] + sfile + RegXB.mensa[id][2]);
     }
   }
 //..........................................


 }  //Fin de clase Vbase


  //-------------------------------------------------------------------------

   class Preinfo extends Panel {

     Label L1 = new Label("File: ");
     Label L2 = new Label("Ver. ");
     Label L3 = new Label("Last modif. ");
     Label L4 = new Label("N. records: ");
     Label L5 = new Label("N. fields: ");
     Label L6 = new Label("File size: ");


     public Preinfo(Color FONDO){
        super();
        setLayout(new GridLayout(2,3,5,5));
        setBackground(FONDO);
        setForeground(new Color(20,10,20));    //pasar a la clase
        setFont(new Font("Serif",Font.BOLD, 10));

        add(L1);
        add(L2);
        add(L3);
        add(L4);
        add(L5);
        add(L6);
      }
     
     public void dispinfo( String fil, String ver, String lmod, String nrec,
                           String nfields, String filsize){

        L1.setText("File: "+fil);
        L2.setText("Vers.: "+ver);
        L3.setText("Last modif.: "+lmod);
        L4.setText("N. records: "+nrec);
        L5.setText("N. fields: "+ nfields);
        L6.setText("File size: "+filsize+" bytes");

     }

   }
    

  //-------------------------------------------------------------------------

                          //Fin c¢digo applet
 //.........................*************************.............................



/*
Infbase.java Copyrigh()  N.Betancort  1999
Clase que implementa m‚todos de gesti¢n de ficheros en formato Xbase
Interface java-Xbase
*/

import java.io.*;
import java.util.Vector;
import java.awt.*;

 public class Infbase {

   //Declaraciones

   BufferedInputStream Nibuf;             //*
   IOException ex;                        //*
   TextField mensabar;                    //*

   int icabe[]= new int[12];              //cabecera en ints  *
   int numreg = 0;                        //numero total de registros  *
   int longreg = 0;                       //longitud de cada registro  *
   int longhead = 0;                      //longitud cabecera *
   int logfilesize = 0;                   //longitud l¢gica del fichero *
   int numcam = 0;                        //numero de campos por registro *
   int datasize = 0;                      //tama¤o segmento de datos *  
   byte fieldstruct[] = new byte[32];     //Estructura de cada campo *
 
   String fecha = "01-01-1981";              //*
   String snumreg = "0";                     //*
   String snumcam = "0";                     //*
   String slfilesize = "0";                  //*
   String sregistro;                         //bufer temporal  *
   String ver = "Unknown";                   //*
   boolean marca = false;                    //*


   String snomcam[] = new String[30];         //Nombres de campos   *
   String stipcam[] = new String[30];          //Tipos de campos     *
   int loncam[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
   int insert_space[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
   int error = 0;


  public Infbase( BufferedInputStream pNibuf) throws IOException{ //Constructor

    this.Nibuf = pNibuf;                 //capturar acceso
    error = 0;                          

    if (Nibuf.markSupported() == false ){
         error = 1;                      //BuffInputStream mark error
    }

    //Leer cabecera en array enteros
    Nibuf.mark(1024);
    Nibuf.reset();
    for(int i=0; i<12; i++){ icabe[i] = Nibuf.read();}

    if (icabe[0] < 6 ){ ver = RegXB.versiones[icabe[0]];}     //Comprobar versi¢n
    else if (icabe[0] == 48) {ver = RegXB.versiones[1];}

    String anno = fecha.valueOf(icabe[1]+1900);         //Obtener fecha
    String mes = fecha.valueOf(icabe[2]);
    String dia = fecha.valueOf(icabe[3]);
    fecha = dia + "-" + mes + "-" + anno;

    //Obtener n£mero y longitud de registros
    numreg = icabe[7]*256*256*256 +icabe[6]*256*256 +icabe[5]*256 +icabe[4];
    snumreg = snumreg.valueOf(numreg);
    if ( numreg < 1 ){ error = 5; }             //No contiene registros
    else if( numreg > 2048 ) { error = 6;}      //superado el limite max

    longreg = icabe[11] * 256 + icabe[10] ;    //longitud de cada  registro
    longhead = icabe[9] * 256 + icabe[8] ;     //longitud cabecera

    //longitud logica del fichero (numreg por longreg mas cabecera)
    logfilesize = (numreg * longreg) + longhead + 1; 
    slfilesize = slfilesize.valueOf(logfilesize);
    if (logfilesize > 65536 ){ error = 7; }  // Fichero mayor de 64kbytes


    Nibuf.reset();                  //Determinaci¢n del n£mero de campos
    Nibuf.skip(32);
    int j=0;
    while( j < 24 ) {               //Max num campos =24 

       if ( Nibuf.read() != 13) {   //Comprobar marca inicio
            Nibuf.skip(31);
            j++ ;
       }
       else{ break; }              
    }                               //fin while

    numcam = j;
    snumcam = snumcam.valueOf(numcam);
 
    if ( numcam > 0 ){              //Obtenci¢n par metros de campos

       Nibuf.reset();
       Nibuf.skip(32);

       for( int k = 0; k < numcam; k++){
          
         int rt2 = Nibuf.read(fieldstruct, 0, 32);    //leer estruct. campo
         if(rt2 != -1){
            String sestru = new String(fieldstruct);
            snomcam[k] = sestru.substring(0, 10).trim(); //nombre del campo
            stipcam[k] = sestru.substring(11, 12);       //tipo de campo

            Byte bloncam = new Byte( fieldstruct[16]);   //longitud campo
            int lcam = bloncam.intValue();
            if (lcam < 0) {lcam = lcam + 256 ;}          //Corregir negativos
            loncam[k] = lcam;
            int dife = snomcam[k].length() - lcam ;
            if( dife > 0 & dife < 10 ) {  insert_space[k] = dife;  }
         }
         else{ error = 3; } //error en lectura de estructura de datos  
       }
    }
    else{ error = 2 ; }   // Fichero de datos no reconocido  

  }  //fin constructor

 //-------------------------------------------------------------------------

  public void infodata( BufferedInputStream pNibuf, List datalist) throws IOException { 

    this.Nibuf = pNibuf;                         //capturar acceso
    datasize = logfilesize - longhead ;
    byte bufer[] = new byte[datasize];           //bufer de datos

    //proceso lectura de datos
    Nibuf.skip(longhead-1);         //puntero a marca inicio de datos

    if (Nibuf.read() !=13) {
          error = 10 ; // warning marca de inicio no localizada
    }

    int ret3 = Nibuf.read(bufer, 0, datasize);       //lectura datos
        
    if( ret3 != -1){    

       for(int p = 0; p < numreg; p++){       //obtener substing of bytes

           sregistro = new String(bufer, p*longreg, longreg);
           sregistro = formatear( sregistro, p+1 );
           datalist.addItem (sregistro);
       }
     }
  //   else { error = 4 ;  } //Error en lectura datos

   } //fin m‚todo

//-----------------------------------------------------

   public String encabezado() {     //devuelve la cabecera del listado

          String espacio = RegXB.cadena("        ", 32);   //256 spaces
          String cabe =" Nrec ";
          int dif;

          for (int k=0; k snomcam[k].length()) {
                    dif = loncam[k] - snomcam[k].length();
                    cabe = cabe + espacio.substring(0,dif);
               }
          }
          return(cabe);
    }

//-----------------------------------------------------------------

   public String formatear(String sin, int n) { //da formato a cada registro

          String espa2 = "          ";
          String snrec = espa2.valueOf(n);
          try{ snrec = snrec + espa2.substring(0, 4 - snrec.length() );}
          catch (Exception e){     }
          String trans = " " + snrec +" ";
          int r = 1;
          for (int k = 0; k < numcam; k++){
               trans = trans + sin.substring(r, r+loncam[k]);
               trans = trans + espa2.substring(0, insert_space[k]+1);
               r = r + loncam[k];
          }
          return(trans);
    }

//-----------------------------------------------------------------

     //Fin de clase

 }