Revision 466

View differences:

trunk/libraries/libGDBMS/.classpath
1
<?xml version="1.0" encoding="UTF-8"?>
2
<classpath>
3
	<classpathentry kind="src" path="src"/>
4
	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
5
	<classpathentry kind="src" path="/DriverManager"/>
6
	<classpathentry kind="lib" path="lib/mysql-connector-java-3.0.15-ga-bin.jar"/>
7
	<classpathentry kind="output" path="bin"/>
8
</classpath>
0 9

  
trunk/libraries/libGDBMS/.cvsignore
1
bin
2
java.hprof.txt
3
vias.dbf
4
metrics
0 5

  
trunk/libraries/libGDBMS/csv driver.jardesc
1
<?xml version="1.0" encoding="UTF-8"?>
2
<jardesc>
3
    <jar path="C:/eclipse3.0.1/workspace/GDBMS/drivers/csv/driver.jar"/>
4
    <options overwrite="false" compress="true" exportErrors="true" exportWarnings="true" saveDescription="true" descriptionLocation="/GDBMS/csv driver.jardesc" useSourceFolders="false" buildIfNeeded="true"/>
5
    <manifest manifestVersion="1.0" usesManifest="true" reuseManifest="false" saveManifest="false" generateManifest="true" manifestLocation="/jws/al servidor">
6
        <sealing sealJar="false">
7
            <packagesToSeal/>
8
            <packagesToUnSeal/>
9
        </sealing>
10
    </manifest>
11
    <selectedElements exportClassFiles="true" exportOutputFolder="false" exportJavaFiles="false">
12
        <javaElement handleIdentifier="=GDBMS/src&lt;com.hardcode.gdbms.driver.csv"/>
13
    </selectedElements>
14
</jardesc>
0 15

  
trunk/libraries/libGDBMS/dbf driver.jardesc
1
<?xml version="1.0" encoding="UTF-8"?>
2
<jardesc>
3
    <jar path="C:/eclipse3.0.1/workspace/GDBMS/drivers/dbf/driver.jar"/>
4
    <options overwrite="false" compress="true" exportErrors="true" exportWarnings="true" saveDescription="true" descriptionLocation="/GDBMS/dbf driver.jardesc" useSourceFolders="false" buildIfNeeded="true"/>
5
    <manifest manifestVersion="1.0" usesManifest="true" reuseManifest="false" saveManifest="false" generateManifest="true" manifestLocation="/jws/al servidor">
6
        <sealing sealJar="false">
7
            <packagesToSeal/>
8
            <packagesToUnSeal/>
9
        </sealing>
10
    </manifest>
11
    <selectedElements exportClassFiles="true" exportOutputFolder="false" exportJavaFiles="false">
12
        <javaElement handleIdentifier="=GDBMS/src&lt;com.hardcode.gdbms.driver.dbf"/>
13
    </selectedElements>
14
</jardesc>
0 15

  
trunk/libraries/libGDBMS/.project
1
<?xml version="1.0" encoding="UTF-8"?>
2
<projectDescription>
3
	<name>GDBMS estable</name>
4
	<comment></comment>
5
	<projects>
6
		<project>DriverManager</project>
7
		<project>Utilities</project>
8
	</projects>
9
	<buildSpec>
10
		<buildCommand>
11
			<name>org.eclipse.jdt.core.javabuilder</name>
12
			<arguments>
13
			</arguments>
14
		</buildCommand>
15
	</buildSpec>
16
	<natures>
17
		<nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
18
		<nature>org.eclipse.jdt.core.javanature</nature>
19
		<nature>org.eclipse.jem.beaninfo.BeanInfoNature</nature>
20
	</natures>
21
</projectDescription>
0 22

  
trunk/libraries/libGDBMS/compile.xml
1
<project name="all" default="compile-javacc" basedir=".">
2

  
3
  <target name="init">
4
    <tstamp/>
5
    <property environment="env"/>
6
    <property name="src" value="src"/>
7
    <property name="build" value="bin"/>
8
    <property name="doc" value="/home/andrew/doc/html/javadoc" />
9
    <property name="javacchome" value="C:/software/javacc-3.2"/>
10
	<!--    <property name="build.compiler" value="jikes" />
11
    <property name="junitclasspath" value="/home/andrew/junit3.8.1/junit.jar"/>
12
    <property name="classpath" value="${junitclasspath}:${build}"/>-->
13
    <!-- <echo message="classpath: ${classpath}"/> -->
14
  </target>
15

  
16
  <target name="clean" depends="init">
17
    <delete>
18
      <fileset dir="${build}"/>
19
    </delete>
20
  </target>
21

  
22
  <target name="compile-javacc" depends="init">
23
    <delete failonerror="true">
24
      <fileset dir="${src}/com/hardcode/gdbms/parser">
25
        <include name="*.java"/>
26
      </fileset>
27
    </delete>
28
<!--    <jjtree target="${src}/com/hardcode/gdbms/parser/sql.jj"
29
            static="no"
30
            nodescopehook="true"
31
            javacchome="${javacchome}"/>-->
32
    <javacc target="${src}/com/hardcode/gdbms/parser/sql.jj"
33
            static="no"
34
            javacchome="${javacchome}"/>
35
  </target>
36
<!--  
37
  <target name="doc-public" depends="init">
38
    <delete>
39
      <fileset dir="${doc}/public"/>
40
    </delete>
41
    <javadoc packagenames="org.acooke.*"
42
             sourcepath="${src}"
43
             destdir="${doc}/public"
44
             public="true">
45
      <doctitle><![CDATA[<h1>org.acooke - public</h1>]]></doctitle>
46
    </javadoc>
47
  </target>
48

  
49
  <target name="doc-package" depends="init">
50
    <delete>
51
      <fileset dir="${doc}/package"/>
52
    </delete>
53
    <javadoc packagenames="org.acooke.*"
54
             sourcepath="${src}"
55
             destdir="${doc}/package"
56
             package="true">
57
      <doctitle><![CDATA[<h1>org.acooke - package</h1>]]></doctitle>
58
    </javadoc>
59
  </target>
60

  
61
  <target name="doc-private" depends="init">
62
    <delete>
63
      <fileset dir="${doc}/private"/>
64
    </delete>
65
    <javadoc packagenames="org.acooke.*"
66
             sourcepath="${src}"
67
             destdir="${doc}/private"
68
             private="true">
69
      <doctitle><![CDATA[<h1>org.acooke - private</h1>]]></doctitle>
70
    </javadoc>
71
  </target>
72

  
73
  <target name="doc" depends="init">
74
    <parallel>
75
      <antcall target="doc-private"/>
76
      <antcall target="doc-package"/>
77
      <antcall target="doc-public"/>
78
    </parallel>
79
  </target>
80
-->
81
</project>
0 82

  
trunk/libraries/libGDBMS/src/com/hardcode/gdbms/driver/mysql/Auz.java
1
/*
2
 * Created on 17-oct-2004
3
 */
4
package com.hardcode.gdbms.driver.mysql;
5

  
6
import java.sql.Connection;
7
import java.sql.DriverManager;
8
import java.sql.Statement;
9

  
10

  
11
/**
12
 * DOCUMENT ME!
13
 *
14
 * @author Fernando Gonz?lez Cort?s
15
 */
16
public class Auz {
17
    /**
18
     * DOCUMENT ME!
19
     *
20
     * @param args DOCUMENT ME!
21
     */
22
    public static void main(String[] args) {
23
        try {
24
            Class.forName("com.mysql.jdbc.Driver").newInstance();
25

  
26
            Connection conn = DriverManager.getConnection(
27
                    "jdbc:mysql://localhost/prueba?user=root");
28
            
29
            Statement s = conn.createStatement();
30
            for (int i = 1000000; i <= 1000000; i++){
31
                s.execute("INSERT INTO prueba values('cadena "+i+"')");
32
            }
33
            s.close();
34
            conn.close();
35
        } catch (Exception ex) {
36
            ex.printStackTrace();
37
        }
38
    }
39
}
0 40

  
trunk/libraries/libGDBMS/src/com/hardcode/gdbms/driver/mysql/MySQLDriver.java
1
/*
2
 * Created on 16-oct-2004
3
 */
4
package com.hardcode.gdbms.driver.mysql;
5

  
6
import com.hardcode.driverManager.Driver;
7

  
8
import com.hardcode.gdbms.engine.data.DBDriver;
9
import com.hardcode.gdbms.engine.data.DriverException;
10
import com.hardcode.gdbms.engine.values.Value;
11
import com.hardcode.gdbms.engine.values.ValueFactory;
12

  
13
import java.sql.Connection;
14
import java.sql.DriverManager;
15
import java.sql.ResultSet;
16
import java.sql.SQLException;
17
import java.sql.Statement;
18
import java.sql.Types;
19

  
20

  
21
/**
22
 * DOCUMENT ME!
23
 *
24
 * @author Fernando Gonz?lez Cort?s
25
 */
26
public class MySQLDriver implements DBDriver, Driver {
27
    private static Exception driverException;
28

  
29
    static {
30
        try {
31
            Class.forName("com.mysql.jdbc.Driver").newInstance();
32
        } catch (Exception ex) {
33
            driverException = ex;
34
        }
35
    }
36

  
37
    private Connection conn;
38
    private Statement st;
39
    private ResultSet res;
40
    private long tableLength;
41

  
42
    /**
43
     * DOCUMENT ME!
44
     *
45
     * @param host DOCUMENT ME!
46
     * @param port DOCUMENT ME!
47
     * @param dbName DOCUMENT ME!
48
     * @param user DOCUMENT ME!
49
     * @param password DOCUMENT ME!
50
     *
51
     * @throws SQLException
52
     * @throws RuntimeException DOCUMENT ME!
53
     *
54
     * @see com.hardcode.gdbms.engine.data.DBDriver#connect(java.lang.String)
55
     */
56
    public void connect(String host, int port, String dbName, String user,
57
        String password) throws SQLException {
58
        if (driverException != null) {
59
            throw new RuntimeException(driverException);
60
        }
61

  
62
        String connectionString = "jdbc:mysql://" + host;
63
        if (port != -1){
64
        	connectionString += ":" + port;
65
        }
66
        
67
        connectionString += "/" + dbName;
68
        
69
        if (user != null){
70
        	connectionString += "?user=" + user + "&password=" + password;
71
        }
72
        
73
        conn = DriverManager.getConnection(connectionString);
74
    }
75

  
76
    /**
77
     * DOCUMENT ME!
78
     *
79
     * @throws SQLException
80
     *
81
     * @see com.hardcode.gdbms.engine.data.DBDriver#closeConnection()
82
     */
83
    public void closeConnection() throws SQLException {
84
        conn.close();
85
    }
86

  
87
    /**
88
     * @see com.hardcode.gdbms.engine.data.ReadDriver#getFieldValue(long, int)
89
     */
90
    public Value getFieldValue(long rowIndex, int fieldId)
91
        throws DriverException {
92
        try {
93
            fieldId++;
94
            res.absolute((int) rowIndex + 1);
95

  
96
            int type = res.getMetaData().getColumnType(fieldId);
97

  
98
            switch (type) {
99
                case Types.BIGINT:
100
                    return ValueFactory.createValue(res.getLong(fieldId));
101

  
102
                case Types.BIT:
103
                    return ValueFactory.createValue(res.getBoolean(fieldId));
104

  
105
                case Types.CHAR:
106
                    return ValueFactory.createValue(res.getString(fieldId));
107

  
108
                case Types.DATE:
109
                    return ValueFactory.createValue(res.getDate(fieldId));
110

  
111
                case Types.FLOAT:
112
                case Types.DOUBLE:
113
                    return ValueFactory.createValue(res.getDouble(fieldId));
114

  
115
                case Types.INTEGER:
116
                    return ValueFactory.createValue(res.getInt(fieldId));
117

  
118
                case Types.REAL:
119
                    return ValueFactory.createValue(res.getFloat(fieldId));
120

  
121
                case Types.VARCHAR:
122
                    return ValueFactory.createValue(res.getString(fieldId));
123

  
124
                case Types.VARBINARY:
125
                case Types.TINYINT:
126
                case Types.TIMESTAMP:
127
                case Types.TIME:
128
                case Types.SMALLINT:
129
                case Types.OTHER:
130
                case Types.NUMERIC:
131
                case Types.LONGVARCHAR:
132
                case Types.LONGVARBINARY:
133
                case Types.DECIMAL:
134
                case Types.BINARY:default:
135
                    throw new DriverException("Type not recognized: " + type);
136
            }
137
        } catch (SQLException e) {
138
            throw new DriverException(e);
139
        }
140
    }
141

  
142
    /**
143
     * @see com.hardcode.gdbms.engine.data.ReadDriver#getFieldCount()
144
     */
145
    public int getFieldCount() throws DriverException {
146
        try {
147
            return res.getMetaData().getColumnCount();
148
        } catch (SQLException e) {
149
            throw new DriverException(e);
150
        }
151
    }
152

  
153
    /**
154
     * @see com.hardcode.gdbms.engine.data.ReadDriver#getFieldName(int)
155
     */
156
    public String getFieldName(int fieldId) throws DriverException {
157
        try {
158
        	fieldId++;
159
            return res.getMetaData().getColumnName(fieldId);
160
        } catch (SQLException e) {
161
            throw new DriverException(e);
162
        }
163
    }
164

  
165
    /**
166
     * @see com.hardcode.gdbms.engine.data.ReadDriver#getRowCount()
167
     */
168
    public long getRowCount() throws DriverException {
169
        return tableLength;
170
    }
171

  
172
    /**
173
     * @see com.hardcode.driverManager.Driver#getName()
174
     */
175
    public String getName() {
176
        return "mysql";
177
    }
178

  
179
    /**
180
     * @see com.hardcode.gdbms.engine.data.DBDriver#openTable(java.lang.String)
181
     */
182
    public void openTable(String table) throws SQLException {
183
        st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
184
                ResultSet.CONCUR_READ_ONLY);
185
        res = st.executeQuery("select * from " + table);
186
        res.last();
187
        tableLength = res.getRow();
188
        res.beforeFirst();
189
    }
190

  
191
    /**
192
     * @see com.hardcode.gdbms.engine.data.DBDriver#closeTable()
193
     */
194
    public void closeTable() throws SQLException {
195
        res.close();
196
        st.close();
197
    }
198

  
199
    /**
200
     * @see com.hardcode.gdbms.engine.data.Delegable#executeSQL(java.lang.String)
201
     */
202
    public void executeSQL(String sql) throws SQLException {
203
        st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
204
                ResultSet.CONCUR_READ_ONLY);
205
        res = st.executeQuery(sql);
206
        res.last();
207
        tableLength = res.getRow();
208
        res.beforeFirst();
209
    }
210
}
0 211

  
trunk/libraries/libGDBMS/src/com/hardcode/gdbms/driver/csv/CSVDriver.java
1
package com.hardcode.gdbms.driver.csv;
2

  
3
import java.io.BufferedReader;
4
import java.io.File;
5
import java.io.FileReader;
6
import java.io.IOException;
7
import java.util.ArrayList;
8

  
9
import com.hardcode.driverManager.Driver;
10
import com.hardcode.gdbms.engine.data.DriverException;
11
import com.hardcode.gdbms.engine.data.FileDriver;
12
import com.hardcode.gdbms.engine.values.IntValue;
13
import com.hardcode.gdbms.engine.values.StringValue;
14
import com.hardcode.gdbms.engine.values.Value;
15

  
16

  
17
/**
18
 * Driver para ficheros csv, en el que la primera fila se toma como la que
19
 * define los nombres de los campos
20
 *
21
 * @author Fernando Gonz?lez Cort?s
22
 */
23
public class CSVDriver implements Driver, FileDriver {
24
    private BufferedReader reader;
25
    private ArrayList lineas;
26

  
27
    /**
28
     * @see com.hardcode.gdbms.driver.Driver#getName()
29
     */
30
    public String getName() {
31
        return "csv";
32
    }
33

  
34
    /**
35
     * @see com.hardcode.gdbms.data.DataSource#getFieldName(int)
36
     */
37
    public String getFieldName(int fieldId) throws DriverException {
38
        String[] campos = (String[]) lineas.get(0);
39

  
40
        return campos[fieldId];
41
    }
42

  
43
    /**
44
     * @see com.hardcode.gdbms.data.DataSource#getIntFieldValue(int, int)
45
     */
46
    public Value getFieldValue(long rowIndex, int fieldId)
47
        throws DriverException {
48
        String[] campos = (String[]) lineas.get((int) (rowIndex + 1));
49

  
50
        if (fieldId == 0) {
51
            IntValue value = new IntValue();
52
            value.setValue(Integer.parseInt(campos[fieldId]));
53

  
54
            return value;
55
        }
56

  
57
        StringValue value = new StringValue();
58
        value.setValue(campos[fieldId]);
59

  
60
        return value;
61
    }
62

  
63
    /**
64
     * @see com.hardcode.gdbms.data.DataSource#getFieldCount()
65
     */
66
    public int getFieldCount() throws DriverException {
67
        String[] campos = (String[]) lineas.get(0);
68

  
69
        return campos.length;
70
    }
71

  
72
    /**
73
     * @see com.hardcode.gdbms.data.DataSource#open(java.io.File)
74
     */
75
    public void open(File file) throws IOException {
76
        reader = new BufferedReader(new FileReader(file));
77

  
78
        lineas = new ArrayList();
79

  
80
        String aux;
81

  
82
        while ((aux = reader.readLine()) != null) {
83
            String[] campos = aux.split(";");
84
            lineas.add(campos);
85
        }
86
    }
87

  
88
    /**
89
     * @see com.hardcode.gdbms.data.DataSource#close()
90
     */
91
    public void close() throws IOException {
92
        reader.close();
93
    }
94

  
95
    /**
96
     * @see com.hardcode.gdbms.data.DataSource#getRowCount()
97
     */
98
    public long getRowCount() {
99
        return lineas.size() - 1;
100
    }
101

  
102
	/**
103
	 * @see com.hardcode.gdbms.engine.data.FileDriver#fileAccepted(java.io.File)
104
	 */
105
	public boolean fileAccepted(File f) {
106
		return f.getAbsolutePath().toUpperCase().endsWith("CSV");
107
	}
108
}
0 109

  
trunk/libraries/libGDBMS/src/com/hardcode/gdbms/driver/dbf/DBFDriver.java
1
package com.hardcode.gdbms.driver.dbf;
2

  
3
import java.io.File;
4
import java.io.IOException;
5
import java.util.Calendar;
6

  
7
import com.hardcode.driverManager.Driver;
8
import com.hardcode.gdbms.engine.data.DriverException;
9
import com.hardcode.gdbms.engine.data.FileDriver;
10
import com.hardcode.gdbms.engine.values.BooleanValue;
11
import com.hardcode.gdbms.engine.values.DoubleValue;
12
import com.hardcode.gdbms.engine.values.StringValue;
13
import com.hardcode.gdbms.engine.values.Value;
14
import com.hardcode.gdbms.engine.values.ValueFactory;
15

  
16

  
17
/**
18
 * DOCUMENT ME!
19
 *
20
 * @author Fernando Gonz?lez Cort?s
21
 */
22
public class DBFDriver implements Driver, FileDriver {
23
    private DbaseFile dbf = new DbaseFile();
24
    private char[] fieldTypes;
25

  
26
    /**
27
     * @see com.hardcode.driverManager.Driver#getName()
28
     */
29
    public String getName() {
30
        return "gdbms dbf driver";
31
    }
32

  
33
    /**
34
     * @see com.hardcode.gdbms.engine.data.GDBMSDriver#open(java.io.File)
35
     */
36
    public void open(File file) throws IOException {
37
        dbf.open(file);
38

  
39
        try {
40
            fieldTypes = new char[getFieldCount()];
41

  
42
            for (int i = 0; i < fieldTypes.length; i++) {
43
                fieldTypes[i] = dbf.getFieldType(i);
44
            }
45
        } catch (DriverException e) {
46
            throw new IOException(e.getMessage());
47
        }
48

  
49
        /*            memory = new Value[getRowCount()][getFieldCount()];
50
                    for (int i = 0; i < getRowCount(); i++){
51
                            for (int j = 0; j < getFieldCount(); j++){
52
                                    try {
53
                                                memory[i][j] = getFieldValueOff(i,j);
54
                                        } catch (IOException e) {
55
                                                e.printStackTrace();
56
                                        } catch (SemanticException e) {
57
                                                e.printStackTrace();
58
                                        }
59
                            }
60
                    }
61
            */
62
    }
63

  
64
    /**
65
     * @see com.hardcode.gdbms.engine.data.GDBMSDriver#close()
66
     */
67
    public void close() throws IOException {
68
        dbf.close();
69
    }
70

  
71
    /**
72
     * @see com.hardcode.gdbms.engine.data.ReadAccess#getFieldValue(long, int)
73
     */
74
    public Value getFieldValue(long rowIndex, int fieldId)
75
        throws DriverException {
76
        // Field Type (C  or M)
77
        char fieldType = fieldTypes[fieldId];
78

  
79
        if (fieldType == 'L') {
80
            return new BooleanValue(dbf.getBooleanFieldValue((int) rowIndex,
81
                    fieldId));
82

  
83
            /*                }else if (fieldType == 'N'){
84
                                    String strValue = dbf.getStringFieldValue(rowIndex, fieldId);
85
                                    long value = Long.parseLong(strValue);
86
                                    if ((value > Integer.MIN_VALUE) && (value < Integer.MAX_VALUE)){
87
                                            return new IntValue((int) value);
88
                                    }else{
89
                                            return new LongValue(value);
90
                                    }
91
            */
92
        } else if ((fieldType == 'F') || (fieldType == 'N')) {
93
            String strValue = dbf.getStringFieldValue((int) rowIndex, fieldId)
94
                                 .trim();
95

  
96
            //if (strValue.length() == 0) return null;
97
            double value = Double.parseDouble(strValue);
98

  
99
            return new DoubleValue(value);
100
        } else if (fieldType == 'C') {
101
            return new StringValue(dbf.getStringFieldValue((int) rowIndex,
102
                    fieldId).trim());
103
        } else if (fieldType == 'D') {
104
            String date = dbf.getStringFieldValue((int) rowIndex, fieldId).trim();
105

  
106
            //if (date.length() == 0) return null;
107
            String year = date.substring(0, 4);
108
            String month = date.substring(4, 2);
109
            String day = date.substring(6, 2);
110
            Calendar c = Calendar.getInstance();
111
            c.set(Calendar.YEAR, Integer.parseInt(year));
112
            c.set(Calendar.MONTH, Integer.parseInt(month));
113
            c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
114

  
115
            return ValueFactory.createValue(c.getTime());
116
        } else {
117
            throw new DriverException("Unknown field type");
118
        }
119
    }
120

  
121
    /**
122
     * @see com.hardcode.gdbms.engine.data.ReadAccess#getFieldCount()
123
     */
124
    public int getFieldCount() throws DriverException {
125
        return dbf.getFieldCount();
126
    }
127

  
128
    /**
129
     * @see com.hardcode.gdbms.engine.data.ReadAccess#getFieldName(int)
130
     */
131
    public String getFieldName(int fieldId) throws DriverException {
132
        return dbf.getFieldName(fieldId);
133
    }
134

  
135
    /**
136
     * @see com.hardcode.gdbms.engine.data.ReadAccess#getRowCount()
137
     */
138
    public long getRowCount() throws DriverException {
139
        return dbf.getRecordCount();
140
    }
141

  
142
	/**
143
	 * @see com.hardcode.gdbms.engine.data.FileDriver#fileAccepted(java.io.File)
144
	 */
145
	public boolean fileAccepted(File f) {
146
		return f.getAbsolutePath().toUpperCase().endsWith("DBF");
147
	}
148

  
149
    /*
150
     * @see com.hardcode.gdbms.engine.data.ReadAccess#getFieldValue(int, int)
151
     *
152
    public Value getFieldValue(int rowIndex, int fieldId) throws IOException, SemanticException {
153
            return memory[rowIndex][fieldId];
154
    }*/
155
}
0 156

  
trunk/libraries/libGDBMS/src/com/hardcode/gdbms/driver/dbf/DbaseFileHeader.java
1
/*
2
 * Created on 16-feb-2004
3
 *
4
 * To change the template for this generated file go to
5
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
6
 */
7
package com.hardcode.gdbms.driver.dbf;
8

  
9
import java.io.IOException;
10
import java.nio.ByteBuffer;
11
import java.nio.ByteOrder;
12
import java.util.Calendar;
13
import java.util.Date;
14

  
15
/**
16
 * Class to represent the header of a Dbase III file. Creation date: (5/15/2001
17
 * 5:15:30 PM)
18
 */
19
public class DbaseFileHeader {
20
    // Constant for the size of a record
21
    private int FILE_DESCRIPTOR_SIZE = 32;
22

  
23
    // type of the file, must be 03h
24
    private int myFileType = 0x03;
25

  
26
    // Date the file was last updated.
27
    private Date myUpdateDate = new Date();
28

  
29
    // Number of records in the datafile
30
    private int myNumRecords = 0;
31

  
32
    // Length of the header structure
33
    private int myHeaderLength;
34

  
35
    // Length of the records
36
    private int myRecordLength;
37

  
38
    // Number of fields in the record.
39
    private int myNumFields;
40

  
41
    // collection of header records.
42
    private DbaseFieldDescriptor[] myFieldDescriptions;
43
    
44
//TODO descomentar esto cuando tenga la clase WarningSupport
45
//    private WarningSupport warnings = new WarningSupport();
46

  
47
    /**
48
     * DbaseFileHreader constructor comment.
49
     */
50
    public DbaseFileHeader() {
51
        super();
52
    }
53

  
54
    /**
55
     * Add a column to this DbaseFileHeader. The type is one of (C N L or D)
56
     * character, number, logical(true/false), or date. The Field length is
57
     * the total length in bytes reserved for this column. The decimal count
58
     * only applies to numbers(N), and floating point values (F), and refers
59
     * to the number of characters to reserve after the decimal point.
60
     *
61
     * @param inFieldName DOCUMENT ME!
62
     * @param inFieldType DOCUMENT ME!
63
     * @param inFieldLength DOCUMENT ME!
64
     * @param inDecimalCount DOCUMENT ME!
65
     *
66
     * @throws Exception DOCUMENT ME!
67
     */
68
    public void addColumn(String inFieldName, char inFieldType,
69
        int inFieldLength, int inDecimalCount) throws Exception {
70
        if (inFieldLength <= 0) {
71
            inFieldLength = 1;
72
        }
73

  
74
        if (myFieldDescriptions == null) {
75
            myFieldDescriptions = new DbaseFieldDescriptor[0];
76
        }
77

  
78
        int tempLength = 1; // the length is used for the offset, and there is a * for deleted as the first byte
79
        DbaseFieldDescriptor[] tempFieldDescriptors = new DbaseFieldDescriptor[myFieldDescriptions.length +
80
            1];
81

  
82
        for (int i = 0; i < myFieldDescriptions.length; i++) {
83
            myFieldDescriptions[i].myFieldDataAddress = tempLength;
84
            tempLength = tempLength + myFieldDescriptions[i].myFieldLength;
85
            tempFieldDescriptors[i] = myFieldDescriptions[i];
86
        }
87

  
88
        tempFieldDescriptors[myFieldDescriptions.length] = new DbaseFieldDescriptor();
89
        tempFieldDescriptors[myFieldDescriptions.length].myFieldLength = inFieldLength;
90
        tempFieldDescriptors[myFieldDescriptions.length].myDecimalCount = inDecimalCount;
91
        tempFieldDescriptors[myFieldDescriptions.length].myFieldDataAddress = tempLength;
92

  
93
        // set the field name
94
        String tempFieldName = inFieldName;
95

  
96
        if (tempFieldName == null) {
97
            tempFieldName = "NoName";
98
        }
99

  
100
        if (tempFieldName.length() > 11) {
101
            tempFieldName = tempFieldName.substring(0, 11);
102
            warn("FieldName " + inFieldName +
103
                " is longer than 11 characters, truncating to " +
104
                tempFieldName);
105
        }
106

  
107
        tempFieldDescriptors[myFieldDescriptions.length].myFieldName = tempFieldName;
108

  
109
        // the field type
110
        if ((inFieldType == 'C') || (inFieldType == 'c')) {
111
            tempFieldDescriptors[myFieldDescriptions.length].myFieldType = 'C';
112

  
113
            if (inFieldLength > 254) {
114
                warn("Field Length for " + inFieldName + " set to " +
115
                    inFieldLength +
116
                    " Which is longer than 254, not consistent with dbase III");
117
            }
118
        } else if ((inFieldType == 'S') || (inFieldType == 's')) {
119
            tempFieldDescriptors[myFieldDescriptions.length].myFieldType = 'C';
120
            warn("Field type for " + inFieldName +
121
                " set to S which is flat out wrong people!, I am setting this to C, in the hopes you meant character.");
122

  
123
            if (inFieldLength > 254) {
124
                warn("Field Length for " + inFieldName + " set to " +
125
                    inFieldLength +
126
                    " Which is longer than 254, not consistent with dbase III");
127
            }
128

  
129
            tempFieldDescriptors[myFieldDescriptions.length].myFieldLength = 8;
130
        } else if ((inFieldType == 'D') || (inFieldType == 'd')) {
131
            tempFieldDescriptors[myFieldDescriptions.length].myFieldType = 'D';
132

  
133
            if (inFieldLength != 8) {
134
                warn("Field Length for " + inFieldName + " set to " +
135
                    inFieldLength + " Setting to 8 digets YYYYMMDD");
136
            }
137

  
138
            tempFieldDescriptors[myFieldDescriptions.length].myFieldLength = 8;
139
        } else if ((inFieldType == 'F') || (inFieldType == 'f')) {
140
            tempFieldDescriptors[myFieldDescriptions.length].myFieldType = 'F';
141

  
142
            if (inFieldLength > 20) {
143
                warn("Field Length for " + inFieldName + " set to " +
144
                    inFieldLength +
145
                    " Preserving length, but should be set to Max of 20 not valid for dbase IV, and UP specification, not present in dbaseIII.");
146
            }
147
        } else if ((inFieldType == 'N') || (inFieldType == 'n')) {
148
            tempFieldDescriptors[myFieldDescriptions.length].myFieldType = 'N';
149

  
150
            if (inFieldLength > 18) {
151
                warn("Field Length for " + inFieldName + " set to " +
152
                    inFieldLength +
153
                    " Preserving length, but should be set to Max of 18 for dbase III specification.");
154
            }
155

  
156
            if (inDecimalCount < 0) {
157
                warn("Field Decimal Position for " + inFieldName + " set to " +
158
                    inDecimalCount +
159
                    " Setting to 0 no decimal data will be saved.");
160
                tempFieldDescriptors[myFieldDescriptions.length].myDecimalCount = 0;
161
            }
162

  
163
            if (inDecimalCount > (inFieldLength - 1)) {
164
                warn("Field Decimal Position for " + inFieldName + " set to " +
165
                    inDecimalCount + " Setting to " + (inFieldLength - 1) +
166
                    " no non decimal data will be saved.");
167
                tempFieldDescriptors[myFieldDescriptions.length].myDecimalCount = inFieldLength -
168
                    1;
169
            }
170
        } else if ((inFieldType == 'L') || (inFieldType == 'l')) {
171
            tempFieldDescriptors[myFieldDescriptions.length].myFieldType = 'L';
172

  
173
            if (inFieldLength != 1) {
174
                warn("Field Length for " + inFieldName + " set to " +
175
                    inFieldLength +
176
                    " Setting to length of 1 for logical fields.");
177
            }
178

  
179
            tempFieldDescriptors[myFieldDescriptions.length].myFieldLength = 1;
180
        } else {
181
            throw new Exception("Undefined field type " + inFieldType +
182
                " For column " + inFieldName);
183
        }
184

  
185
        // the length of a record
186
        tempLength = tempLength +
187
            tempFieldDescriptors[myFieldDescriptions.length].myFieldLength;
188

  
189
        // set the new fields.
190
        myFieldDescriptions = tempFieldDescriptors;
191
        myHeaderLength = 33 + (32 * myFieldDescriptions.length);
192
        myNumFields = myFieldDescriptions.length;
193
        myRecordLength = tempLength;
194
    }
195

  
196
    /**
197
     * Remove a column from this DbaseFileHeader.
198
     *
199
     * @param inFieldName DOCUMENT ME!
200
     *
201
     * @return index of the removed column, -1 if no found
202
     */
203
    public int removeColumn(String inFieldName) {
204
        int retCol = -1;
205
        int tempLength = 1;
206
        DbaseFieldDescriptor[] tempFieldDescriptors = new DbaseFieldDescriptor[myFieldDescriptions.length -
207
            1];
208

  
209
        for (int i = 0, j = 0; i < myFieldDescriptions.length; i++) {
210
            if (!inFieldName.equalsIgnoreCase(
211
                        myFieldDescriptions[i].myFieldName.trim())) {
212
                // if this is the last field and we still haven't found the
213
                // named field
214
                if ((i == j) && (i == (myFieldDescriptions.length - 1))) {
215
                    System.err.println("Could not find a field named '" +
216
                        inFieldName + "' for removal");
217

  
218
                    return retCol;
219
                }
220

  
221
                tempFieldDescriptors[j] = myFieldDescriptions[i];
222
                tempFieldDescriptors[j].myFieldDataAddress = tempLength;
223
                tempLength += tempFieldDescriptors[j].myFieldLength;
224

  
225
                // only increment j on non-matching fields
226
                j++;
227
            } else {
228
                retCol = i;
229
            }
230
        }
231

  
232
        // set the new fields.
233
        myFieldDescriptions = tempFieldDescriptors;
234
        myHeaderLength = 33 + (32 * myFieldDescriptions.length);
235
        myNumFields = myFieldDescriptions.length;
236
        myRecordLength = tempLength;
237

  
238
        return retCol;
239
    }
240

  
241
    /**
242
     * DOCUMENT ME!
243
     *
244
     * @param inWarn DOCUMENT ME!
245
     */
246
    private void warn(String inWarn) {
247
//TODO Descomentar esto cuando tenga la clase warning support
248
//    	warnings.warn(inWarn);
249
    }
250

  
251
    /**
252
     * Return the Field Descriptor for the given field.
253
     *
254
     * @param inIndex DOCUMENT ME!
255
     *
256
     * @return DOCUMENT ME!
257
     */
258
    public DbaseFieldDescriptor getFieldDescription(int inIndex) {
259
        return myFieldDescriptions[inIndex];
260
    }
261

  
262
    // Retrieve the length of the field at the given index
263
    public int getFieldLength(int inIndex) {
264
        return myFieldDescriptions[inIndex].myFieldLength;
265
    }
266

  
267
    // Retrieve the location of the decimal point within the field.
268
    public int getFieldDecimalCount(int inIndex) {
269
        return myFieldDescriptions[inIndex].myDecimalCount;
270
    }
271

  
272
    // Retrieve the Name of the field at the given index
273
    public String getFieldName(int inIndex) {
274
        return myFieldDescriptions[inIndex].myFieldName;
275
    }
276

  
277
    // Retrieve the type of field at the given index
278
    public char getFieldType(int inIndex) {
279
        return myFieldDescriptions[inIndex].myFieldType;
280
    }
281

  
282
    /**
283
     * Return the date this file was last updated.
284
     *
285
     * @return DOCUMENT ME!
286
     */
287
    public Date getLastUpdateDate() {
288
        return myUpdateDate;
289
    }
290

  
291
    /**
292
     * Return the number of fields in the records.
293
     *
294
     * @return DOCUMENT ME!
295
     */
296
    public int getNumFields() {
297
        return myNumFields;
298
    }
299

  
300
    /**
301
     * Return the number of records in the file
302
     *
303
     * @return DOCUMENT ME!
304
     */
305
    public int getNumRecords() {
306
        return myNumRecords;
307
    }
308

  
309
    /**
310
     * Return the length of the records in bytes.
311
     *
312
     * @return DOCUMENT ME!
313
     */
314
    public int getRecordLength() {
315
        return myRecordLength;
316
    }
317

  
318
    /**
319
     * Return the length of the header
320
     *
321
     * @return DOCUMENT ME!
322
     */
323
    public int getHeaderLength() {
324
        return myHeaderLength;
325
    }
326

  
327
    /**
328
     * Read the header data from the DBF file.
329
     *
330
     * @param in DOCUMENT ME!
331
     *
332
     * @throws Exception DOCUMENT ME!
333
     */
334
    public void readHeader(ByteBuffer in) throws IOException {
335
        // type of file.
336
        myFileType = in.get();
337

  
338
        if (myFileType != 0x03) {
339
            throw new IOException("Unsupported DBF file Type " +
340
                Integer.toHexString(myFileType));
341
        }
342

  
343
        // parse the update date information.
344
        int tempUpdateYear = (int) in.get();
345
        int tempUpdateMonth = (int) in.get();
346
        int tempUpdateDay = (int) in.get();
347
        tempUpdateYear = tempUpdateYear + 1900;
348

  
349
        Calendar c = Calendar.getInstance();
350
        c.set(Calendar.YEAR, tempUpdateYear);
351
        c.set(Calendar.MONTH, tempUpdateMonth - 1);
352
        c.set(Calendar.DATE, tempUpdateDay);
353
        myUpdateDate = c.getTime();
354

  
355
        // read the number of records.
356
        in.order(ByteOrder.LITTLE_ENDIAN);
357
        myNumRecords = in.getInt();
358

  
359
        // read the length of the header structure.
360
        myHeaderLength = in.getShort();
361

  
362
        // read the length of a record
363
        myRecordLength = in.getShort();
364

  
365
		in.order(ByteOrder.BIG_ENDIAN);
366

  
367
        // skip the reserved bytes in the header.
368
        in.position(in.position()+20);
369

  
370
        // calculate the number of Fields in the header
371
        myNumFields = (myHeaderLength - FILE_DESCRIPTOR_SIZE - 1) / FILE_DESCRIPTOR_SIZE;
372

  
373
        // read all of the header records
374
        myFieldDescriptions = new DbaseFieldDescriptor[myNumFields];
375

  
376
        for (int i = 0; i < myNumFields; i++) {
377
            myFieldDescriptions[i] = new DbaseFieldDescriptor();
378

  
379
            // read the field name
380
            byte[] buffer = new byte[11];
381
            in.get(buffer);
382
            myFieldDescriptions[i].myFieldName = new String(buffer);
383

  
384
            // read the field type
385
            myFieldDescriptions[i].myFieldType = (char) in.get();
386

  
387
            // read the field data address, offset from the start of the record.
388
            myFieldDescriptions[i].myFieldDataAddress = in.getInt();
389

  
390
            // read the field length in bytes
391
            int tempLength = (int) in.get();
392

  
393
            if (tempLength < 0) {
394
                tempLength = tempLength + 256;
395
            }
396

  
397
            myFieldDescriptions[i].myFieldLength = tempLength;
398

  
399
            // read the field decimal count in bytes
400
            myFieldDescriptions[i].myDecimalCount = (int) in.get();
401

  
402
            // read the reserved bytes.
403
			in.position(in.position()+14);
404
        }
405

  
406
        // Last byte is a marker for the end of the field definitions.
407
        in.get();
408
    }
409

  
410
    /**
411
     * Set the number of records in the file
412
     *
413
     * @param inNumRecords DOCUMENT ME!
414
     */
415
    protected void setNumRecords(int inNumRecords) {
416
        myNumRecords = inNumRecords;
417
    }
418

  
419
    /*
420
     * Write the header data to the DBF file.
421
     *
422
     * @param out DOCUMENT ME!
423
     *
424
     * @throws Exception DOCUMENT ME!
425
     *
426
    public void writeHeader(LEDataOutputStream out) throws Exception {
427
        // write the output file type.
428
        out.writeByte(myFileType);
429

  
430
        // write the date stuff
431
        Calendar c = Calendar.getInstance();
432
        c.setTime(new Date());
433
        out.writeByte(c.get(Calendar.YEAR) - 1900);
434
        out.writeByte(c.get(Calendar.MONTH) + 1);
435
        out.writeByte(c.get(Calendar.DAY_OF_MONTH));
436

  
437
        // write the number of records in the datafile.
438
        out.writeInt(myNumRecords);
439

  
440
        // write the length of the header structure.
441
        out.writeShort(myHeaderLength);
442

  
443
        // write the length of a record
444
        out.writeShort(myRecordLength);
445

  
446
        // write the reserved bytes in the header
447
        for (int i = 0; i < 20; i++)
448
            out.writeByte(0);
449

  
450
        // write all of the header records
451
        int tempOffset = 0;
452

  
453
        for (int i = 0; i < myFieldDescriptions.length; i++) {
454
            // write the field name
455
            for (int j = 0; j < 11; j++) {
456
                if (myFieldDescriptions[i].myFieldName.length() > j) {
457
                    out.writeByte((int) myFieldDescriptions[i].myFieldName.charAt(
458
                            j));
459
                } else {
460
                    out.writeByte(0);
461
                }
462
            }
463

  
464
            // write the field type
465
            out.writeByte(myFieldDescriptions[i].myFieldType);
466

  
467
            // write the field data address, offset from the start of the record.
468
            out.writeInt(tempOffset);
469
            tempOffset += myFieldDescriptions[i].myFieldLength;
470

  
471
            // write the length of the field.
472
            out.writeByte(myFieldDescriptions[i].myFieldLength);
473

  
474
            // write the decimal count.
475
            out.writeByte(myFieldDescriptions[i].myDecimalCount);
476

  
477
            // write the reserved bytes.
478
            for (int j = 0; j < 14; j++)
479
                out.writeByte(0);
480
        }
481

  
482
        // write the end of the field definitions marker
483
        out.writeByte(0x0D);
484
    }
485
*/
486
    /**
487
     * Class for holding the information assicated with a record.
488
     */
489
    class DbaseFieldDescriptor {
490
        // Field Name
491
        String myFieldName;
492

  
493
        // Field Type (C N L D F or M)
494
        char myFieldType;
495

  
496
        // Field Data Address offset from the start of the record.
497
        int myFieldDataAddress;
498

  
499
        // Length of the data in bytes
500
        int myFieldLength;
501

  
502
        // Field decimal count in Binary, indicating where the decimal is
503
        int myDecimalCount;
504
    }
505
}
0 506

  
trunk/libraries/libGDBMS/src/com/hardcode/gdbms/driver/dbf/DbaseFile.java
1
/*
2
 * Created on 16-feb-2004
3
 *
4
 * To change the template for this generated file go to
5
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
6
 */
7
package com.hardcode.gdbms.driver.dbf;
8

  
9
/**
10
 */
11
import java.io.File;
12
import java.io.FileInputStream;
13
import java.io.IOException;
... This diff was truncated because it exceeds the maximum size that can be displayed.

Also available in: Unified diff