diff options
author | James Ahlborn <jtahlborn@yahoo.com> | 2013-08-16 02:09:48 +0000 |
---|---|---|
committer | James Ahlborn <jtahlborn@yahoo.com> | 2013-08-16 02:09:48 +0000 |
commit | 417fb06208f50cbf164a1c101ac03c7bae0856d8 (patch) | |
tree | 52217c1c09bc71377ca0f422ed43d24d6917a178 /test/src/java/com/healthmarketscience/jackcess | |
parent | 790b943d773fc72a11089b6acaf17aa341f92ae4 (diff) | |
download | jackcess-417fb06208f50cbf164a1c101ac03c7bae0856d8.tar.gz jackcess-417fb06208f50cbf164a1c101ac03c7bae0856d8.zip |
move files into standard maven dir structure
git-svn-id: https://svn.code.sf.net/p/jackcess/code/jackcess/trunk@781 f203690c-595d-4dc9-a70b-905162fa7fd2
Diffstat (limited to 'test/src/java/com/healthmarketscience/jackcess')
23 files changed, 0 insertions, 8731 deletions
diff --git a/test/src/java/com/healthmarketscience/jackcess/BigIndexTest.java b/test/src/java/com/healthmarketscience/jackcess/BigIndexTest.java deleted file mode 100644 index 32f228e..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/BigIndexTest.java +++ /dev/null @@ -1,211 +0,0 @@ -/* -Copyright (c) 2008 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Random; - -import junit.framework.TestCase; - -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import com.healthmarketscience.jackcess.impl.TableImpl; -import com.healthmarketscience.jackcess.impl.IndexImpl; - -/** - * @author james - */ -public class BigIndexTest extends TestCase { - - public BigIndexTest(String name) { - super(name); - } - - public void testComplexIndex() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.COMP_INDEX, true)) { - // this file has an index with "compressed" entries and node pages - Database db = open(testDB); - TableImpl t = (TableImpl)db.getTable("Table1"); - IndexImpl index = t.getIndex("CD_AGENTE"); - assertFalse(index.isInitialized()); - assertEquals(512, countRows(t)); - assertEquals(512, index.getIndexData().getEntryCount()); - db.close(); - } - } - - public void testBigIndex() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.BIG_INDEX)) { - // this file has an index with "compressed" entries and node pages - Database db = open(testDB); - TableImpl t = (TableImpl)db.getTable("Table1"); - IndexImpl index = t.getIndex("col1"); - assertFalse(index.isInitialized()); - assertEquals(0, countRows(t)); - assertEquals(0, index.getIndexData().getEntryCount()); - db.close(); - - DatabaseTest._autoSync = false; - try { - - String extraText = " some random text to fill out the index and make it fill up pages with lots of extra bytes so i will keep typing until i think that i probably have enough text in the index entry so that i do not need to add as many entries in order"; - - // copy to temp file and attempt to edit - db = openCopy(testDB); - t = (TableImpl)db.getTable("Table1"); - index = t.getIndex("col1"); - - // add 2,000 (pseudo) random entries to the table - Random rand = new Random(13L); - for(int i = 0; i < 2000; ++i) { - if((i == 850) || (i == 1850)) { - int end = i + 50; - List<Object[]> rows = new ArrayList<Object[]>(50); - for(; i < end; ++i) { - int nextInt = rand.nextInt(Integer.MAX_VALUE); - String nextVal = "" + nextInt + extraText; - if(((i + 1) % 333) == 0) { - nextVal = null; - } - rows.add(new Object[]{nextVal, - "this is some row data " + nextInt}); - } - t.addRows(rows); - --i; - } else { - int nextInt = rand.nextInt(Integer.MAX_VALUE); - String nextVal = "" + nextInt + extraText; - if(((i + 1) % 333) == 0) { - nextVal = null; - } - t.addRow(nextVal, "this is some row data " + nextInt); - } - } - - index.getIndexData().validate(); - - db.flush(); - t = null; - System.gc(); - - t = (TableImpl)db.getTable("Table1"); - index = t.getIndex("col1"); - - // make sure all entries are there and correctly ordered - String firstValue = " "; - String prevValue = firstValue; - int rowCount = 0; - List<String> firstTwo = new ArrayList<String>(); - for(Map<String,Object> row : CursorBuilder.createCursor(index)) { - String origVal = (String)row.get("col1"); - String val = origVal; - if(val == null) { - val = firstValue; - } - assertTrue("" + prevValue + " <= " + val + " " + rowCount, - prevValue.compareTo(val) <= 0); - if(firstTwo.size() < 2) { - firstTwo.add(origVal); - } - prevValue = val; - ++rowCount; - } - - assertEquals(2000, rowCount); - - index.getIndexData().validate(); - - // delete an entry in the middle - Cursor cursor = CursorBuilder.createCursor(index); - for(int i = 0; i < (rowCount / 2); ++i) { - assertTrue(cursor.moveToNextRow()); - } - cursor.deleteCurrentRow(); - --rowCount; - - // remove all but the first two entries (from the end) - cursor.afterLast(); - for(int i = 0; i < (rowCount - 2); ++i) { - assertTrue(cursor.moveToPreviousRow()); - cursor.deleteCurrentRow(); - } - - index.getIndexData().validate(); - - List<String> found = new ArrayList<String>(); - for(Map<String,Object> row : CursorBuilder.createCursor(index)) { - found.add((String)row.get("col1")); - } - - assertEquals(firstTwo, found); - - // remove remaining entries - cursor = CursorBuilder.createCursor(t); - for(int i = 0; i < 2; ++i) { - assertTrue(cursor.moveToNextRow()); - cursor.deleteCurrentRow(); - } - - assertFalse(cursor.moveToNextRow()); - assertFalse(cursor.moveToPreviousRow()); - - index.getIndexData().validate(); - - // add 50 (pseudo) random entries to the table - rand = new Random(42L); - for(int i = 0; i < 50; ++i) { - int nextInt = rand.nextInt(Integer.MAX_VALUE); - String nextVal = "some prefix " + nextInt + extraText; - if(((i + 1) % 3333) == 0) { - nextVal = null; - } - t.addRow(nextVal, "this is some row data " + nextInt); - } - - index.getIndexData().validate(); - - cursor = CursorBuilder.createCursor(index); - while(cursor.moveToNextRow()) { - cursor.deleteCurrentRow(); - } - - index.getIndexData().validate(); - - db.close(); - - } finally { - DatabaseTest._autoSync = Database.DEFAULT_AUTO_SYNC; - } - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/ComplexColumnTest.java b/test/src/java/com/healthmarketscience/jackcess/ComplexColumnTest.java deleted file mode 100644 index 173a53c..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/ComplexColumnTest.java +++ /dev/null @@ -1,485 +0,0 @@ -/* -Copyright (c) 2011 James Ahlborn - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA -*/ - -package com.healthmarketscience.jackcess; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.complex.Attachment; -import com.healthmarketscience.jackcess.complex.ComplexDataType; -import com.healthmarketscience.jackcess.complex.ComplexValueForeignKey; -import com.healthmarketscience.jackcess.complex.SingleValue; -import com.healthmarketscience.jackcess.complex.UnsupportedValue; -import com.healthmarketscience.jackcess.complex.Version; -import com.healthmarketscience.jackcess.impl.ByteUtil; -import com.healthmarketscience.jackcess.impl.ColumnImpl; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import com.healthmarketscience.jackcess.impl.PageChannel; -import junit.framework.TestCase; - - -/** - * - * @author James Ahlborn - */ -public class ComplexColumnTest extends TestCase -{ - - public ComplexColumnTest(String name) { - super(name); - } - - public void testVersions() throws Exception - { - for(final TestDB testDB : TestDB.getSupportedForBasename(Basename.COMPLEX)) { - Database db = openCopy(testDB); - db.setTimeZone(TEST_TZ); - - Table t1 = db.getTable("Table1"); - Column col = t1.getColumn("append-memo-data"); - assertTrue(col.isAppendOnly()); - Column verCol = col.getVersionHistoryColumn(); - assertNotNull(verCol); - assertEquals(ComplexDataType.VERSION_HISTORY, - verCol.getComplexInfo().getType()); - - for(Map<String,Object> row : t1) { - String rowId = (String)row.get("id"); - ComplexValueForeignKey complexValueFk = - (ComplexValueForeignKey)verCol.getRowValue(row); - - String curValue = (String)col.getRowValue(row); - - if(rowId.equals("row1")) { - checkVersions(1, complexValueFk, curValue); - } else if(rowId.equals("row2")) { - checkVersions(2, complexValueFk, curValue, - "row2-memo", new Date(1315876862334L)); - } else if(rowId.equals("row3")) { - checkVersions(3, complexValueFk, curValue, - "row3-memo-again", new Date(1315876965382L), - "row3-memo-revised", new Date(1315876953077L), - "row3-memo", new Date(1315876879126L)); - } else if(rowId.equals("row4")) { - checkVersions(4, complexValueFk, curValue, - "row4-memo", new Date(1315876945758L)); - } else { - assertTrue(false); - } - } - - Object[] row8 = {"row8", Column.AUTO_NUMBER, "some-data", "row8-memo", - Column.AUTO_NUMBER, Column.AUTO_NUMBER}; - t1.addRow(row8); - - ComplexValueForeignKey row8ValFk = (ComplexValueForeignKey) - verCol.getRowValue(row8); - Date upTime = new Date(); - row8ValFk.addVersion("row8-memo", upTime); - checkVersions(row8ValFk.get(), row8ValFk, "row8-memo", - "row8-memo", upTime); - - Cursor cursor = CursorBuilder.createCursor(t1); - assertTrue(cursor.findFirstRow(t1.getColumn("id"), "row3")); - ComplexValueForeignKey row3ValFk = (ComplexValueForeignKey) - cursor.getCurrentRowValue(verCol); - cursor.setCurrentRowValue(col, "new-value"); - Version v = row3ValFk.addVersion("new-value", upTime); - checkVersions(3, row3ValFk, "new-value", - "new-value", upTime, - "row3-memo-again", new Date(1315876965382L), - "row3-memo-revised", new Date(1315876953077L), - "row3-memo", new Date(1315876879126L)); - - try { - v.update(); - fail("UnsupportedOperationException should have been thrown"); - } catch(UnsupportedOperationException expected) { - // success - } - - checkVersions(3, row3ValFk, "new-value", - "new-value", upTime, - "row3-memo-again", new Date(1315876965382L), - "row3-memo-revised", new Date(1315876953077L), - "row3-memo", new Date(1315876879126L)); - - try { - v.delete(); - fail("UnsupportedOperationException should have been thrown"); - } catch(UnsupportedOperationException expected) { - // success - } - - checkVersions(3, row3ValFk, "new-value", - "new-value", upTime, - "row3-memo-again", new Date(1315876965382L), - "row3-memo-revised", new Date(1315876953077L), - "row3-memo", new Date(1315876879126L)); - - try { - v.getComplexValueForeignKey().deleteAllValues(); - fail("UnsupportedOperationException should have been thrown"); - } catch(UnsupportedOperationException expected) { - // success - } - - checkVersions(3, row3ValFk, "new-value", - "new-value", upTime, - "row3-memo-again", new Date(1315876965382L), - "row3-memo-revised", new Date(1315876953077L), - "row3-memo", new Date(1315876879126L)); - - db.close(); - } - } - - public void testAttachments() throws Exception - { - for(final TestDB testDB : TestDB.getSupportedForBasename(Basename.COMPLEX)) { - - Database db = openCopy(testDB); - - Table t1 = db.getTable("Table1"); - Column col = t1.getColumn("attach-data"); - assertEquals(ComplexDataType.ATTACHMENT, - col.getComplexInfo().getType()); - - for(Map<String,Object> row : t1) { - String rowId = (String)row.get("id"); - ComplexValueForeignKey complexValueFk = - (ComplexValueForeignKey)col.getRowValue(row); - - if(rowId.equals("row1")) { - checkAttachments(1, complexValueFk); - } else if(rowId.equals("row2")) { - checkAttachments(2, complexValueFk, "test_data.txt", "test_data2.txt"); - } else if(rowId.equals("row3")) { - checkAttachments(3, complexValueFk); - } else if(rowId.equals("row4")) { - checkAttachments(4, complexValueFk, "test_data2.txt"); - } else { - assertTrue(false); - } - } - - Object[] row8 = {"row8", Column.AUTO_NUMBER, "some-data", "row8-memo", - Column.AUTO_NUMBER, Column.AUTO_NUMBER}; - t1.addRow(row8); - - ComplexValueForeignKey row8ValFk = (ComplexValueForeignKey) - col.getRowValue(row8); - row8ValFk.addAttachment(null, "test_data.txt", "txt", - getFileBytes("test_data.txt"), null, null); - checkAttachments(row8ValFk.get(), row8ValFk, "test_data.txt"); - row8ValFk.addEncodedAttachment(null, "test_data2.txt", "txt", - getEncodedFileBytes("test_data2.txt"), null, - null); - checkAttachments(row8ValFk.get(), row8ValFk, "test_data.txt", - "test_data2.txt"); - - Cursor cursor = CursorBuilder.createCursor(t1); - assertTrue(cursor.findFirstRow(t1.getColumn("id"), "row4")); - ComplexValueForeignKey row4ValFk = (ComplexValueForeignKey) - cursor.getCurrentRowValue(col); - Attachment a = row4ValFk.addAttachment(null, "test_data.txt", "txt", - getFileBytes("test_data.txt"), null, - null); - checkAttachments(4, row4ValFk, "test_data2.txt", "test_data.txt"); - - a.setFileType("zip"); - a.setFileName("some_data.zip"); - byte[] newBytes = "this is not a zip file".getBytes("US-ASCII"); - a.setFileData(newBytes); - a.update(); - - Attachment updated = row4ValFk.getAttachments().get(1); - assertNotSame(updated, a); - assertEquals("zip", updated.getFileType()); - assertEquals("some_data.zip", updated.getFileName()); - assertTrue(Arrays.equals(newBytes, updated.getFileData())); - byte[] encBytes = updated.getEncodedFileData(); - assertEquals(newBytes.length + 28, encBytes.length); - ByteBuffer bb = PageChannel.wrap(encBytes); - assertEquals(0, bb.getInt()); - assertTrue(ByteUtil.matchesRange(bb, 28, newBytes)); - - updated.delete(); - checkAttachments(4, row4ValFk, "test_data2.txt"); - row4ValFk.getAttachments().get(0).delete(); - checkAttachments(4, row4ValFk); - - assertTrue(cursor.findFirstRow(t1.getColumn("id"), "row2")); - ComplexValueForeignKey row2ValFk = (ComplexValueForeignKey) - cursor.getCurrentRowValue(col); - row2ValFk.deleteAllValues(); - checkAttachments(2, row2ValFk); - - db.close(); - } - } - - public void testMultiValues() throws Exception - { - for(final TestDB testDB : TestDB.getSupportedForBasename(Basename.COMPLEX)) { - - Database db = openCopy(testDB); - - Table t1 = db.getTable("Table1"); - Column col = t1.getColumn("multi-value-data"); - assertEquals(ComplexDataType.MULTI_VALUE, - col.getComplexInfo().getType()); - - for(Map<String,Object> row : t1) { - String rowId = (String)row.get("id"); - ComplexValueForeignKey complexValueFk = - (ComplexValueForeignKey)col.getRowValue(row); - - if(rowId.equals("row1")) { - checkMultiValues(1, complexValueFk); - } else if(rowId.equals("row2")) { - checkMultiValues(2, complexValueFk, "value1", "value4"); - } else if(rowId.equals("row3")) { - checkMultiValues(3, complexValueFk, - "value1", "value2", "value3", "value4"); - } else if(rowId.equals("row4")) { - checkMultiValues(4, complexValueFk); - } else { - assertTrue(false); - } - } - - Object[] row8 = {"row8", Column.AUTO_NUMBER, "some-data", "row8-memo", - Column.AUTO_NUMBER, Column.AUTO_NUMBER}; - t1.addRow(row8); - - ComplexValueForeignKey row8ValFk = (ComplexValueForeignKey) - col.getRowValue(row8); - row8ValFk.addMultiValue("value1"); - row8ValFk.addMultiValue("value2"); - checkMultiValues(row8ValFk.get(), row8ValFk, "value1", "value2"); - - Cursor cursor = CursorBuilder.createCursor(t1); - assertTrue(cursor.findFirstRow(t1.getColumn("id"), "row2")); - ComplexValueForeignKey row2ValFk = (ComplexValueForeignKey) - cursor.getCurrentRowValue(col); - SingleValue v = row2ValFk.addMultiValue("value2"); - row2ValFk.addMultiValue("value3"); - checkMultiValues(2, row2ValFk, "value1", "value4", "value2", "value3"); - - v.set("value5"); - v.update(); - checkMultiValues(2, row2ValFk, "value1", "value4", "value5", "value3"); - - v.delete(); - checkMultiValues(2, row2ValFk, "value1", "value4", "value3"); - row2ValFk.getMultiValues().get(0).delete(); - checkMultiValues(2, row2ValFk, "value4", "value3"); - row2ValFk.getMultiValues().get(1).delete(); - checkMultiValues(2, row2ValFk, "value4"); - row2ValFk.getMultiValues().get(0).delete(); - checkMultiValues(2, row2ValFk); - - assertTrue(cursor.findFirstRow(t1.getColumn("id"), "row3")); - ComplexValueForeignKey row3ValFk = (ComplexValueForeignKey) - cursor.getCurrentRowValue(col); - row3ValFk.deleteAllValues(); - checkMultiValues(3, row3ValFk); - - db.close(); - } - } - - public void testUnsupported() throws Exception - { - for(final TestDB testDB : TestDB.getSupportedForBasename(Basename.UNSUPPORTED)) { - - Database db = openCopy(testDB); - - Table t1 = db.getTable("Test"); - Column col = t1.getColumn("UnknownComplex"); - assertEquals(ComplexDataType.UNSUPPORTED, - col.getComplexInfo().getType()); - - for(Map<String,Object> row : t1) { - Integer rowId = (Integer)row.get("ID"); - ComplexValueForeignKey complexValueFk = - (ComplexValueForeignKey)col.getRowValue(row); - - if(rowId.equals(1)) { - checkUnsupportedValues(1, complexValueFk, - "RawData: FF FE 62 61 7A"); - } else if(rowId.equals(2)) { - checkUnsupportedValues(2, complexValueFk, "RawData: FF FE 66 6F 6F", "RawData: FF FE 62 61 7A"); - } else if(rowId.equals(3)) { - checkUnsupportedValues(3, complexValueFk); - } else { - assertTrue(false); - } - } - - db.close(); - } - } - - private static void checkVersions( - int cValId, ComplexValueForeignKey complexValueFk, - String curValue, Object... versionInfos) - throws Exception - { - assertEquals(cValId, complexValueFk.get()); - - List<Version> versions = complexValueFk.getVersions(); - if(versionInfos.length == 0) { - assertTrue(versions.isEmpty()); - assertNull(curValue); - } else { - assertEquals(versionInfos.length / 2, versions.size()); - assertEquals(curValue, versions.get(0).getValue()); - for(int i = 0; i < versionInfos.length; i+=2) { - String value = (String)versionInfos[i]; - Date modDate = (Date)versionInfos[i+1]; - Version v = versions.get(i/2); - assertEquals(value, v.getValue()); - assertSameDate(modDate, v.getModifiedDate()); - } - } - } - - private static void checkAttachments( - int cValId, ComplexValueForeignKey complexValueFk, - String... fileNames) - throws Exception - { - assertEquals(cValId, complexValueFk.get()); - - List<Attachment> attachments = complexValueFk.getAttachments(); - if(fileNames.length == 0) { - assertTrue(attachments.isEmpty()); - } else { - assertEquals(fileNames.length, attachments.size()); - for(int i = 0; i < fileNames.length; ++i) { - String fname = fileNames[i]; - Attachment a = attachments.get(i); - assertEquals(fname, a.getFileName()); - assertEquals("txt", a.getFileType()); - assertTrue(Arrays.equals(getFileBytes(fname), a.getFileData())); - assertTrue(Arrays.equals(getEncodedFileBytes(fname), - a.getEncodedFileData())); - } - } - } - - private static void checkMultiValues( - int cValId, ComplexValueForeignKey complexValueFk, - Object... expectedValues) - throws Exception - { - assertEquals(cValId, complexValueFk.get()); - - List<SingleValue> values = complexValueFk.getMultiValues(); - if(expectedValues.length == 0) { - assertTrue(values.isEmpty()); - } else { - assertEquals(expectedValues.length, values.size()); - for(int i = 0; i < expectedValues.length; ++i) { - Object value = expectedValues[i]; - SingleValue v = values.get(i); - assertEquals(value, v.get()); - } - } - } - - private static void checkUnsupportedValues( - int cValId, ComplexValueForeignKey complexValueFk, - String... expectedValues) - throws Exception - { - assertEquals(cValId, complexValueFk.get()); - - List<UnsupportedValue> values = complexValueFk.getUnsupportedValues(); - if(expectedValues.length == 0) { - assertTrue(values.isEmpty()); - } else { - assertEquals(expectedValues.length, values.size()); - for(int i = 0; i < expectedValues.length; ++i) { - String value = expectedValues[i]; - UnsupportedValue v = values.get(i); - assertEquals(1, v.getValues().size()); - Object rv = v.get("Value"); - assertTrue(ColumnImpl.isRawData(rv)); - assertEquals(value, rv.toString()); - } - } - } - - private static byte[] getFileBytes(String fname) throws Exception - { - if("test_data.txt".equals(fname)) { - return TEST_BYTES; - } - if("test_data2.txt".equals(fname)) { - return TEST2_BYTES; - } - throw new RuntimeException("unexpected bytes"); - } - - private static byte[] getEncodedFileBytes(String fname) throws Exception - { - if("test_data.txt".equals(fname)) { - return TEST_ENC_BYTES; - } - if("test_data2.txt".equals(fname)) { - return TEST2_ENC_BYTES; - } - throw new RuntimeException("unexpected bytes"); - } - - private static byte b(int i) { return (byte)i; } - - private static byte[] getAsciiBytes(String str) { - try { - return str.getBytes("US-ASCII"); - } catch(Exception e) { - throw new RuntimeException(e); - } - } - - private static final byte[] TEST_ENC_BYTES = new byte[] { - b(0x01),b(0x00),b(0x00),b(0x00),b(0x3A),b(0x00),b(0x00),b(0x00),b(0x78),b(0x5E),b(0x13),b(0x61),b(0x60),b(0x60),b(0x60),b(0x04),b(0x62),b(0x16),b(0x20),b(0x2E),b(0x61),b(0xA8),b(0x00),b(0x62), - b(0x20),b(0x9D),b(0x91),b(0x59),b(0xAC),b(0x00),b(0x44),b(0xC5),b(0xF9),b(0xB9),b(0xA9),b(0x0A),b(0x25),b(0xA9),b(0xC5),b(0x25),b(0x0A),b(0x29),b(0x89),b(0x25),b(0x89),b(0x0A),b(0x69),b(0xF9), - b(0x45),b(0x0A),b(0x89),b(0x25),b(0x25),b(0x89),b(0xC9),b(0x19),b(0xB9),b(0xA9),b(0x79),b(0x25),b(0x7A),b(0x00),b(0x52),b(0xA9),b(0x0F),b(0x7A) - }; - - private static final byte[] TEST_BYTES = getAsciiBytes("this is some test data for attachment."); - - private static final byte[] TEST2_ENC_BYTES = new byte[] { - b(0x01),b(0x00),b(0x00),b(0x00),b(0x3F),b(0x00),b(0x00),b(0x00),b(0x78),b(0x5E),b(0x13),b(0x61),b(0x60),b(0x60),b(0x60),b(0x04),b(0x62),b(0x16),b(0x20),b(0x2E),b(0x61),b(0xA8),b(0x00),b(0x62), - b(0x20),b(0x9D),b(0x91),b(0x59),b(0xAC),b(0x00),b(0x44),b(0xC5),b(0xF9),b(0xB9),b(0xA9),b(0x0A),b(0xB9),b(0xF9),b(0x45),b(0xA9),b(0x0A),b(0x25),b(0xA9),b(0xC5),b(0x25),b(0x0A),b(0x29),b(0x89), - b(0x25),b(0x89),b(0x0A),b(0x69),b(0xF9),b(0x45),b(0x0A),b(0x89),b(0x25),b(0x25),b(0x89),b(0xC9),b(0x19),b(0xB9),b(0xA9),b(0x79),b(0x25),b(0x7A),b(0x00),b(0xA5),b(0x0B),b(0x11),b(0x4D) - }; - - private static final byte[] TEST2_BYTES = getAsciiBytes("this is some more test data for attachment."); - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/CursorBuilderTest.java b/test/src/java/com/healthmarketscience/jackcess/CursorBuilderTest.java deleted file mode 100644 index affd28c..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/CursorBuilderTest.java +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess; - -import junit.framework.TestCase; - -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import com.healthmarketscience.jackcess.impl.IndexImpl; - -/** - * @author James Ahlborn - */ -public class CursorBuilderTest extends TestCase { - - public CursorBuilderTest(String name) throws Exception { - super(name); - } - - private static void assertCursor( - Cursor expected, Cursor found) - { - assertSame(expected.getTable(), found.getTable()); - if(expected instanceof IndexCursor) { - assertSame(((IndexCursor)expected).getIndex(), - ((IndexCursor)found).getIndex()); - } - - assertEquals(expected.getSavepoint().getCurrentPosition(), - found.getSavepoint().getCurrentPosition()); - } - - public void test() throws Exception - { - for (final TestDB indexCursorDB : CursorTest.INDEX_CURSOR_DBS) { - Database db = CursorTest.createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - IndexImpl idx = (IndexImpl)table.getIndexes().get(0); - - Cursor expected = CursorBuilder.createCursor(table); - - Cursor found = new CursorBuilder(table).toCursor(); - assertCursor(expected, found); - - expected = CursorBuilder.createCursor(idx); - found = new CursorBuilder(table) - .setIndex(idx) - .toCursor(); - assertCursor(expected, found); - - expected = CursorBuilder.createCursor(idx); - found = new CursorBuilder(table) - .setIndexByName("id") - .toCursor(); - assertCursor(expected, found); - - try { - new CursorBuilder(table) - .setIndexByName("foo"); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException ignored) { - // success - } - - expected = CursorBuilder.createCursor(idx); - found = new CursorBuilder(table) - .setIndexByColumns(table.getColumn("id")) - .toCursor(); - assertCursor(expected, found); - - try { - new CursorBuilder(table) - .setIndexByColumns(table.getColumn("value")); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException ignored) { - // success - } - - try { - new CursorBuilder(table) - .setIndexByColumns(table.getColumn("id"), table.getColumn("value")); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException ignored) { - // success - } - - expected = CursorBuilder.createCursor(table); - expected.beforeFirst(); - found = new CursorBuilder(table) - .beforeFirst() - .toCursor(); - assertCursor(expected, found); - - expected = CursorBuilder.createCursor(table); - expected.afterLast(); - found = new CursorBuilder(table) - .afterLast() - .toCursor(); - assertCursor(expected, found); - - expected = CursorBuilder.createCursor(table); - expected.moveNextRows(2); - Cursor.Savepoint sp = expected.getSavepoint(); - found = new CursorBuilder(table) - .afterLast() - .restoreSavepoint(sp) - .toCursor(); - assertCursor(expected, found); - - expected = CursorBuilder.createCursor(idx); - expected.moveNextRows(2); - sp = expected.getSavepoint(); - found = new CursorBuilder(table) - .setIndex(idx) - .beforeFirst() - .restoreSavepoint(sp) - .toCursor(); - assertCursor(expected, found); - - expected = CursorBuilder.createCursor(idx, - idx.constructIndexRowFromEntry(3), - null); - found = new CursorBuilder(table) - .setIndex(idx) - .setStartEntry(3) - .toCursor(); - assertCursor(expected, found); - - expected = CursorBuilder.createCursor(idx, - idx.constructIndexRowFromEntry(3), - false, - idx.constructIndexRowFromEntry(7), - false); - found = new CursorBuilder(table) - .setIndex(idx) - .setStartEntry(3) - .setStartRowInclusive(false) - .setEndEntry(7) - .setEndRowInclusive(false) - .toCursor(); - assertCursor(expected, found); - - - - db.close(); - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/CursorTest.java b/test/src/java/com/healthmarketscience/jackcess/CursorTest.java deleted file mode 100644 index d10d18b..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/CursorTest.java +++ /dev/null @@ -1,1209 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.TreeSet; - -import static com.healthmarketscience.jackcess.Database.*; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.impl.JetFormatTest; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import com.healthmarketscience.jackcess.impl.RowIdImpl; -import com.healthmarketscience.jackcess.util.CaseInsensitiveColumnMatcher; -import com.healthmarketscience.jackcess.util.ColumnMatcher; -import com.healthmarketscience.jackcess.util.RowFilterTest; -import com.healthmarketscience.jackcess.util.SimpleColumnMatcher; -import junit.framework.TestCase; - -/** - * @author James Ahlborn - */ -public class CursorTest extends TestCase { - - static final List<TestDB> INDEX_CURSOR_DBS = - TestDB.getSupportedForBasename(Basename.INDEX_CURSOR); - - - public CursorTest(String name) throws Exception { - super(name); - } - - private static List<Map<String,Object>> createTestTableData() - throws Exception - { - List<Map<String,Object>> expectedRows = - new ArrayList<Map<String,Object>>(); - for(int i = 0; i < 10; ++i) { - expectedRows.add(createExpectedRow("id", i, "value", "data" + i)); - } - return expectedRows; - } - - private static List<Map<String,Object>> createTestTableData( - int startIdx, - int endIdx) - throws Exception - { - List<Map<String,Object>> expectedRows = createTestTableData(); - expectedRows.subList(endIdx, expectedRows.size()).clear(); - expectedRows.subList(0, startIdx).clear(); - return expectedRows; - } - - private static Database createTestTable(final FileFormat fileFormat) - throws Exception - { - Database db = create(fileFormat); - - Table table = new TableBuilder("test") - .addColumn(new ColumnBuilder("id", DataType.LONG)) - .addColumn(new ColumnBuilder("value", DataType.TEXT)) - .toTable(db); - - for(Map<String,Object> row : createTestTableData()) { - table.addRow(row.get("id"), row.get("value")); - } - - return db; - } - - private static List<Map<String,Object>> createUnorderedTestTableData() - throws Exception - { - List<Map<String,Object>> expectedRows = - new ArrayList<Map<String,Object>>(); - int[] ids = new int[]{3, 7, 6, 1, 2, 9, 0, 5, 4, 8}; - for(int i : ids) { - expectedRows.add(createExpectedRow("id", i, "value", "data" + i)); - } - return expectedRows; - } - - static Database createTestIndexTable(final TestDB indexCursorDB) - throws Exception - { - Database db = openCopy(indexCursorDB); - - Table table = db.getTable("test"); - - for(Map<String,Object> row : createUnorderedTestTableData()) { - table.addRow(row.get("id"), row.get("value")); - } - - return db; - } - - private static List<Map<String,Object>> createDupeTestTableData() - throws Exception - { - List<Map<String,Object>> expectedRows = - new ArrayList<Map<String,Object>>(); - int[] ids = new int[]{3, 7, 6, 1, 2, 9, 0, 5, 4, 8}; - for(int i : ids) { - expectedRows.add(createExpectedRow("id", i, "value", "data" + (i % 3))); - } - for(int i : ids) { - expectedRows.add(createExpectedRow("id", i, "value", "data" + (i % 5))); - } - return expectedRows; - } - - private static Database createDupeTestTable(final FileFormat fileFormat) - throws Exception - { - Database db = create(fileFormat); - - Table table = new TableBuilder("test") - .addColumn(new ColumnBuilder("id", DataType.LONG)) - .addColumn(new ColumnBuilder("value", DataType.TEXT)) - .toTable(db); - - for(Map<String,Object> row : createDupeTestTableData()) { - table.addRow(row.get("id"), row.get("value")); - } - - return db; - } - - static Database createDupeTestTable(final TestDB indexCursorDB) - throws Exception - { - Database db = openCopy(indexCursorDB); - - Table table = db.getTable("test"); - - for(Map<String,Object> row : createDupeTestTableData()) { - table.addRow(row.get("id"), row.get("value")); - } - - return db; - } - - private static Cursor createIndexSubRangeCursor(Table table, - Index idx, - int type) - throws Exception - { - return table.newCursor() - .setIndex(idx) - .setStartEntry(3 - type) - .setStartRowInclusive(type == 0) - .setEndEntry(8 + type) - .setEndRowInclusive(type == 0) - .toCursor(); - } - - public void testRowId() throws Exception { - // test special cases - RowIdImpl rowId1 = new RowIdImpl(1, 2); - RowIdImpl rowId2 = new RowIdImpl(1, 3); - RowIdImpl rowId3 = new RowIdImpl(2, 1); - - List<RowIdImpl> sortedRowIds = - new ArrayList<RowIdImpl>(new TreeSet<RowIdImpl>( - Arrays.asList(rowId1, rowId2, rowId3, RowIdImpl.FIRST_ROW_ID, - RowIdImpl.LAST_ROW_ID))); - - assertEquals(Arrays.asList(RowIdImpl.FIRST_ROW_ID, rowId1, rowId2, rowId3, - RowIdImpl.LAST_ROW_ID), - sortedRowIds); - } - - public void testSimple() throws Exception { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = createTestTable(fileFormat); - - Table table = db.getTable("test"); - Cursor cursor = CursorBuilder.createCursor(table); - doTestSimple(cursor, null); - db.close(); - } - } - - private static void doTestSimple(Cursor cursor, - List<Map<String, Object>> expectedRows) - throws Exception - { - if(expectedRows == null) { - expectedRows = createTestTableData(); - } - - List<Map<String, Object>> foundRows = - new ArrayList<Map<String, Object>>(); - for(Map<String, Object> row : cursor) { - foundRows.add(row); - } - assertEquals(expectedRows, foundRows); - } - - public void testMove() throws Exception { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = createTestTable(fileFormat); - - Table table = db.getTable("test"); - Cursor cursor = CursorBuilder.createCursor(table); - doTestMove(cursor, null); - - db.close(); - } - } - - private static void doTestMove(Cursor cursor, - List<Map<String, Object>> expectedRows) - throws Exception - { - if(expectedRows == null) { - expectedRows = createTestTableData(); - } - expectedRows.subList(1, 4).clear(); - - List<Map<String, Object>> foundRows = - new ArrayList<Map<String, Object>>(); - assertTrue(cursor.isBeforeFirst()); - assertFalse(cursor.isAfterLast()); - foundRows.add(cursor.getNextRow()); - assertEquals(3, cursor.moveNextRows(3)); - assertFalse(cursor.isBeforeFirst()); - assertFalse(cursor.isAfterLast()); - - Map<String,Object> expectedRow = cursor.getCurrentRow(); - Cursor.Savepoint savepoint = cursor.getSavepoint(); - assertEquals(2, cursor.movePreviousRows(2)); - assertEquals(2, cursor.moveNextRows(2)); - assertTrue(cursor.moveToNextRow()); - assertTrue(cursor.moveToPreviousRow()); - assertEquals(expectedRow, cursor.getCurrentRow()); - - while(cursor.moveToNextRow()) { - foundRows.add(cursor.getCurrentRow()); - } - assertEquals(expectedRows, foundRows); - assertFalse(cursor.isBeforeFirst()); - assertTrue(cursor.isAfterLast()); - - assertEquals(0, cursor.moveNextRows(3)); - - cursor.beforeFirst(); - assertTrue(cursor.isBeforeFirst()); - assertFalse(cursor.isAfterLast()); - - cursor.afterLast(); - assertFalse(cursor.isBeforeFirst()); - assertTrue(cursor.isAfterLast()); - - cursor.restoreSavepoint(savepoint); - assertEquals(expectedRow, cursor.getCurrentRow()); - } - - public void testMoveNoReset() throws Exception { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = createTestTable(fileFormat); - - Table table = db.getTable("test"); - Cursor cursor = CursorBuilder.createCursor(table); - doTestMoveNoReset(cursor); - - db.close(); - } - } - - private static void doTestMoveNoReset(Cursor cursor) - throws Exception - { - List<Map<String, Object>> expectedRows = createTestTableData(); - List<Map<String, Object>> foundRows = new ArrayList<Map<String, Object>>(); - - Iterator<Row> iter = cursor.newIterable().iterator(); - - for(int i = 0; i < 6; ++i) { - foundRows.add(iter.next()); - } - - iter = cursor.newIterable().reset(false).reverse().iterator(); - iter.next(); - Map<String, Object> row = iter.next(); - assertEquals(expectedRows.get(4), row); - - iter = cursor.newIterable().reset(false).iterator(); - iter.next(); - row = iter.next(); - assertEquals(expectedRows.get(5), row); - iter.next(); - - iter = cursor.newIterable().reset(false).iterator(); - for(int i = 6; i < 10; ++i) { - foundRows.add(iter.next()); - } - - assertEquals(expectedRows, foundRows); - } - - public void testSearch() throws Exception { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = createTestTable(fileFormat); - - Table table = db.getTable("test"); - Cursor cursor = CursorBuilder.createCursor(table); - doTestSearch(table, cursor, null, 42, -13); - - db.close(); - } - } - - private static void doTestSearch(Table table, Cursor cursor, Index index, - Integer... outOfRangeValues) - throws Exception - { - assertTrue(cursor.findFirstRow(table.getColumn("id"), 3)); - assertEquals(createExpectedRow("id", 3, - "value", "data" + 3), - cursor.getCurrentRow()); - - assertTrue(cursor.findFirstRow(createExpectedRow( - "id", 6, - "value", "data" + 6))); - assertEquals(createExpectedRow("id", 6, - "value", "data" + 6), - cursor.getCurrentRow()); - - assertFalse(cursor.findFirstRow(createExpectedRow( - "id", 8, - "value", "data" + 13))); - assertFalse(cursor.findFirstRow(table.getColumn("id"), 13)); - assertEquals(createExpectedRow("id", 6, - "value", "data" + 6), - cursor.getCurrentRow()); - - assertTrue(cursor.findFirstRow(createExpectedRow( - "value", "data" + 7))); - assertEquals(createExpectedRow("id", 7, - "value", "data" + 7), - cursor.getCurrentRow()); - - assertTrue(cursor.findFirstRow(table.getColumn("value"), "data" + 4)); - assertEquals(createExpectedRow("id", 4, - "value", "data" + 4), - cursor.getCurrentRow()); - - for(Integer outOfRangeValue : outOfRangeValues) { - assertFalse(cursor.findFirstRow(table.getColumn("id"), - outOfRangeValue)); - assertFalse(cursor.findFirstRow(table.getColumn("value"), - "data" + outOfRangeValue)); - assertFalse(cursor.findFirstRow(createExpectedRow( - "id", outOfRangeValue, - "value", "data" + outOfRangeValue))); - } - - assertEquals("data" + 5, - CursorBuilder.findValue(table, - table.getColumn("value"), - table.getColumn("id"), 5)); - assertEquals(createExpectedRow("id", 5, - "value", "data" + 5), - CursorBuilder.findRow(table, - createExpectedRow("id", 5))); - if(index != null) { - assertEquals("data" + 5, - CursorBuilder.findValue(index, - table.getColumn("value"), - table.getColumn("id"), 5)); - assertEquals(createExpectedRow("id", 5, - "value", "data" + 5), - CursorBuilder.findRow(index, - createExpectedRow("id", 5))); - - assertNull(CursorBuilder.findValue(index, - table.getColumn("value"), - table.getColumn("id"), - -17)); - assertNull(CursorBuilder.findRow(index, - createExpectedRow("id", 13))); - } - } - - public void testReverse() throws Exception { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = createTestTable(fileFormat); - - Table table = db.getTable("test"); - Cursor cursor = CursorBuilder.createCursor(table); - doTestReverse(cursor, null); - - db.close(); - } - } - - private static void doTestReverse(Cursor cursor, - List<Map<String, Object>> expectedRows) - throws Exception - { - if(expectedRows == null) { - expectedRows = createTestTableData(); - } - Collections.reverse(expectedRows); - - List<Map<String, Object>> foundRows = - new ArrayList<Map<String, Object>>(); - for(Map<String, Object> row : cursor.newIterable().reverse()) { - foundRows.add(row); - } - assertEquals(expectedRows, foundRows); - } - - public void testLiveAddition() throws Exception { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = createTestTable(fileFormat); - - Table table = db.getTable("test"); - - Cursor cursor1 = CursorBuilder.createCursor(table); - Cursor cursor2 = CursorBuilder.createCursor(table); - doTestLiveAddition(table, cursor1, cursor2, 11); - - db.close(); - } - } - - private static void doTestLiveAddition(Table table, - Cursor cursor1, - Cursor cursor2, - Integer newRowNum) throws Exception - { - cursor1.moveNextRows(11); - cursor2.moveNextRows(11); - - assertTrue(cursor1.isAfterLast()); - assertTrue(cursor2.isAfterLast()); - - table.addRow(newRowNum, "data" + newRowNum); - Map<String,Object> expectedRow = - createExpectedRow("id", newRowNum, "value", "data" + newRowNum); - - assertFalse(cursor1.isAfterLast()); - assertFalse(cursor2.isAfterLast()); - - assertEquals(expectedRow, cursor1.getCurrentRow()); - assertEquals(expectedRow, cursor2.getCurrentRow()); - assertFalse(cursor1.moveToNextRow()); - assertFalse(cursor2.moveToNextRow()); - assertTrue(cursor1.isAfterLast()); - assertTrue(cursor2.isAfterLast()); - } - - - public void testLiveDeletion() throws Exception { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = createTestTable(fileFormat); - - Table table = db.getTable("test"); - - Cursor cursor1 = CursorBuilder.createCursor(table); - Cursor cursor2 = CursorBuilder.createCursor(table); - Cursor cursor3 = CursorBuilder.createCursor(table); - Cursor cursor4 = CursorBuilder.createCursor(table); - doTestLiveDeletion(cursor1, cursor2, cursor3, cursor4, 1); - - db.close(); - } - } - - private static void doTestLiveDeletion( - Cursor cursor1, - Cursor cursor2, - Cursor cursor3, - Cursor cursor4, - int firstValue) throws Exception - { - assertEquals(2, cursor1.moveNextRows(2)); - assertEquals(3, cursor2.moveNextRows(3)); - assertEquals(3, cursor3.moveNextRows(3)); - assertEquals(4, cursor4.moveNextRows(4)); - - Map<String,Object> expectedPrevRow = - createExpectedRow("id", firstValue, "value", "data" + firstValue); - ++firstValue; - Map<String,Object> expectedDeletedRow = - createExpectedRow("id", firstValue, "value", "data" + firstValue); - ++firstValue; - Map<String,Object> expectedNextRow = - createExpectedRow("id", firstValue, "value", "data" + firstValue); - - assertEquals(expectedDeletedRow, cursor2.getCurrentRow()); - assertEquals(expectedDeletedRow, cursor3.getCurrentRow()); - - assertFalse(cursor2.isCurrentRowDeleted()); - assertFalse(cursor3.isCurrentRowDeleted()); - - cursor2.deleteCurrentRow(); - - assertTrue(cursor2.isCurrentRowDeleted()); - assertTrue(cursor3.isCurrentRowDeleted()); - - assertEquals(expectedNextRow, cursor1.getNextRow()); - assertEquals(expectedNextRow, cursor2.getNextRow()); - assertEquals(expectedNextRow, cursor3.getNextRow()); - - assertEquals(expectedPrevRow, cursor3.getPreviousRow()); - - assertTrue(cursor3.moveToNextRow()); - cursor3.deleteCurrentRow(); - assertTrue(cursor3.isCurrentRowDeleted()); - - firstValue += 2; - expectedNextRow = - createExpectedRow("id", firstValue, "value", "data" + firstValue); - assertTrue(cursor3.moveToNextRow()); - assertEquals(expectedNextRow, cursor3.getNextRow()); - - cursor1.beforeFirst(); - assertTrue(cursor1.moveToNextRow()); - cursor1.deleteCurrentRow(); - assertFalse(cursor1.isBeforeFirst()); - assertFalse(cursor1.isAfterLast()); - assertFalse(cursor1.moveToPreviousRow()); - assertTrue(cursor1.isBeforeFirst()); - assertFalse(cursor1.isAfterLast()); - - cursor1.afterLast(); - assertTrue(cursor1.moveToPreviousRow()); - cursor1.deleteCurrentRow(); - assertFalse(cursor1.isBeforeFirst()); - assertFalse(cursor1.isAfterLast()); - assertFalse(cursor1.moveToNextRow()); - assertFalse(cursor1.isBeforeFirst()); - assertTrue(cursor1.isAfterLast()); - - cursor1.beforeFirst(); - while(cursor1.moveToNextRow()) { - cursor1.deleteCurrentRow(); - } - - assertTrue(cursor1.isAfterLast()); - assertTrue(cursor2.isCurrentRowDeleted()); - assertTrue(cursor3.isCurrentRowDeleted()); - assertTrue(cursor4.isCurrentRowDeleted()); - } - - public void testSimpleIndex() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - assertTable(createUnorderedTestTableData(), table); - - Cursor cursor = CursorBuilder.createCursor(idx); - doTestSimple(cursor, null); - - db.close(); - } - } - - public void testMoveIndex() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - Cursor cursor = CursorBuilder.createCursor(idx); - doTestMove(cursor, null); - - db.close(); - } - } - - public void testReverseIndex() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - Cursor cursor = CursorBuilder.createCursor(idx); - doTestReverse(cursor, null); - - db.close(); - } - } - - public void testSearchIndex() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - Cursor cursor = CursorBuilder.createCursor(idx); - doTestSearch(table, cursor, idx, 42, -13); - - db.close(); - } - } - - public void testLiveAdditionIndex() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - Cursor cursor1 = CursorBuilder.createCursor(idx); - Cursor cursor2 = CursorBuilder.createCursor(idx); - doTestLiveAddition(table, cursor1, cursor2, 11); - - db.close(); - } - } - - public void testLiveDeletionIndex() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - Cursor cursor1 = CursorBuilder.createCursor(idx); - Cursor cursor2 = CursorBuilder.createCursor(idx); - Cursor cursor3 = CursorBuilder.createCursor(idx); - Cursor cursor4 = CursorBuilder.createCursor(idx); - doTestLiveDeletion(cursor1, cursor2, cursor3, cursor4, 1); - - db.close(); - } - } - - public void testSimpleIndexSubRange() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - for(int i = 0; i < 2; ++i) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - Cursor cursor = createIndexSubRangeCursor(table, idx, i); - - List<Map<String,Object>> expectedRows = - createTestTableData(3, 9); - - doTestSimple(cursor, expectedRows); - - db.close(); - } - } - } - - public void testMoveIndexSubRange() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - for(int i = 0; i < 2; ++i) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - Cursor cursor = createIndexSubRangeCursor(table, idx, i); - - List<Map<String,Object>> expectedRows = - createTestTableData(3, 9); - - doTestMove(cursor, expectedRows); - - db.close(); - } - } - } - - public void testSearchIndexSubRange() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - for(int i = 0; i < 2; ++i) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - Cursor cursor = createIndexSubRangeCursor(table, idx, i); - - doTestSearch(table, cursor, idx, 2, 9); - - db.close(); - } - } - } - - public void testReverseIndexSubRange() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - for(int i = 0; i < 2; ++i) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - Cursor cursor = createIndexSubRangeCursor(table, idx, i); - - List<Map<String,Object>> expectedRows = - createTestTableData(3, 9); - - doTestReverse(cursor, expectedRows); - - db.close(); - } - } - } - - public void testLiveAdditionIndexSubRange() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - for(int i = 0; i < 2; ++i) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - Cursor cursor1 = createIndexSubRangeCursor(table, idx, i); - Cursor cursor2 = createIndexSubRangeCursor(table, idx, i); - - doTestLiveAddition(table, cursor1, cursor2, 8); - - db.close(); - } - } - } - - public void testLiveDeletionIndexSubRange() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - for(int i = 0; i < 2; ++i) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - Cursor cursor1 = createIndexSubRangeCursor(table, idx, i); - Cursor cursor2 = createIndexSubRangeCursor(table, idx, i); - Cursor cursor3 = createIndexSubRangeCursor(table, idx, i); - Cursor cursor4 = createIndexSubRangeCursor(table, idx, i); - - doTestLiveDeletion(cursor1, cursor2, cursor3, cursor4, 4); - - db.close(); - } - } - } - - public void testFindAllIndex() throws Exception { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = createDupeTestTable(fileFormat); - - Table table = db.getTable("test"); - Cursor cursor = CursorBuilder.createCursor(table); - - doTestFindAll(table, cursor, null); - - db.close(); - } - } - - public void testFindAll() throws Exception { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - Database db = createDupeTestTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - Cursor cursor = CursorBuilder.createCursor(idx); - - doTestFindAll(table, cursor, idx); - - db.close(); - } - } - - private static void doTestFindAll(Table table, Cursor cursor, Index index) - throws Exception - { - List<? extends Map<String,Object>> rows = RowFilterTest.toList( - cursor.newIterable().setMatchPattern("value", "data2")); - - List<? extends Map<String, Object>> expectedRows = null; - - if(index == null) { - expectedRows = - createExpectedTable( - createExpectedRow( - "id", 2, "value", "data2"), - createExpectedRow( - "id", 5, "value", "data2"), - createExpectedRow( - "id", 8, "value", "data2"), - createExpectedRow( - "id", 7, "value", "data2"), - createExpectedRow( - "id", 2, "value", "data2")); - } else { - expectedRows = - createExpectedTable( - createExpectedRow( - "id", 2, "value", "data2"), - createExpectedRow( - "id", 2, "value", "data2"), - createExpectedRow( - "id", 5, "value", "data2"), - createExpectedRow( - "id", 7, "value", "data2"), - createExpectedRow( - "id", 8, "value", "data2")); - } - assertEquals(expectedRows, rows); - - Column valCol = table.getColumn("value"); - rows = RowFilterTest.toList( - cursor.newIterable().setMatchPattern(valCol, "data4")); - - if(index == null) { - expectedRows = - createExpectedTable( - createExpectedRow( - "id", 9, "value", "data4"), - createExpectedRow( - "id", 4, "value", "data4")); - } else { - expectedRows = - createExpectedTable( - createExpectedRow( - "id", 4, "value", "data4"), - createExpectedRow( - "id", 9, "value", "data4")); - } - assertEquals(expectedRows, rows); - - rows = RowFilterTest.toList( - cursor.newIterable().setMatchPattern(valCol, "data9")); - - assertTrue(rows.isEmpty()); - - rows = RowFilterTest.toList( - cursor.newIterable().setMatchPattern( - Collections.singletonMap("id", 8))); - - expectedRows = - createExpectedTable( - createExpectedRow( - "id", 8, "value", "data2"), - createExpectedRow( - "id", 8, "value", "data3")); - assertEquals(expectedRows, rows); - - for(Map<String,Object> row : table) { - - List<Map<String,Object>> tmpRows = new ArrayList<Map<String,Object>>(); - for(Map<String,Object> tmpRow : cursor) { - if(row.equals(tmpRow)) { - tmpRows.add(tmpRow); - } - } - expectedRows = tmpRows; - assertFalse(expectedRows.isEmpty()); - - rows = RowFilterTest.toList(cursor.newIterable().setMatchPattern(row)); - - assertEquals(expectedRows, rows); - } - - rows = RowFilterTest.toList( - cursor.newIterable().addMatchPattern("id", 8) - .addMatchPattern("value", "data13")); - assertTrue(rows.isEmpty()); - } - - public void testId() throws Exception - { - for (final TestDB indexCursorDB : INDEX_CURSOR_DBS) { - Database db = createTestIndexTable(indexCursorDB); - - Table table = db.getTable("test"); - Index idx = table.getIndexes().get(0); - - Cursor tCursor = CursorBuilder.createCursor(table); - Cursor iCursor = CursorBuilder.createCursor(idx); - - Cursor.Savepoint tSave = tCursor.getSavepoint(); - Cursor.Savepoint iSave = iCursor.getSavepoint(); - - tCursor.restoreSavepoint(tSave); - iCursor.restoreSavepoint(iSave); - - try { - tCursor.restoreSavepoint(iSave); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException e) { - // success - } - - try { - iCursor.restoreSavepoint(tSave); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException e) { - // success - } - - Cursor tCursor2 = CursorBuilder.createCursor(table); - Cursor iCursor2 = CursorBuilder.createCursor(idx); - - tCursor2.restoreSavepoint(tSave); - iCursor2.restoreSavepoint(iSave); - - db.close(); - } - } - - public void testColumnMatcher() throws Exception { - - - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = createTestTable(fileFormat); - - Table table = db.getTable("test"); - - doTestMatchers(table, SimpleColumnMatcher.INSTANCE, false); - doTestMatchers(table, CaseInsensitiveColumnMatcher.INSTANCE, true); - - Cursor cursor = CursorBuilder.createCursor(table); - doTestMatcher(table, cursor, SimpleColumnMatcher.INSTANCE, false); - doTestMatcher(table, cursor, CaseInsensitiveColumnMatcher.INSTANCE, - true); - db.close(); - } - } - - private static void doTestMatchers(Table table, ColumnMatcher columnMatcher, - boolean caseInsensitive) - throws Exception - { - assertTrue(columnMatcher.matches(table, "value", null, null)); - assertFalse(columnMatcher.matches(table, "value", "foo", null)); - assertFalse(columnMatcher.matches(table, "value", null, "foo")); - assertTrue(columnMatcher.matches(table, "value", "foo", "foo")); - assertTrue(columnMatcher.matches(table, "value", "foo", "Foo") - == caseInsensitive); - - assertFalse(columnMatcher.matches(table, "value", 13, null)); - assertFalse(columnMatcher.matches(table, "value", null, 13)); - assertTrue(columnMatcher.matches(table, "value", 13, 13)); - } - - private static void doTestMatcher(Table table, Cursor cursor, - ColumnMatcher columnMatcher, - boolean caseInsensitive) - throws Exception - { - cursor.setColumnMatcher(columnMatcher); - - assertTrue(cursor.findFirstRow(table.getColumn("id"), 3)); - assertEquals(createExpectedRow("id", 3, - "value", "data" + 3), - cursor.getCurrentRow()); - - assertTrue(cursor.findFirstRow(createExpectedRow( - "id", 6, - "value", "data" + 6))); - assertEquals(createExpectedRow("id", 6, - "value", "data" + 6), - cursor.getCurrentRow()); - - assertTrue(cursor.findFirstRow(createExpectedRow( - "id", 6, - "value", "Data" + 6)) == caseInsensitive); - if(caseInsensitive) { - assertEquals(createExpectedRow("id", 6, - "value", "data" + 6), - cursor.getCurrentRow()); - } - - assertFalse(cursor.findFirstRow(createExpectedRow( - "id", 8, - "value", "data" + 13))); - assertFalse(cursor.findFirstRow(table.getColumn("id"), 13)); - assertEquals(createExpectedRow("id", 6, - "value", "data" + 6), - cursor.getCurrentRow()); - - assertTrue(cursor.findFirstRow(createExpectedRow( - "value", "data" + 7))); - assertEquals(createExpectedRow("id", 7, - "value", "data" + 7), - cursor.getCurrentRow()); - - assertTrue(cursor.findFirstRow(createExpectedRow( - "value", "Data" + 7)) == caseInsensitive); - if(caseInsensitive) { - assertEquals(createExpectedRow("id", 7, - "value", "data" + 7), - cursor.getCurrentRow()); - } - - assertTrue(cursor.findFirstRow(table.getColumn("value"), "data" + 4)); - assertEquals(createExpectedRow("id", 4, - "value", "data" + 4), - cursor.getCurrentRow()); - - assertTrue(cursor.findFirstRow(table.getColumn("value"), "Data" + 4) - == caseInsensitive); - if(caseInsensitive) { - assertEquals(createExpectedRow("id", 4, - "value", "data" + 4), - cursor.getCurrentRow()); - } - - assertEquals(Arrays.asList(createExpectedRow("id", 4, - "value", "data" + 4)), - RowFilterTest.toList( - cursor.newIterable() - .setMatchPattern("value", "data4") - .setColumnMatcher(SimpleColumnMatcher.INSTANCE))); - - assertEquals(Arrays.asList(createExpectedRow("id", 3, - "value", "data" + 3)), - RowFilterTest.toList( - cursor.newIterable() - .setMatchPattern("value", "DaTa3") - .setColumnMatcher(CaseInsensitiveColumnMatcher.INSTANCE))); - - assertEquals(Arrays.asList(createExpectedRow("id", 2, - "value", "data" + 2)), - RowFilterTest.toList( - cursor.newIterable() - .addMatchPattern("value", "DaTa2") - .addMatchPattern("id", 2) - .setColumnMatcher(CaseInsensitiveColumnMatcher.INSTANCE))); - } - - public void testIndexCursor() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX)) { - - Database db = open(testDB); - Table t1 = db.getTable("Table1"); - Index idx = t1.getIndex(IndexBuilder.PRIMARY_KEY_NAME); - IndexCursor cursor = CursorBuilder.createCursor(idx); - - assertFalse(cursor.findFirstRowByEntry(-1)); - cursor.findClosestRowByEntry(-1); - assertEquals(0, cursor.getCurrentRow().get("id")); - - assertTrue(cursor.findFirstRowByEntry(1)); - assertEquals(1, cursor.getCurrentRow().get("id")); - - cursor.findClosestRowByEntry(2); - assertEquals(2, cursor.getCurrentRow().get("id")); - - assertFalse(cursor.findFirstRowByEntry(4)); - cursor.findClosestRowByEntry(4); - assertTrue(cursor.isAfterLast()); - - db.close(); - } - } - - public void testIndexCursorDelete() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX)) { - - Database db = openCopy(testDB); - Table t1 = db.getTable("Table1"); - Index idx = t1.getIndex("Table2Table1"); - IndexCursor cursor = CursorBuilder.createCursor(idx); - - List<String> expectedData = new ArrayList<String>(); - for(Map<String,Object> row : cursor.newEntryIterable(1) - .addColumnNames("data")) { - expectedData.add((String)row.get("data")); - } - - assertEquals(Arrays.asList("baz11", "baz11-2"), expectedData); - - expectedData = new ArrayList<String>(); - for(Iterator<? extends Map<String,Object>> iter = - cursor.newEntryIterable(1).iterator(); - iter.hasNext(); ) { - expectedData.add((String)iter.next().get("data")); - iter.remove(); - try { - iter.remove(); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalStateException e) { - // success - } - - if(!iter.hasNext()) { - try { - iter.next(); - fail("NoSuchElementException should have been thrown"); - } catch(NoSuchElementException e) { - // success - } - } - } - - assertEquals(Arrays.asList("baz11", "baz11-2"), expectedData); - - expectedData = new ArrayList<String>(); - for(Map<String,Object> row : cursor.newEntryIterable(1) - .addColumnNames("data")) { - expectedData.add((String)row.get("data")); - } - - assertTrue(expectedData.isEmpty()); - - db.close(); - } - } - - public void testCursorDelete() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX)) { - - Database db = openCopy(testDB); - Table t1 = db.getTable("Table1"); - Cursor cursor = CursorBuilder.createCursor(t1); - - List<String> expectedData = new ArrayList<String>(); - for(Map<String,Object> row : cursor.newIterable().setColumnNames( - Arrays.asList("otherfk1", "data"))) { - if(row.get("otherfk1").equals(1)) { - expectedData.add((String)row.get("data")); - } - } - - assertEquals(Arrays.asList("baz11", "baz11-2"), expectedData); - - expectedData = new ArrayList<String>(); - for(Iterator<? extends Map<String,Object>> iter = cursor.iterator(); - iter.hasNext(); ) { - Map<String,Object> row = iter.next(); - if(row.get("otherfk1").equals(1)) { - expectedData.add((String)row.get("data")); - iter.remove(); - try { - iter.remove(); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalStateException e) { - // success - } - } - - if(!iter.hasNext()) { - try { - iter.next(); - fail("NoSuchElementException should have been thrown"); - } catch(NoSuchElementException e) { - // success - } - } - } - - assertEquals(Arrays.asList("baz11", "baz11-2"), expectedData); - - expectedData = new ArrayList<String>(); - for(Map<String,Object> row : cursor.newIterable().setColumnNames( - Arrays.asList("otherfk1", "data"))) { - if(row.get("otherfk1").equals(1)) { - expectedData.add((String)row.get("data")); - } - } - - assertTrue(expectedData.isEmpty()); - - db.close(); - } - } - -} - diff --git a/test/src/java/com/healthmarketscience/jackcess/DatabaseTest.java b/test/src/java/com/healthmarketscience/jackcess/DatabaseTest.java deleted file mode 100644 index eef4ecb..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/DatabaseTest.java +++ /dev/null @@ -1,1686 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.math.BigDecimal; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.sql.Types; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; -import java.util.TreeSet; -import java.util.UUID; - -import static com.healthmarketscience.jackcess.Database.*; -import com.healthmarketscience.jackcess.complex.ComplexValueForeignKey; -import com.healthmarketscience.jackcess.impl.ByteUtil; -import com.healthmarketscience.jackcess.impl.ColumnImpl; -import com.healthmarketscience.jackcess.impl.DatabaseImpl; -import com.healthmarketscience.jackcess.impl.IndexData; -import com.healthmarketscience.jackcess.impl.IndexImpl; -import com.healthmarketscience.jackcess.impl.JetFormat; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import com.healthmarketscience.jackcess.impl.RowIdImpl; -import com.healthmarketscience.jackcess.impl.RowImpl; -import com.healthmarketscience.jackcess.impl.TableImpl; -import com.healthmarketscience.jackcess.util.LinkResolver; -import com.healthmarketscience.jackcess.util.MemFileChannel; -import com.healthmarketscience.jackcess.util.RowFilterTest; -import junit.framework.TestCase; - - -/** - * @author Tim McCune - */ -public class DatabaseTest extends TestCase { - - public static final TimeZone TEST_TZ = - TimeZone.getTimeZone("America/New_York"); - - static boolean _autoSync = Database.DEFAULT_AUTO_SYNC; - - - public DatabaseTest(String name) throws Exception { - super(name); - } - - public static Database open(FileFormat fileFormat, File file) - throws Exception - { - return open(fileFormat, file, false); - } - - private static Database open(FileFormat fileFormat, File file, - boolean inMem) - throws Exception - { - FileChannel channel = (inMem ? MemFileChannel.newChannel(file, "r") - : null); - final Database db = new DatabaseBuilder(file).setReadOnly(true) - .setAutoSync(_autoSync).setChannel(channel).open(); - assertEquals("Wrong JetFormat.", - DatabaseImpl.getFileFormatDetails(fileFormat).getFormat(), - ((DatabaseImpl)db).getFormat()); - assertEquals("Wrong FileFormat.", fileFormat, db.getFileFormat()); - return db; - } - - public static Database open(TestDB testDB) throws Exception { - return open(testDB.getExpectedFileFormat(), testDB.getFile()); - } - - public static Database openMem(TestDB testDB) throws Exception { - return open(testDB.getExpectedFileFormat(), testDB.getFile(), true); - } - - public static Database create(FileFormat fileFormat) throws Exception { - return create(fileFormat, false); - } - - public static Database create(FileFormat fileFormat, boolean keep) - throws Exception - { - return create(fileFormat, keep, false); - } - - public static Database createMem(FileFormat fileFormat) throws Exception { - return create(fileFormat, false, true); - } - - private static Database create(FileFormat fileFormat, boolean keep, - boolean inMem) - throws Exception - { - FileChannel channel = (inMem ? MemFileChannel.newChannel() : null); - return new DatabaseBuilder(createTempFile(keep)).setFileFormat(fileFormat) - .setAutoSync(_autoSync).setChannel(channel).create(); - } - - - public static Database openCopy(TestDB testDB) throws Exception { - return openCopy(testDB, false); - } - - public static Database openCopy(TestDB testDB, boolean keep) - throws Exception - { - return openCopy(testDB.getExpectedFileFormat(), testDB.getFile(), keep); - } - - public static Database openCopy(FileFormat fileFormat, File file) - throws Exception - { - return openCopy(fileFormat, file, false); - } - - public static Database openCopy(FileFormat fileFormat, File file, - boolean keep) - throws Exception - { - File tmp = createTempFile(keep); - copyFile(file, tmp); - Database db = new DatabaseBuilder(tmp).setAutoSync(_autoSync).open(); - assertEquals("Wrong JetFormat.", - DatabaseImpl.getFileFormatDetails(fileFormat).getFormat(), - ((DatabaseImpl)db).getFormat()); - assertEquals("Wrong FileFormat.", fileFormat, db.getFileFormat()); - return db; - } - - - public void testInvalidTableDefs() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - try { - ((DatabaseImpl)db).createTable("test", Collections.<ColumnBuilder>emptyList()); - fail("created table with no columns?"); - } catch(IllegalArgumentException e) { - // success - } - - try { - new TableBuilder("test") - .addColumn(new ColumnBuilder("A", DataType.TEXT)) - .addColumn(new ColumnBuilder("a", DataType.MEMO)) - .toTable(db); - fail("created table with duplicate column names?"); - } catch(IllegalArgumentException e) { - // success - } - - try { - new TableBuilder("test") - .addColumn(new ColumnBuilder("A", DataType.TEXT) - .setLengthInUnits(352)) - .toTable(db); - fail("created table with invalid column length?"); - } catch(IllegalArgumentException e) { - // success - } - - try { - new TableBuilder("test") - .addColumn(new ColumnBuilder("A_" + createString(70), DataType.TEXT)) - .toTable(db); - fail("created table with too long column name?"); - } catch(IllegalArgumentException e) { - // success - } - - new TableBuilder("test") - .addColumn(new ColumnBuilder("A", DataType.TEXT)) - .toTable(db); - - - try { - new TableBuilder("Test") - .addColumn(new ColumnBuilder("A", DataType.TEXT)) - .toTable(db); - fail("create duplicate tables?"); - } catch(IllegalArgumentException e) { - // success - } - - db.close(); - } - } - - public void testReadDeletedRows() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.DEL, true)) { - Table table = open(testDB).getTable("Table"); - int rows = 0; - while (table.getNextRow() != null) { - rows++; - } - assertEquals(2, rows); - table.getDatabase().close(); - } - } - - public void testGetColumns() throws Exception { - for (final TestDB testDB : SUPPORTED_DBS_TEST_FOR_READ) { - - List<? extends Column> columns = open(testDB).getTable("Table1").getColumns(); - assertEquals(9, columns.size()); - checkColumn(columns, 0, "A", DataType.TEXT); - checkColumn(columns, 1, "B", DataType.TEXT); - checkColumn(columns, 2, "C", DataType.BYTE); - checkColumn(columns, 3, "D", DataType.INT); - checkColumn(columns, 4, "E", DataType.LONG); - checkColumn(columns, 5, "F", DataType.DOUBLE); - checkColumn(columns, 6, "G", DataType.SHORT_DATE_TIME); - checkColumn(columns, 7, "H", DataType.MONEY); - checkColumn(columns, 8, "I", DataType.BOOLEAN); - } - } - - static void checkColumn(List<? extends Column> columns, int columnNumber, - String name, DataType dataType) - throws Exception - { - Column column = columns.get(columnNumber); - assertEquals(name, column.getName()); - assertEquals(dataType, column.getType()); - } - - public void testGetNextRow() throws Exception { - for (final TestDB testDB : SUPPORTED_DBS_TEST_FOR_READ) { - final Database db = open(testDB); - assertEquals(4, db.getTableNames().size()); - final Table table = db.getTable("Table1"); - - Map<String, Object> row1 = table.getNextRow(); - Map<String, Object> row2 = table.getNextRow(); - - if(!"abcdefg".equals(row1.get("A"))) { - Map<String, Object> tmpRow = row1; - row1 = row2; - row2 = tmpRow; - } - - checkTestDBTable1RowABCDEFG(testDB, table, row1); - checkTestDBTable1RowA(testDB, table, row2); - - db.close(); - } - } - - static void checkTestDBTable1RowABCDEFG(final TestDB testDB, final Table table, final Map<String, Object> row) - throws IOException { - assertEquals("testDB: " + testDB + "; table: " + table, "abcdefg", row.get("A")); - assertEquals("hijklmnop", row.get("B")); - assertEquals(new Byte((byte) 2), row.get("C")); - assertEquals(new Short((short) 222), row.get("D")); - assertEquals(new Integer(333333333), row.get("E")); - assertEquals(new Double(444.555d), row.get("F")); - final Calendar cal = Calendar.getInstance(); - cal.setTime((Date) row.get("G")); - assertEquals(Calendar.SEPTEMBER, cal.get(Calendar.MONTH)); - assertEquals(21, cal.get(Calendar.DAY_OF_MONTH)); - assertEquals(1974, cal.get(Calendar.YEAR)); - assertEquals(0, cal.get(Calendar.HOUR_OF_DAY)); - assertEquals(0, cal.get(Calendar.MINUTE)); - assertEquals(0, cal.get(Calendar.SECOND)); - assertEquals(0, cal.get(Calendar.MILLISECOND)); - assertEquals(Boolean.TRUE, row.get("I")); - } - - static void checkTestDBTable1RowA(final TestDB testDB, final Table table, final Map<String, Object> row) - throws IOException { - assertEquals("testDB: " + testDB + "; table: " + table, "a", row.get("A")); - assertEquals("b", row.get("B")); - assertEquals(new Byte((byte) 0), row.get("C")); - assertEquals(new Short((short) 0), row.get("D")); - assertEquals(new Integer(0), row.get("E")); - assertEquals(new Double(0d), row.get("F")); - final Calendar cal = Calendar.getInstance(); - cal.setTime((Date) row.get("G")); - assertEquals(Calendar.DECEMBER, cal.get(Calendar.MONTH)); - assertEquals(12, cal.get(Calendar.DAY_OF_MONTH)); - assertEquals(1981, cal.get(Calendar.YEAR)); - assertEquals(0, cal.get(Calendar.HOUR_OF_DAY)); - assertEquals(0, cal.get(Calendar.MINUTE)); - assertEquals(0, cal.get(Calendar.SECOND)); - assertEquals(0, cal.get(Calendar.MILLISECOND)); - assertEquals(Boolean.FALSE, row.get("I")); - } - - public void testCreate() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - assertEquals(0, db.getTableNames().size()); - db.close(); - } - } - - public void testWriteAndRead() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - doTestWriteAndRead(db); - db.close(); - } - } - - public void testWriteAndReadInMem() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = createMem(fileFormat); - doTestWriteAndRead(db); - db.close(); - } - } - - private static void doTestWriteAndRead(Database db) throws Exception { - createTestTable(db); - Object[] row = createTestRow(); - row[3] = null; - Table table = db.getTable("Test"); - int count = 1000; - for (int i = 0; i < count; i++) { - table.addRow(row); - } - for (int i = 0; i < count; i++) { - Map<String, Object> readRow = table.getNextRow(); - assertEquals(row[0], readRow.get("A")); - assertEquals(row[1], readRow.get("B")); - assertEquals(row[2], readRow.get("C")); - assertEquals(row[3], readRow.get("D")); - assertEquals(row[4], readRow.get("E")); - assertEquals(row[5], readRow.get("F")); - assertEquals(row[6], readRow.get("G")); - assertEquals(row[7], readRow.get("H")); - } - } - - public void testWriteAndReadInBatch() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - createTestTable(db); - int count = 1000; - List<Object[]> rows = new ArrayList<Object[]>(count); - Object[] row = createTestRow(); - for (int i = 0; i < count; i++) { - rows.add(row); - } - Table table = db.getTable("Test"); - table.addRows(rows); - for (int i = 0; i < count; i++) { - Map<String, Object> readRow = table.getNextRow(); - assertEquals(row[0], readRow.get("A")); - assertEquals(row[1], readRow.get("B")); - assertEquals(row[2], readRow.get("C")); - assertEquals(row[3], readRow.get("D")); - assertEquals(row[4], readRow.get("E")); - assertEquals(row[5], readRow.get("F")); - assertEquals(row[6], readRow.get("G")); - assertEquals(row[7], readRow.get("H")); - } - - db.close(); - } - } - - public void testDeleteCurrentRow() throws Exception { - - // make sure correct row is deleted - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - createTestTable(db); - Map<String,Object> row1 = createTestRowMap("Tim1"); - Map<String,Object> row2 = createTestRowMap("Tim2"); - Map<String,Object> row3 = createTestRowMap("Tim3"); - Table table = db.getTable("Test"); - @SuppressWarnings("unchecked") - List<Map<String,Object>> rows = Arrays.asList(row1, row2, row3); - table.addRowsFromMaps(rows); - assertRowCount(3, table); - - table.reset(); - table.getNextRow(); - table.getNextRow(); - table.getDefaultCursor().deleteCurrentRow(); - - table.reset(); - - Map<String, Object> outRow = table.getNextRow(); - assertEquals("Tim1", outRow.get("A")); - outRow = table.getNextRow(); - assertEquals("Tim3", outRow.get("A")); - assertRowCount(2, table); - - // test multi row delete/add - db = create(fileFormat); - createTestTable(db); - Object[] row = createTestRow(); - table = db.getTable("Test"); - for (int i = 0; i < 10; i++) { - row[3] = i; - table.addRow(row); - } - row[3] = 1974; - assertRowCount(10, table); - table.reset(); - table.getNextRow(); - table.getDefaultCursor().deleteCurrentRow(); - assertRowCount(9, table); - table.reset(); - table.getNextRow(); - table.getDefaultCursor().deleteCurrentRow(); - assertRowCount(8, table); - table.reset(); - for (int i = 0; i < 8; i++) { - table.getNextRow(); - } - table.getDefaultCursor().deleteCurrentRow(); - assertRowCount(7, table); - table.addRow(row); - assertRowCount(8, table); - table.reset(); - for (int i = 0; i < 3; i++) { - table.getNextRow(); - } - table.getDefaultCursor().deleteCurrentRow(); - assertRowCount(7, table); - table.reset(); - assertEquals(2, table.getNextRow().get("D")); - - db.close(); - } - } - - public void testDeleteRow() throws Exception { - - // make sure correct row is deleted - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - createTestTable(db); - Table table = db.getTable("Test"); - for(int i = 0; i < 10; ++i) { - table.addRowFromMap(createTestRowMap("Tim" + i)); - } - assertRowCount(10, table); - - table.reset(); - - List<Row> rows = RowFilterTest.toList(table); - - Row r1 = rows.remove(7); - Row r2 = rows.remove(3); - assertEquals(8, rows.size()); - - assertSame(r2, table.deleteRow(r2)); - assertSame(r1, table.deleteRow(r1)); - - assertTable(rows, table); - - table.deleteRow(r2); - table.deleteRow(r1); - - assertTable(rows, table); - } - } - - public void testReadLongValue() throws Exception { - - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.TEST2, true)) { - Database db = open(testDB); - Table table = db.getTable("MSP_PROJECTS"); - Map<String, Object> row = table.getNextRow(); - assertEquals("Jon Iles this is a a vawesrasoih aksdkl fas dlkjflkasjd flkjaslkdjflkajlksj dfl lkasjdf lkjaskldfj lkas dlk lkjsjdfkl; aslkdf lkasjkldjf lka skldf lka sdkjfl;kasjd falksjdfljaslkdjf laskjdfk jalskjd flkj aslkdjflkjkjasljdflkjas jf;lkasjd fjkas dasdf asd fasdf asdf asdmhf lksaiyudfoi jasodfj902384jsdf9 aw90se fisajldkfj lkasj dlkfslkd jflksjadf as", row.get("PROJ_PROP_AUTHOR")); - assertEquals("T", row.get("PROJ_PROP_COMPANY")); - assertEquals("Standard", row.get("PROJ_INFO_CAL_NAME")); - assertEquals("Project1", row.get("PROJ_PROP_TITLE")); - byte[] foundBinaryData = (byte[])row.get("RESERVED_BINARY_DATA"); - byte[] expectedBinaryData = - toByteArray(new File("test/data/test2BinData.dat")); - assertTrue(Arrays.equals(expectedBinaryData, foundBinaryData)); - - db.close(); - } - } - - public void testWriteLongValue() throws Exception { - - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - Table table = - new TableBuilder("test") - .addColumn(new ColumnBuilder("A", DataType.TEXT)) - .addColumn(new ColumnBuilder("B", DataType.MEMO)) - .addColumn(new ColumnBuilder("C", DataType.OLE)) - .toTable(db); - - String testStr = "This is a test"; - String longMemo = createString(2030); - byte[] oleValue = toByteArray(new File("test/data/test2BinData.dat")); - - - table.addRow(testStr, testStr, null); - table.addRow(testStr, longMemo, oleValue); - - table.reset(); - - Map<String, Object> row = table.getNextRow(); - - assertEquals(testStr, row.get("A")); - assertEquals(testStr, row.get("B")); - assertNull(row.get("C")); - - row = table.getNextRow(); - - assertEquals(testStr, row.get("A")); - assertEquals(longMemo, row.get("B")); - assertTrue(Arrays.equals(oleValue, (byte[])row.get("C"))); - - db.close(); - } - } - - public void testManyMemos() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - final int numColumns = 126; - TableBuilder bigTableBuilder = new TableBuilder("test"); - - for (int i = 0; i < numColumns; i++) - { - bigTableBuilder.addColumn(new ColumnBuilder("column_" + i, DataType.MEMO)); - } - - Table bigTable = bigTableBuilder.toTable(db); - - List<Object[]> expectedRows = new ArrayList<Object[]>(); - - for (int j = 0; j < 3; j++) - { - Object[] rowData = new String[numColumns]; - for (int i = 0; i < numColumns; i++) - { - rowData[i] = "v_" + i + ";" + (j + 999); - } - expectedRows.add(rowData); - bigTable.addRow(rowData); - } - - String extra1 = createString(100); - String extra2 = createString(2050); - - for (int j = 0; j < 1; j++) - { - Object[] rowData = new String[numColumns]; - for (int i = 0; i < numColumns; i++) - { - rowData[i] = "v_" + i + ";" + (j + 999) + extra2; - } - expectedRows.add(rowData); - bigTable.addRow(rowData); - } - - for (int j = 0; j < 2; j++) - { - Object[] rowData = new String[numColumns]; - for (int i = 0; i < numColumns; i++) - { - String tmp = "v_" + i + ";" + (j + 999); - if((i % 3) == 0) { - tmp += extra1; - } else if((i % 7) == 0) { - tmp += extra2; - } - rowData[i] = tmp; - } - expectedRows.add(rowData); - bigTable.addRow(rowData); - } - - bigTable.reset(); - Iterator<Object[]> expIter = expectedRows.iterator(); - for(Map<?,?> row : bigTable) { - Object[] expectedRow = expIter.next(); - assertEquals(Arrays.asList(expectedRow), - new ArrayList<Object>(row.values())); - } - - db.close(); - } - } - - public void testMissingFile() throws Exception { - File bogusFile = new File("fooby-dooby.mdb"); - assertTrue(!bogusFile.exists()); - try { - new DatabaseBuilder(bogusFile).setReadOnly(true). - setAutoSync(_autoSync).open(); - fail("FileNotFoundException should have been thrown"); - } catch(FileNotFoundException e) { - } - assertTrue(!bogusFile.exists()); - } - - public void testReadWithDeletedCols() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.DEL_COL, true)) { - Table table = open(testDB).getTable("Table1"); - - Map<String, Object> expectedRow0 = new LinkedHashMap<String, Object>(); - expectedRow0.put("id", 0); - expectedRow0.put("id2", 2); - expectedRow0.put("data", "foo"); - expectedRow0.put("data2", "foo2"); - - Map<String, Object> expectedRow1 = new LinkedHashMap<String, Object>(); - expectedRow1.put("id", 3); - expectedRow1.put("id2", 5); - expectedRow1.put("data", "bar"); - expectedRow1.put("data2", "bar2"); - - int rowNum = 0; - Map<String, Object> row = null; - while ((row = table.getNextRow()) != null) { - if(rowNum == 0) { - assertEquals(expectedRow0, row); - } else if(rowNum == 1) { - assertEquals(expectedRow1, row); - } else if(rowNum >= 2) { - fail("should only have 2 rows"); - } - rowNum++; - } - - table.getDatabase().close(); - } - } - - public void testCurrency() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - Table table = new TableBuilder("test") - .addColumn(new ColumnBuilder("A", DataType.MONEY)) - .toTable(db); - - table.addRow(new BigDecimal("-2341234.03450")); - table.addRow(37L); - table.addRow("10000.45"); - - table.reset(); - - List<Object> foundValues = new ArrayList<Object>(); - Map<String, Object> row = null; - while((row = table.getNextRow()) != null) { - foundValues.add(row.get("A")); - } - - assertEquals(Arrays.asList( - new BigDecimal("-2341234.0345"), - new BigDecimal("37.0000"), - new BigDecimal("10000.4500")), - foundValues); - - try { - table.addRow(new BigDecimal("342523234145343543.3453")); - fail("IOException should have been thrown"); - } catch(IOException e) { - // ignored - } - - db.close(); - } - } - - public void testGUID() throws Exception - { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - Table table = new TableBuilder("test") - .addColumn(new ColumnBuilder("A", DataType.GUID)) - .toTable(db); - - table.addRow("{32A59F01-AA34-3E29-453F-4523453CD2E6}"); - table.addRow("{32a59f01-aa34-3e29-453f-4523453cd2e6}"); - table.addRow("{11111111-1111-1111-1111-111111111111}"); - table.addRow(" {FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF} "); - table.addRow(UUID.fromString("32a59f01-1234-3e29-4aaf-4523453cd2e6")); - - table.reset(); - - List<Object> foundValues = new ArrayList<Object>(); - Map<String, Object> row = null; - while((row = table.getNextRow()) != null) { - foundValues.add(row.get("A")); - } - - assertEquals(Arrays.asList( - "{32A59F01-AA34-3E29-453F-4523453CD2E6}", - "{32A59F01-AA34-3E29-453F-4523453CD2E6}", - "{11111111-1111-1111-1111-111111111111}", - "{FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF}", - "{32A59F01-1234-3E29-4AAF-4523453CD2E6}"), - foundValues); - - try { - table.addRow("3245234"); - fail("IOException should have been thrown"); - } catch(IOException e) { - // ignored - } - - db.close(); - } - } - - public void testNumeric() throws Exception - { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - ColumnBuilder col = new ColumnBuilder("A", DataType.NUMERIC) - .setScale(4).setPrecision(8).toColumn(); - assertTrue(col.getType().isVariableLength()); - - Table table = new TableBuilder("test") - .addColumn(col) - .addColumn(new ColumnBuilder("B", DataType.NUMERIC) - .setScale(8).setPrecision(28)) - .toTable(db); - - table.addRow(new BigDecimal("-1234.03450"), - new BigDecimal("23923434453436.36234219")); - table.addRow(37L, 37L); - table.addRow("1000.45", "-3452345321000"); - - table.reset(); - - List<Object> foundSmallValues = new ArrayList<Object>(); - List<Object> foundBigValues = new ArrayList<Object>(); - Map<String, Object> row = null; - while((row = table.getNextRow()) != null) { - foundSmallValues.add(row.get("A")); - foundBigValues.add(row.get("B")); - } - - assertEquals(Arrays.asList( - new BigDecimal("-1234.0345"), - new BigDecimal("37.0000"), - new BigDecimal("1000.4500")), - foundSmallValues); - assertEquals(Arrays.asList( - new BigDecimal("23923434453436.36234219"), - new BigDecimal("37.00000000"), - new BigDecimal("-3452345321000.00000000")), - foundBigValues); - - try { - table.addRow(new BigDecimal("3245234.234"), - new BigDecimal("3245234.234")); - fail("IOException should have been thrown"); - } catch(IOException e) { - // ignored - } - - db.close(); - } - } - - public void testFixedNumeric() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.FIXED_NUMERIC)) { - Database db = openCopy(testDB); - Table t = db.getTable("test"); - - boolean first = true; - for(Column col : t.getColumns()) { - if(first) { - assertTrue(col.isVariableLength()); - assertEquals(DataType.MEMO, col.getType()); - first = false; - } else { - assertFalse(col.isVariableLength()); - assertEquals(DataType.NUMERIC, col.getType()); - } - } - - Map<String, Object> row = t.getNextRow(); - assertEquals("some data", row.get("col1")); - assertEquals(new BigDecimal("1"), row.get("col2")); - assertEquals(new BigDecimal("0"), row.get("col3")); - assertEquals(new BigDecimal("0"), row.get("col4")); - assertEquals(new BigDecimal("4"), row.get("col5")); - assertEquals(new BigDecimal("-1"), row.get("col6")); - assertEquals(new BigDecimal("1"), row.get("col7")); - - Object[] tmpRow = new Object[]{ - "foo", new BigDecimal("1"), new BigDecimal(3), new BigDecimal("13"), - new BigDecimal("-17"), new BigDecimal("0"), new BigDecimal("8734")}; - t.addRow(tmpRow); - t.reset(); - - t.getNextRow(); - row = t.getNextRow(); - assertEquals(tmpRow[0], row.get("col1")); - assertEquals(tmpRow[1], row.get("col2")); - assertEquals(tmpRow[2], row.get("col3")); - assertEquals(tmpRow[3], row.get("col4")); - assertEquals(tmpRow[4], row.get("col5")); - assertEquals(tmpRow[5], row.get("col6")); - assertEquals(tmpRow[6], row.get("col7")); - - db.close(); - } - } - - public void testMultiPageTableDef() throws Exception - { - for (final TestDB testDB : SUPPORTED_DBS_TEST_FOR_READ) { - List<? extends Column> columns = open(testDB).getTable("Table2").getColumns(); - assertEquals(89, columns.size()); - } - } - - public void testOverflow() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.OVERFLOW, true)) { - Database mdb = open(testDB); - Table table = mdb.getTable("Table1"); - - // 7 rows, 3 and 5 are overflow - table.getNextRow(); - table.getNextRow(); - - Map<String, Object> row = table.getNextRow(); - assertEquals(Arrays.<Object>asList( - null, "row3col3", null, null, null, null, null, - "row3col9", null), - new ArrayList<Object>(row.values())); - - table.getNextRow(); - - row = table.getNextRow(); - assertEquals(Arrays.<Object>asList( - null, "row5col2", null, null, null, null, null, null, - null), - new ArrayList<Object>(row.values())); - - table.reset(); - assertRowCount(7, table); - - mdb.close(); - } - } - - public void testLongValueAsMiddleColumn() throws Exception - { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - Table newTable = new TableBuilder("NewTable") - .addColumn(new ColumnBuilder("a").setSQLType(Types.INTEGER)) - .addColumn(new ColumnBuilder("b").setSQLType(Types.LONGVARCHAR)) - .addColumn(new ColumnBuilder("c").setSQLType(Types.VARCHAR)) - .toTable(db); - - String lval = createString(2000); // "--2000 chars long text--"; - String tval = createString(40); // "--40chars long text--"; - newTable.addRow(new Integer(1), lval, tval); - - newTable = db.getTable("NewTable"); - Map<String, Object> readRow = newTable.getNextRow(); - assertEquals(new Integer(1), readRow.get("a")); - assertEquals(lval, readRow.get("b")); - assertEquals(tval, readRow.get("c")); - - db.close(); - } - } - - - public void testUsageMapPromotion() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.PROMOTION)) { - Database db = openCopy(testDB); - Table t = db.getTable("jobDB1"); - - assertTrue(((TableImpl)t).getOwnedPagesCursor().getUsageMap().toString() - .startsWith("(InlineHandler)")); - - String lval = createNonAsciiString(255); // "--255 chars long text--"; - - for(int i = 0; i < 1000; ++i) { - t.addRow(i, 13, 57, lval, lval, lval, lval, lval, lval, 47.0d); - } - - Set<Integer> ids = new HashSet<Integer>(); - for(Map<String,Object> row : t) { - ids.add((Integer)row.get("ID")); - } - assertEquals(1000, ids.size()); - - assertTrue(((TableImpl)t).getOwnedPagesCursor().getUsageMap().toString() - .startsWith("(ReferenceHandler)")); - - db.close(); - } - } - - - public void testLargeTableDef() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - final int numColumns = 90; - - List<ColumnBuilder> columns = new ArrayList<ColumnBuilder>(); - List<String> colNames = new ArrayList<String>(); - for(int i = 0; i < numColumns; ++i) { - String colName = "MyColumnName" + i; - colNames.add(colName); - columns.add(new ColumnBuilder(colName, DataType.TEXT).toColumn()); - } - - ((DatabaseImpl)db).createTable("test", columns); - - Table t = db.getTable("test"); - - List<String> row = new ArrayList<String>(); - Map<String,Object> expectedRowData = new LinkedHashMap<String, Object>(); - for(int i = 0; i < numColumns; ++i) { - String value = "" + i + " some row data"; - row.add(value); - expectedRowData.put(colNames.get(i), value); - } - - t.addRow(row.toArray()); - - t.reset(); - assertEquals(expectedRowData, t.getNextRow()); - - db.close(); - } - } - - public void testAutoNumber() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - Table table = new TableBuilder("test") - .addColumn(new ColumnBuilder("a", DataType.LONG) - .setAutoNumber(true)) - .addColumn(new ColumnBuilder("b", DataType.TEXT)) - .toTable(db); - - doTestAutoNumber(table); - - db.close(); - } - } - - public void testAutoNumberPK() throws Exception { - for (final TestDB testDB : SUPPORTED_DBS_TEST) { - Database db = openCopy(testDB); - - Table table = db.getTable("Table3"); - - doTestAutoNumber(table); - - db.close(); - } - } - - private void doTestAutoNumber(Table table) throws Exception - { - Object[] row = {null, "row1"}; - assertSame(row, table.addRow(row)); - assertEquals(1, ((Integer)row[0]).intValue()); - row = table.addRow(13, "row2"); - assertEquals(2, ((Integer)row[0]).intValue()); - row = table.addRow("flubber", "row3"); - assertEquals(3, ((Integer)row[0]).intValue()); - - table.reset(); - - row = table.addRow(Column.AUTO_NUMBER, "row4"); - assertEquals(4, ((Integer)row[0]).intValue()); - row = table.addRow(Column.AUTO_NUMBER, "row5"); - assertEquals(5, ((Integer)row[0]).intValue()); - - Object[] smallRow = {Column.AUTO_NUMBER}; - row = table.addRow(smallRow); - assertNotSame(row, smallRow); - assertEquals(6, ((Integer)row[0]).intValue()); - - table.reset(); - - List<? extends Map<String, Object>> expectedRows = - createExpectedTable( - createExpectedRow( - "a", 1, - "b", "row1"), - createExpectedRow( - "a", 2, - "b", "row2"), - createExpectedRow( - "a", 3, - "b", "row3"), - createExpectedRow( - "a", 4, - "b", "row4"), - createExpectedRow( - "a", 5, - "b", "row5"), - createExpectedRow( - "a", 6, - "b", null)); - - assertTable(expectedRows, table); - } - - public void testWriteAndReadDate() throws Exception { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - Table table = new TableBuilder("test") - .addColumn(new ColumnBuilder("name", DataType.TEXT)) - .addColumn(new ColumnBuilder("date", DataType.SHORT_DATE_TIME)) - .toTable(db); - - // since jackcess does not really store millis, shave them off before - // storing the current date/time - long curTimeNoMillis = (System.currentTimeMillis() / 1000L); - curTimeNoMillis *= 1000L; - - DateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); - List<Date> dates = - new ArrayList<Date>( - Arrays.asList( - df.parse("19801231 00:00:00"), - df.parse("19930513 14:43:27"), - null, - df.parse("20210102 02:37:00"), - new Date(curTimeNoMillis))); - - Calendar c = Calendar.getInstance(); - for(int year = 1801; year < 2050; year +=3) { - for(int month = 0; month <= 12; ++month) { - for(int day = 1; day < 29; day += 3) { - c.clear(); - c.set(Calendar.YEAR, year); - c.set(Calendar.MONTH, month); - c.set(Calendar.DAY_OF_MONTH, day); - dates.add(c.getTime()); - } - } - } - - for(Date d : dates) { - table.addRow("row " + d, d); - } - - List<Date> foundDates = new ArrayList<Date>(); - for(Map<String,Object> row : table) { - foundDates.add((Date)row.get("date")); - } - - assertEquals(dates.size(), foundDates.size()); - for(int i = 0; i < dates.size(); ++i) { - Date expected = dates.get(i); - Date found = foundDates.get(i); - assertSameDate(expected, found); - } - - db.close(); - } - } - - public void testSystemTable() throws Exception - { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - Set<String> sysTables = new TreeSet<String>( - String.CASE_INSENSITIVE_ORDER); - sysTables.addAll( - Arrays.asList("MSysObjects", "MSysQueries", "MSysACES", - "MSysRelationships")); - - if (fileFormat.ordinal() < FileFormat.V2003.ordinal()) { - assertNotNull("file format: " + fileFormat, db.getSystemTable("MSysAccessObjects")); - sysTables.add("MSysAccessObjects"); - } else { - // v2003+ template files have no "MSysAccessObjects" table - assertNull("file format: " + fileFormat, db.getSystemTable("MSysAccessObjects")); - sysTables.addAll( - Arrays.asList("MSysNavPaneGroupCategories", - "MSysNavPaneGroups", "MSysNavPaneGroupToObjects", - "MSysNavPaneObjectIDs", "MSysAccessStorage")); - if(fileFormat.ordinal() >= FileFormat.V2007.ordinal()) { - sysTables.addAll( - Arrays.asList( - "MSysComplexColumns", "MSysComplexType_Attachment", - "MSysComplexType_Decimal", "MSysComplexType_GUID", - "MSysComplexType_IEEEDouble", "MSysComplexType_IEEESingle", - "MSysComplexType_Long", "MSysComplexType_Short", - "MSysComplexType_Text", "MSysComplexType_UnsignedByte")); - } - if(fileFormat.ordinal() >= FileFormat.V2010.ordinal()) { - sysTables.add("f_12D7448B56564D8AAE333BCC9B3718E5_Data"); - sysTables.add("MSysResources"); - } - } - - assertEquals(sysTables, db.getSystemTableNames()); - - assertNotNull(db.getSystemTable("MSysObjects")); - assertNotNull(db.getSystemTable("MSysQueries")); - assertNotNull(db.getSystemTable("MSysACES")); - assertNotNull(db.getSystemTable("MSysRelationships")); - - assertNull(db.getSystemTable("MSysBogus")); - - - db.close(); - } - } - - public void testUpdateRow() throws Exception - { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - Table t = new TableBuilder("test") - .addColumn(new ColumnBuilder("name", DataType.TEXT)) - .addColumn(new ColumnBuilder("id", DataType.LONG) - .setAutoNumber(true)) - .addColumn(new ColumnBuilder("data", DataType.TEXT) - .setLength(JetFormat.TEXT_FIELD_MAX_LENGTH)) - .toTable(db); - - for(int i = 0; i < 10; ++i) { - t.addRow("row" + i, Column.AUTO_NUMBER, "initial data"); - } - - Cursor c = CursorBuilder.createCursor(t); - c.reset(); - c.moveNextRows(2); - Map<String,Object> row = c.getCurrentRow(); - - assertEquals(createExpectedRow("name", "row1", - "id", 2, - "data", "initial data"), - row); - - Map<String,Object> newRow = createExpectedRow( - "name", Column.KEEP_VALUE, - "id", Column.AUTO_NUMBER, - "data", "new data"); - assertSame(newRow, c.updateCurrentRowFromMap(newRow)); - assertEquals(createExpectedRow("name", "row1", - "id", 2, - "data", "new data"), - newRow); - - c.moveNextRows(3); - row = c.getCurrentRow(); - - assertEquals(createExpectedRow("name", "row4", - "id", 5, - "data", "initial data"), - row); - - c.updateCurrentRow(Column.KEEP_VALUE, Column.AUTO_NUMBER, "a larger amount of new data"); - - c.reset(); - c.moveNextRows(2); - row = c.getCurrentRow(); - - assertEquals(createExpectedRow("name", "row1", - "id", 2, - "data", "new data"), - row); - - c.moveNextRows(3); - row = c.getCurrentRow(); - - assertEquals(createExpectedRow("name", "row4", - "id", 5, - "data", "a larger amount of new data"), - row); - - t.reset(); - - String str = createString(100); - for(int i = 10; i < 50; ++i) { - t.addRow("row" + i, Column.AUTO_NUMBER, "big data_" + str); - } - - c.reset(); - c.moveNextRows(9); - row = c.getCurrentRow(); - - assertEquals(createExpectedRow("name", "row8", - "id", 9, - "data", "initial data"), - row); - - String newText = "updated big data_" + createString(200); - - c.setCurrentRowValue(t.getColumn("data"), newText); - - c.reset(); - c.moveNextRows(9); - row = c.getCurrentRow(); - - assertEquals(createExpectedRow("name", "row8", - "id", 9, - "data", newText), - row); - - List<Row> rows = RowFilterTest.toList(t); - assertEquals(50, rows.size()); - - for(Row r : rows) { - r.put("data", "final data " + r.get("id")); - } - - for(Row r : rows) { - assertSame(r, t.updateRow(r)); - } - - t.reset(); - - for(Row r : t) { - assertEquals("final data " + r.get("id"), r.get("data")); - } - - db.close(); - } - } - - public void testFixedText() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.FIXED_TEXT)) { - Database db = openCopy(testDB); - - Table t = db.getTable("users"); - Column c = t.getColumn("c_flag_"); - assertEquals(DataType.TEXT, c.getType()); - assertEquals(false, c.isVariableLength()); - assertEquals(2, c.getLength()); - - Map<String,Object> row = t.getNextRow(); - assertEquals("N", row.get("c_flag_")); - - t.addRow(3, "testFixedText", "boo", "foo", "bob", 3, 5, 9, "Y", - new Date()); - - t.getNextRow(); - row = t.getNextRow(); - assertEquals("testFixedText", row.get("c_user_login")); - assertEquals("Y", row.get("c_flag_")); - - db.close(); - } - } - - public void testDbSortOrder() throws Exception { - - for (final TestDB testDB : SUPPORTED_DBS_TEST_FOR_READ) { - - Database db = open(testDB); - assertEquals(((DatabaseImpl)db).getFormat().DEFAULT_SORT_ORDER, - ((DatabaseImpl)db).getDefaultSortOrder()); - db.close(); - } - } - - public void testUnsupportedColumns() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.UNSUPPORTED)) { - - Database db = open(testDB); - Table t = db.getTable("Test"); - Column varCol = t.getColumn("UnknownVar"); - assertEquals(DataType.UNSUPPORTED_VARLEN, varCol.getType()); - Column fixCol = t.getColumn("UnknownFix"); - assertEquals(DataType.UNSUPPORTED_FIXEDLEN, fixCol.getType()); - - List<String> varVals = Arrays.asList( - "RawData: FF FE 73 6F 6D 65 64 61 74 61", - "RawData: FF FE 6F 74 68 65 72 20 64 61 74 61", - null); - List<String> fixVals = Arrays.asList("RawData: 37 00 00 00", - "RawData: F3 FF FF FF", - "RawData: 02 00 00 00"); - - int idx = 0; - for(Map<String,Object> row : t) { - checkRawValue(varVals.get(idx), varCol.getRowValue(row)); - checkRawValue(fixVals.get(idx), fixCol.getRowValue(row)); - ++idx; - } - db.close(); - } - } - - public void testLinkedTables() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.LINKED)) { - Database db = openCopy(testDB); - - try { - db.getTable("Table2"); - fail("FileNotFoundException should have been thrown"); - } catch(FileNotFoundException e) { - // success - } - - assertTrue(db.getLinkedDatabases().isEmpty()); - - final String linkeeDbName = "Z:\\jackcess_test\\linkeeTest.accdb"; - final File linkeeFile = new File("test/data/linkeeTest.accdb"); - db.setLinkResolver(new LinkResolver() { - public Database resolveLinkedDatabase(Database linkerdb, String dbName) - throws IOException { - assertEquals(linkeeDbName, dbName); - return DatabaseBuilder.open(linkeeFile); - } - }); - - Table t2 = db.getTable("Table2"); - - assertEquals(1, db.getLinkedDatabases().size()); - Database linkeeDb = db.getLinkedDatabases().get(linkeeDbName); - assertNotNull(linkeeDb); - assertEquals(linkeeFile, linkeeDb.getFile()); - - List<? extends Map<String, Object>> expectedRows = - createExpectedTable( - createExpectedRow( - "ID", 1, - "Field1", "bar")); - - assertTable(expectedRows, t2); - - db.createLinkedTable("FooTable", linkeeDbName, "Table2"); - - Table t3 = db.getTable("FooTable"); - - assertEquals(1, db.getLinkedDatabases().size()); - - expectedRows = - createExpectedTable( - createExpectedRow( - "ID", 1, - "Field1", "buzz")); - - assertTable(expectedRows, t3); - - db.close(); - } - } - - public void testTimeZone() throws Exception - { - TimeZone tz = TimeZone.getTimeZone("America/New_York"); - doTestTimeZone(tz); - - tz = TimeZone.getTimeZone("Australia/Sydney"); - doTestTimeZone(tz); - } - - private static void doTestTimeZone(final TimeZone tz) throws Exception - { - ColumnImpl col = new ColumnImpl(null, DataType.SHORT_DATE_TIME, 0, 0, 0) { - @Override - protected Calendar getCalendar() { return Calendar.getInstance(tz); } - }; - - SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd"); - df.setTimeZone(tz); - - long startDate = df.parse("2012.01.01").getTime(); - long endDate = df.parse("2013.01.01").getTime(); - - Calendar curCal = Calendar.getInstance(tz); - curCal.setTimeInMillis(startDate); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss"); - sdf.setTimeZone(tz); - - while(curCal.getTimeInMillis() < endDate) { - Date curDate = curCal.getTime(); - Date newDate = new Date(col.fromDateDouble(col.toDateDouble(curDate))); - if(curDate.getTime() != newDate.getTime()) { - assertEquals(sdf.format(curDate), sdf.format(newDate)); - } - curCal.add(Calendar.MINUTE, 30); - } - } - - private void checkRawValue(String expected, Object val) - { - if(expected != null) { - assertTrue(ColumnImpl.isRawData(val)); - assertEquals(expected, val.toString()); - } else { - assertNull(val); - } - } - - static Object[] createTestRow(String col1Val) { - return new Object[] {col1Val, "R", "McCune", 1234, (byte) 0xad, 555.66d, - 777.88f, (short) 999, new Date()}; - } - - static Object[] createTestRow() { - return createTestRow("Tim"); - } - - static Map<String,Object> createTestRowMap(String col1Val) { - return createExpectedRow("A", col1Val, "B", "R", "C", "McCune", - "D", 1234, "E", (byte) 0xad, "F", 555.66d, - "G", 777.88f, "H", (short) 999, "I", new Date()); - } - - static void createTestTable(Database db) throws Exception { - new TableBuilder("test") - .addColumn(new ColumnBuilder("A", DataType.TEXT)) - .addColumn(new ColumnBuilder("B", DataType.TEXT)) - .addColumn(new ColumnBuilder("C", DataType.TEXT)) - .addColumn(new ColumnBuilder("D", DataType.LONG)) - .addColumn(new ColumnBuilder("E", DataType.BYTE)) - .addColumn(new ColumnBuilder("F", DataType.DOUBLE)) - .addColumn(new ColumnBuilder("G", DataType.FLOAT)) - .addColumn(new ColumnBuilder("H", DataType.INT)) - .addColumn(new ColumnBuilder("I", DataType.SHORT_DATE_TIME)) - .toTable(db); - } - - public static String createString(int len) { - return createString(len, 'a'); - } - - static String createNonAsciiString(int len) { - return createString(len, '\u00C0'); - } - - private static String createString(int len, char firstChar) { - StringBuilder builder = new StringBuilder(len); - for(int i = 0; i < len; ++i) { - builder.append((char)(firstChar + (i % 26))); - } - return builder.toString(); - } - - static void assertRowCount(int expectedRowCount, Table table) - throws Exception - { - assertEquals(expectedRowCount, countRows(table)); - assertEquals(expectedRowCount, table.getRowCount()); - } - - public static int countRows(Table table) throws Exception { - int rtn = 0; - for(Map<String, Object> row : CursorBuilder.createCursor(table)) { - rtn++; - } - return rtn; - } - - public static void assertTable( - List<? extends Map<String, Object>> expectedTable, - Table table) - throws IOException - { - assertCursor(expectedTable, CursorBuilder.createCursor(table)); - } - - public static void assertCursor( - List<? extends Map<String, Object>> expectedTable, - Cursor cursor) - { - List<Map<String, Object>> foundTable = - new ArrayList<Map<String, Object>>(); - for(Map<String, Object> row : cursor) { - foundTable.add(row); - } - assertEquals(expectedTable, foundTable); - } - - public static RowImpl createExpectedRow(Object... rowElements) { - RowImpl row = new RowImpl((RowIdImpl)null); - for(int i = 0; i < rowElements.length; i += 2) { - row.put((String)rowElements[i], - rowElements[i + 1]); - } - return row; - } - - @SuppressWarnings("unchecked") - public static List<Row> createExpectedTable(Row... rows) { - return Arrays.<Row>asList(rows); - } - - static void dumpDatabase(Database mdb) throws Exception { - dumpDatabase(mdb, false); - } - - static void dumpDatabase(Database mdb, boolean systemTables) - throws Exception - { - dumpDatabase(mdb, systemTables, new PrintWriter(System.out, true)); - } - - static void dumpTable(Table table) throws Exception { - dumpTable(table, new PrintWriter(System.out, true)); - } - - static void dumpDatabase(Database mdb, boolean systemTables, - PrintWriter writer) throws Exception - { - writer.println("DATABASE:"); - for(Table table : mdb) { - dumpTable(table, writer); - } - if(systemTables) { - for(String sysTableName : mdb.getSystemTableNames()) { - dumpTable(mdb.getSystemTable(sysTableName), writer); - } - } - } - - static void dumpTable(Table table, PrintWriter writer) throws Exception { - // make sure all indexes are read - for(Index index : table.getIndexes()) { - ((IndexImpl)index).initialize(); - } - - writer.println("TABLE: " + table.getName()); - List<String> colNames = new ArrayList<String>(); - for(Column col : table.getColumns()) { - colNames.add(col.getName()); - } - writer.println("COLUMNS: " + colNames); - for(Map<String, Object> row : CursorBuilder.createCursor(table)) { - writer.println(massageRow(row)); - } - } - - private static Map<String,Object> massageRow(Map<String, Object> row) - throws IOException - { - for(Map.Entry<String, Object> entry : row.entrySet()) { - Object v = entry.getValue(); - if(v instanceof byte[]) { - // make byte[] printable - byte[] bv = (byte[])v; - entry.setValue(ByteUtil.toHexString(ByteBuffer.wrap(bv), bv.length)); - } else if(v instanceof ComplexValueForeignKey) { - // deref complex values - String str = "ComplexValue(" + v + ")" + - ((ComplexValueForeignKey)v).getValues(); - entry.setValue(str); - } - } - - return row; - } - - static void dumpIndex(Index index) throws Exception { - dumpIndex(index, new PrintWriter(System.out, true)); - } - - static void dumpIndex(Index index, PrintWriter writer) throws Exception { - writer.println("INDEX: " + index); - IndexData.EntryCursor ec = ((IndexImpl)index).cursor(); - IndexData.Entry lastE = ec.getLastEntry(); - IndexData.Entry e = null; - while((e = ec.getNextEntry()) != lastE) { - writer.println(e); - } - } - - static void assertSameDate(Date expected, Date found) - { - if(expected == found) { - return; - } - if((expected == null) || (found == null)) { - throw new AssertionError("Expected " + expected + ", found " + found); - } - long expTime = expected.getTime(); - long foundTime = found.getTime(); - // there are some rounding issues due to dates being stored as doubles, - // but it results in a 1 millisecond difference, so i'm not going to worry - // about it - if((expTime != foundTime) && (Math.abs(expTime - foundTime) > 1)) { - throw new AssertionError("Expected " + expTime + " (" + expected + - "), found " + foundTime + " (" + found + ")"); - } - } - - static void copyFile(File srcFile, File dstFile) - throws IOException - { - // FIXME should really be using commons io FileUtils here, but don't want - // to add dep for one simple test method - byte[] buf = new byte[1024]; - OutputStream ostream = new FileOutputStream(dstFile); - InputStream istream = new FileInputStream(srcFile); - try { - int numBytes = 0; - while((numBytes = istream.read(buf)) >= 0) { - ostream.write(buf, 0, numBytes); - } - } finally { - ostream.close(); - } - } - - static File createTempFile(boolean keep) throws Exception { - File tmp = File.createTempFile("databaseTest", ".mdb"); - if(keep) { - System.out.println("Created " + tmp); - } else { - tmp.deleteOnExit(); - } - return tmp; - } - - public static byte[] toByteArray(File file) - throws IOException - { - // FIXME should really be using commons io IOUtils here, but don't want - // to add dep for one simple test method - FileInputStream istream = new FileInputStream(file); - try { - byte[] bytes = new byte[(int)file.length()]; - istream.read(bytes); - return bytes; - } finally { - istream.close(); - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/IndexTest.java b/test/src/java/com/healthmarketscience/jackcess/IndexTest.java deleted file mode 100644 index 777750e..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/IndexTest.java +++ /dev/null @@ -1,530 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.SortedSet; -import java.util.TreeSet; - -import static com.healthmarketscience.jackcess.Database.*; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.impl.ByteUtil; -import com.healthmarketscience.jackcess.impl.IndexCodesTest; -import com.healthmarketscience.jackcess.impl.IndexData; -import com.healthmarketscience.jackcess.impl.IndexImpl; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import com.healthmarketscience.jackcess.impl.RowIdImpl; -import com.healthmarketscience.jackcess.impl.TableImpl; -import junit.framework.TestCase; - -/** - * @author James Ahlborn - */ -public class IndexTest extends TestCase { - - public IndexTest(String name) { - super(name); - } - - public void testByteOrder() throws Exception { - byte b1 = (byte)0x00; - byte b2 = (byte)0x01; - byte b3 = (byte)0x7F; - byte b4 = (byte)0x80; - byte b5 = (byte)0xFF; - - assertTrue(ByteUtil.asUnsignedByte(b1) < ByteUtil.asUnsignedByte(b2)); - assertTrue(ByteUtil.asUnsignedByte(b2) < ByteUtil.asUnsignedByte(b3)); - assertTrue(ByteUtil.asUnsignedByte(b3) < ByteUtil.asUnsignedByte(b4)); - assertTrue(ByteUtil.asUnsignedByte(b4) < ByteUtil.asUnsignedByte(b5)); - } - - public void testByteCodeComparator() { - byte[] b0 = null; - byte[] b1 = new byte[]{(byte)0x00}; - byte[] b2 = new byte[]{(byte)0x00, (byte)0x00}; - byte[] b3 = new byte[]{(byte)0x00, (byte)0x01}; - byte[] b4 = new byte[]{(byte)0x01}; - byte[] b5 = new byte[]{(byte)0x80}; - byte[] b6 = new byte[]{(byte)0xFF}; - byte[] b7 = new byte[]{(byte)0xFF, (byte)0x00}; - byte[] b8 = new byte[]{(byte)0xFF, (byte)0x01}; - - List<byte[]> expectedList = Arrays.<byte[]>asList(b0, b1, b2, b3, b4, - b5, b6, b7, b8); - SortedSet<byte[]> sortedSet = new TreeSet<byte[]>( - IndexData.BYTE_CODE_COMPARATOR); - sortedSet.addAll(expectedList); - assertEquals(expectedList, new ArrayList<byte[]>(sortedSet)); - - } - - public void testPrimaryKey() throws Exception { - for (final TestDB testDB : SUPPORTED_DBS_TEST_FOR_READ) { - Table table = open(testDB).getTable("Table1"); - Map<String, Boolean> foundPKs = new HashMap<String, Boolean>(); - Index pkIndex = null; - for(Index index : table.getIndexes()) { - foundPKs.put(index.getColumns().iterator().next().getName(), - index.isPrimaryKey()); - if(index.isPrimaryKey()) { - pkIndex= index; - - } - } - Map<String, Boolean> expectedPKs = new HashMap<String, Boolean>(); - expectedPKs.put("A", Boolean.TRUE); - expectedPKs.put("B", Boolean.FALSE); - assertEquals(expectedPKs, foundPKs); - assertSame(pkIndex, table.getPrimaryKeyIndex()); - } - } - - public void testLogicalIndexes() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX, true)) { - Database mdb = open(testDB); - - TableImpl table = (TableImpl)mdb.getTable("Table1"); - for(IndexImpl idx : table.getIndexes()) { - idx.initialize(); - } - assertEquals(4, table.getIndexes().size()); - assertEquals(4, table.getLogicalIndexCount()); - checkIndexColumns(table, - "id", "id", - "PrimaryKey", "id", - "Table2Table1", "otherfk1", - "Table3Table1", "otherfk2"); - - table = (TableImpl)mdb.getTable("Table2"); - for(IndexImpl idx : table.getIndexes()) { - idx.initialize(); - } - assertEquals(3, table.getIndexes().size()); - assertEquals(2, table.getIndexDatas().size()); - assertEquals(3, table.getLogicalIndexCount()); - checkIndexColumns(table, - "id", "id", - "PrimaryKey", "id", - ".rC", "id"); - - IndexImpl pkIdx = table.getIndex("PrimaryKey"); - IndexImpl fkIdx = table.getIndex(".rC"); - assertNotSame(pkIdx, fkIdx); - assertTrue(fkIdx.isForeignKey()); - assertSame(pkIdx.getIndexData(), fkIdx.getIndexData()); - IndexData indexData = pkIdx.getIndexData(); - assertEquals(Arrays.asList(pkIdx, fkIdx), indexData.getIndexes()); - assertSame(pkIdx, indexData.getPrimaryIndex()); - - table = (TableImpl)mdb.getTable("Table3"); - for(IndexImpl idx : table.getIndexes()) { - idx.initialize(); - } - assertEquals(3, table.getIndexes().size()); - assertEquals(2, table.getIndexDatas().size()); - assertEquals(3, table.getLogicalIndexCount()); - checkIndexColumns(table, - "id", "id", - "PrimaryKey", "id", - ".rC", "id"); - - pkIdx = table.getIndex("PrimaryKey"); - fkIdx = table.getIndex(".rC"); - assertNotSame(pkIdx, fkIdx); - assertTrue(fkIdx.isForeignKey()); - assertSame(pkIdx.getIndexData(), fkIdx.getIndexData()); - indexData = pkIdx.getIndexData(); - assertEquals(Arrays.asList(pkIdx, fkIdx), indexData.getIndexes()); - assertSame(pkIdx, indexData.getPrimaryIndex()); - } - } - - public void testComplexIndex() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.COMP_INDEX)) { - // this file has an index with "compressed" entries and node pages - Database db = open(testDB); - TableImpl t = (TableImpl)db.getTable("Table1"); - IndexImpl index = t.getIndexes().get(0); - assertFalse(index.isInitialized()); - assertEquals(512, countRows(t)); - assertEquals(512, index.getIndexData().getEntryCount()); - db.close(); - - // copy to temp file and attempt to edit - db = openCopy(testDB); - t = (TableImpl)db.getTable("Table1"); - index = t.getIndexes().get(0); - - t.addRow(99, "abc", "def"); - } - } - - public void testEntryDeletion() throws Exception { - for (final TestDB testDB : SUPPORTED_DBS_TEST) { - Table table = openCopy(testDB).getTable("Table1"); - - for(int i = 0; i < 10; ++i) { - table.addRow("foo" + i, "bar" + i, (byte)42 + i, (short)53 + i, 13 * i, - (6.7d / i), null, null, true); - } - table.reset(); - assertRowCount(12, table); - - for(Index index : table.getIndexes()) { - assertEquals(12, ((IndexImpl)index).getIndexData().getEntryCount()); - } - - table.reset(); - table.getNextRow(); - table.getNextRow(); - table.getDefaultCursor().deleteCurrentRow(); - table.getNextRow(); - table.getDefaultCursor().deleteCurrentRow(); - table.getNextRow(); - table.getNextRow(); - table.getDefaultCursor().deleteCurrentRow(); - table.getNextRow(); - table.getNextRow(); - table.getNextRow(); - table.getDefaultCursor().deleteCurrentRow(); - - table.reset(); - assertRowCount(8, table); - - for(Index index : table.getIndexes()) { - assertEquals(8, ((IndexImpl)index).getIndexData().getEntryCount()); - } - } - } - - public void testIgnoreNulls() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX_PROPERTIES)) { - Database db = openCopy(testDB); - - doTestIgnoreNulls(db, "TableIgnoreNulls1"); - doTestIgnoreNulls(db, "TableIgnoreNulls2"); - - db.close(); - } - } - - private void doTestIgnoreNulls(Database db, String tableName) - throws Exception - { - Table orig = db.getTable(tableName); - IndexImpl origI = (IndexImpl)orig.getIndex("DataIndex"); - Table temp = db.getTable(tableName + "_temp"); - IndexImpl tempI = (IndexImpl)temp.getIndex("DataIndex"); - - // copy from orig table to temp table - for(Map<String,Object> row : orig) { - temp.addRow(orig.asRow(row)); - } - - assertEquals(origI.getIndexData().getEntryCount(), - tempI.getIndexData().getEntryCount()); - - Cursor origC = origI.newCursor().toCursor(); - Cursor tempC = tempI.newCursor().toCursor(); - - while(true) { - boolean origHasNext = origC.moveToNextRow(); - boolean tempHasNext = tempC.moveToNextRow(); - assertTrue(origHasNext == tempHasNext); - if(!origHasNext) { - break; - } - - Map<String,Object> origRow = origC.getCurrentRow(); - Cursor.Position origCurPos = origC.getSavepoint().getCurrentPosition(); - Map<String,Object> tempRow = tempC.getCurrentRow(); - Cursor.Position tempCurPos = tempC.getSavepoint().getCurrentPosition(); - - assertEquals(origRow, tempRow); - assertEquals(IndexCodesTest.entryToString(origCurPos), - IndexCodesTest.entryToString(tempCurPos)); - } - } - - public void testUnique() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX_PROPERTIES)) { - Database db = openCopy(testDB); - - Table t = db.getTable("TableUnique1_temp"); - Index index = t.getIndex("DataIndex"); - - doTestUnique(index, 1, - null, true, - "unique data", true, - null, true, - "more", false, - "stuff", false, - "unique data", false); - - t = db.getTable("TableUnique2_temp"); - index = t.getIndex("DataIndex"); - - doTestUnique(index, 2, - null, null, true, - "unique data", 42, true, - "unique data", null, true, - null, null, true, - "some", 42, true, - "more unique data", 13, true, - null, -4242, true, - "another row", -3462, false, - null, 49, false, - "more", null, false, - "unique data", 42, false, - "unique data", null, false, - null, -4242, false); - - db.close(); - } - } - - private void doTestUnique(Index index, int numValues, - Object... testData) - throws Exception - { - for(int i = 0; i < testData.length; i += (numValues + 1)) { - Object[] row = new Object[numValues + 1]; - row[0] = "testRow" + i; - for(int j = 1; j < (numValues + 1); ++j) { - row[j] = testData[i + j - 1]; - } - boolean expectedSuccess = (Boolean)testData[i + numValues]; - - IOException failure = null; - try { - ((IndexImpl)index).addRow(row, new RowIdImpl(400 + i, 0)); - } catch(IOException e) { - failure = e; - } - if(expectedSuccess) { - assertNull(failure); - } else { - assertTrue(failure != null); - assertTrue(failure.getMessage().contains("uniqueness")); - } - } - } - - public void testUniqueEntryCount() throws Exception { - for (final TestDB testDB : SUPPORTED_DBS_TEST) { - Database db = openCopy(testDB); - Table table = db.getTable("Table1"); - IndexImpl indA = (IndexImpl)table.getIndex("PrimaryKey"); - IndexImpl indB = (IndexImpl)table.getIndex("B"); - - assertEquals(2, indA.getUniqueEntryCount()); - assertEquals(2, indB.getUniqueEntryCount()); - - List<String> bElems = Arrays.asList("bar", null, "baz", "argle", null, - "bazzle", "37", "bar", "bar", "BAZ"); - - for(int i = 0; i < 10; ++i) { - table.addRow("foo" + i, bElems.get(i), (byte)42 + i, (short)53 + i, - 13 * i, (6.7d / i), null, null, true); - } - - assertEquals(12, indA.getIndexData().getEntryCount()); - assertEquals(12, indB.getIndexData().getEntryCount()); - - assertEquals(12, indA.getUniqueEntryCount()); - assertEquals(8, indB.getUniqueEntryCount()); - - table = null; - indA = null; - indB = null; - - table = db.getTable("Table1"); - indA = (IndexImpl)table.getIndex("PrimaryKey"); - indB = (IndexImpl)table.getIndex("B"); - - assertEquals(12, indA.getIndexData().getEntryCount()); - assertEquals(12, indB.getIndexData().getEntryCount()); - - assertEquals(12, indA.getUniqueEntryCount()); - assertEquals(8, indB.getUniqueEntryCount()); - - Cursor c = CursorBuilder.createCursor(table); - assertTrue(c.moveToNextRow()); - - final Map<String,Object> row = c.getCurrentRow(); - // Row order is arbitrary, so v2007 row order difference is valid - if (testDB.getExpectedFileFormat().ordinal() >= - Database.FileFormat.V2007.ordinal()) { - DatabaseTest.checkTestDBTable1RowA(testDB, table, row); - } else { - DatabaseTest.checkTestDBTable1RowABCDEFG(testDB, table, row); - } - c.deleteCurrentRow(); - - assertEquals(11, indA.getIndexData().getEntryCount()); - assertEquals(11, indB.getIndexData().getEntryCount()); - - assertEquals(12, indA.getUniqueEntryCount()); - assertEquals(8, indB.getUniqueEntryCount()); - - db.close(); - } - } - - public void testReplId() throws Exception - { - for (final TestDB testDB : SUPPORTED_DBS_TEST) { - Database db = openCopy(testDB); - Table table = db.getTable("Table4"); - - for(int i = 0; i< 20; ++i) { - table.addRow("row" + i, Column.AUTO_NUMBER); - } - - assertEquals(20, table.getRowCount()); - - db.close(); - } - } - - public void testIndexCreation() throws Exception - { - for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - Table t = new TableBuilder("TestTable") - .addColumn(new ColumnBuilder("id", DataType.LONG)) - .addColumn(new ColumnBuilder("data", DataType.TEXT)) - .addIndex(new IndexBuilder(IndexBuilder.PRIMARY_KEY_NAME) - .addColumns("id").setPrimaryKey()) - .toTable(db); - - assertEquals(1, t.getIndexes().size()); - IndexImpl idx = (IndexImpl)t.getIndexes().get(0); - - assertEquals(IndexBuilder.PRIMARY_KEY_NAME, idx.getName()); - assertEquals(1, idx.getColumns().size()); - assertEquals("id", idx.getColumns().get(0).getName()); - assertTrue(idx.getColumns().get(0).isAscending()); - assertTrue(idx.isPrimaryKey()); - assertTrue(idx.isUnique()); - assertFalse(idx.shouldIgnoreNulls()); - assertNull(idx.getReference()); - - t.addRow(2, "row2"); - t.addRow(1, "row1"); - t.addRow(3, "row3"); - - Cursor c = t.newCursor() - .setIndexByName(IndexBuilder.PRIMARY_KEY_NAME).toCursor(); - - for(int i = 1; i <= 3; ++i) { - Map<String,Object> row = c.getNextRow(); - assertEquals(i, row.get("id")); - assertEquals("row" + i, row.get("data")); - } - assertFalse(c.moveToNextRow()); - } - } - - public void testGetForeignKeyIndex() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX, true)) { - Database db = open(testDB); - Table t1 = db.getTable("Table1"); - Table t2 = db.getTable("Table2"); - Table t3 = db.getTable("Table3"); - - IndexImpl t2t1 = (IndexImpl)t1.getIndex("Table2Table1"); - IndexImpl t3t1 = (IndexImpl)t1.getIndex("Table3Table1"); - - - assertTrue(t2t1.isForeignKey()); - assertNotNull(t2t1.getReference()); - assertFalse(t2t1.getReference().isPrimaryTable()); - assertFalse(t2t1.getReference().isCascadeUpdates()); - assertTrue(t2t1.getReference().isCascadeDeletes()); - doCheckForeignKeyIndex(t1, t2t1, t2); - - assertTrue(t3t1.isForeignKey()); - assertNotNull(t3t1.getReference()); - assertFalse(t3t1.getReference().isPrimaryTable()); - assertTrue(t3t1.getReference().isCascadeUpdates()); - assertFalse(t3t1.getReference().isCascadeDeletes()); - doCheckForeignKeyIndex(t1, t3t1, t3); - - Index t1pk = t1.getIndex(IndexBuilder.PRIMARY_KEY_NAME); - assertNotNull(t1pk); - assertNull(((IndexImpl)t1pk).getReference()); - assertNull(t1pk.getReferencedIndex()); - } - } - - private void doCheckForeignKeyIndex(Table ta, Index ia, Table tb) - throws Exception - { - IndexImpl ib = (IndexImpl)ia.getReferencedIndex(); - assertNotNull(ib); - assertSame(tb, ib.getTable()); - - assertNotNull(ib.getReference()); - assertSame(ia, ib.getReferencedIndex()); - assertTrue(ib.getReference().isPrimaryTable()); - } - - private void checkIndexColumns(Table table, String... idxInfo) - throws Exception - { - Map<String, String> expectedIndexes = new HashMap<String, String>(); - for(int i = 0; i < idxInfo.length; i+=2) { - expectedIndexes.put(idxInfo[i], idxInfo[i+1]); - } - - for(Index idx : table.getIndexes()) { - String colName = expectedIndexes.get(idx.getName()); - assertEquals(1, idx.getColumns().size()); - assertEquals(colName, idx.getColumns().get(0).getName()); - if("PrimaryKey".equals(idx.getName())) { - assertTrue(idx.isPrimaryKey()); - } else { - assertFalse(idx.isPrimaryKey()); - } - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/PropertiesTest.java b/test/src/java/com/healthmarketscience/jackcess/PropertiesTest.java deleted file mode 100644 index 8cd5a55..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/PropertiesTest.java +++ /dev/null @@ -1,211 +0,0 @@ -/* -Copyright (c) 2011 James Ahlborn - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA -*/ - -package com.healthmarketscience.jackcess; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import junit.framework.TestCase; -import com.healthmarketscience.jackcess.impl.PropertyMapImpl; -import com.healthmarketscience.jackcess.impl.PropertyMaps; -import static com.healthmarketscience.jackcess.Database.*; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import com.healthmarketscience.jackcess.impl.TableImpl; -import com.healthmarketscience.jackcess.impl.DatabaseImpl; - -/** - * @author James Ahlborn - */ -public class PropertiesTest extends TestCase -{ - - public PropertiesTest(String name) throws Exception { - super(name); - } - - public void testPropertyMaps() throws Exception - { - PropertyMaps maps = new PropertyMaps(10); - assertTrue(maps.isEmpty()); - assertEquals(0, maps.getSize()); - assertFalse(maps.iterator().hasNext()); - assertEquals(10, maps.getObjectId()); - - PropertyMapImpl defMap = maps.getDefault(); - assertTrue(defMap.isEmpty()); - assertEquals(0, defMap.getSize()); - assertFalse(defMap.iterator().hasNext()); - - PropertyMapImpl colMap = maps.get("testcol"); - assertTrue(colMap.isEmpty()); - assertEquals(0, colMap.getSize()); - assertFalse(colMap.iterator().hasNext()); - - assertFalse(maps.isEmpty()); - assertEquals(2, maps.getSize()); - - assertSame(defMap, maps.get(PropertyMaps.DEFAULT_NAME)); - assertEquals(PropertyMaps.DEFAULT_NAME, defMap.getName()); - assertSame(colMap, maps.get("TESTCOL")); - assertEquals("testcol", colMap.getName()); - - defMap.put("foo", DataType.TEXT, (byte)0, "bar"); - defMap.put("baz", DataType.LONG, (byte)1, 13); - - assertFalse(defMap.isEmpty()); - assertEquals(2, defMap.getSize()); - - colMap.put("buzz", DataType.BOOLEAN, (byte)0, Boolean.TRUE); - - assertFalse(colMap.isEmpty()); - assertEquals(1, colMap.getSize()); - - assertEquals("bar", defMap.getValue("foo")); - assertEquals("bar", defMap.getValue("FOO")); - assertNull(colMap.getValue("foo")); - assertEquals(13, defMap.get("baz").getValue()); - assertEquals(Boolean.TRUE, colMap.getValue("Buzz")); - - assertEquals("bar", defMap.getValue("foo", "blah")); - assertEquals("blah", defMap.getValue("bogus", "blah")); - - List<PropertyMap.Property> props = new ArrayList<PropertyMap.Property>(); - for(PropertyMap map : maps) { - for(PropertyMap.Property prop : map) { - props.add(prop); - } - } - - assertEquals(Arrays.asList(defMap.get("foo"), defMap.get("baz"), - colMap.get("buzz")), props); - } - - public void testReadProperties() throws Exception - { - byte[] nameMapBytes = null; - - for(TestDB testDb : SUPPORTED_DBS_TEST_FOR_READ) { - Database db = open(testDb); - - TableImpl t = (TableImpl)db.getTable("Table1"); - assertEquals(t.getTableDefPageNumber(), - t.getPropertyMaps().getObjectId()); - PropertyMap tProps = t.getProperties(); - assertEquals(PropertyMaps.DEFAULT_NAME, tProps.getName()); - int expectedNumProps = 3; - if(db.getFileFormat() != Database.FileFormat.V1997) { - assertEquals("{5A29A676-1145-4D1A-AE47-9F5415CDF2F1}", - tProps.getValue(PropertyMap.GUID_PROP)); - if(nameMapBytes == null) { - nameMapBytes = (byte[])tProps.getValue("NameMap"); - } else { - assertTrue(Arrays.equals(nameMapBytes, - (byte[])tProps.getValue("NameMap"))); - } - expectedNumProps += 2; - } - assertEquals(expectedNumProps, tProps.getSize()); - assertEquals((byte)0, tProps.getValue("Orientation")); - assertEquals(Boolean.FALSE, tProps.getValue("OrderByOn")); - assertEquals((byte)2, tProps.getValue("DefaultView")); - - PropertyMap colProps = t.getColumn("A").getProperties(); - assertEquals("A", colProps.getName()); - expectedNumProps = 9; - if(db.getFileFormat() != Database.FileFormat.V1997) { - assertEquals("{E9EDD90C-CE55-4151-ABE1-A1ACE1007515}", - colProps.getValue(PropertyMap.GUID_PROP)); - ++expectedNumProps; - } - assertEquals(expectedNumProps, colProps.getSize()); - assertEquals((short)-1, colProps.getValue("ColumnWidth")); - assertEquals((short)0, colProps.getValue("ColumnOrder")); - assertEquals(Boolean.FALSE, colProps.getValue("ColumnHidden")); - assertEquals(Boolean.FALSE, - colProps.getValue(PropertyMap.REQUIRED_PROP)); - assertEquals(Boolean.FALSE, - colProps.getValue(PropertyMap.ALLOW_ZERO_LEN_PROP)); - assertEquals((short)109, colProps.getValue("DisplayControl")); - assertEquals(Boolean.TRUE, colProps.getValue("UnicodeCompression")); - assertEquals((byte)0, colProps.getValue("IMEMode")); - assertEquals((byte)3, colProps.getValue("IMESentenceMode")); - - PropertyMap dbProps = db.getDatabaseProperties(); - assertTrue(((String)dbProps.getValue(PropertyMap.ACCESS_VERSION_PROP)) - .matches("[0-9]{2}[.][0-9]{2}")); - - PropertyMap sumProps = db.getSummaryProperties(); - assertEquals(3, sumProps.getSize()); - assertEquals("test", sumProps.getValue(PropertyMap.TITLE_PROP)); - assertEquals("tmccune", sumProps.getValue(PropertyMap.AUTHOR_PROP)); - assertEquals("Health Market Science", sumProps.getValue(PropertyMap.COMPANY_PROP)); - - PropertyMap userProps = db.getUserDefinedProperties(); - assertEquals(1, userProps.getSize()); - assertEquals(Boolean.TRUE, userProps.getValue("ReplicateProject")); - - db.close(); - } - } - - public void testParseProperties() throws Exception - { - for(FileFormat ff : SUPPORTED_FILEFORMATS_FOR_READ) { - File[] dbFiles = new File(DIR_TEST_DATA, ff.name()).listFiles(); - if(dbFiles == null) { - continue; - } - for(File f : dbFiles) { - - if(!f.isFile()) { - continue; - } - - Database db = open(ff, f); - - PropertyMap dbProps = db.getDatabaseProperties(); - assertFalse(dbProps.isEmpty()); - assertTrue(((String)dbProps.getValue(PropertyMap.ACCESS_VERSION_PROP)) - .matches("[0-9]{2}[.][0-9]{2}")); - - for(Map<String,Object> row : ((DatabaseImpl)db).getSystemCatalog()) { - int id = (Integer)row.get("Id"); - byte[] propBytes = (byte[])row.get("LvProp"); - PropertyMaps propMaps = ((DatabaseImpl)db).getPropertiesForObject(id); - int byteLen = ((propBytes != null) ? propBytes.length : 0); - if(byteLen == 0) { - assertTrue(propMaps.isEmpty()); - } else if(propMaps.isEmpty()) { - assertTrue(byteLen < 80); - } else { - assertTrue(byteLen > 0); - } - } - - db.close(); - } - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/RelationshipTest.java b/test/src/java/com/healthmarketscience/jackcess/RelationshipTest.java deleted file mode 100644 index e2162c3..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/RelationshipTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* -Copyright (c) 2008 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import com.healthmarketscience.jackcess.impl.RelationshipImpl; -import junit.framework.TestCase; - -/** - * @author James Ahlborn - */ -public class RelationshipTest extends TestCase { - - private static final Comparator<Relationship> REL_COMP = new Comparator<Relationship>() { - public int compare(Relationship r1, Relationship r2) { - return String.CASE_INSENSITIVE_ORDER.compare(r1.getName(), r2.getName()); - } - }; - - public RelationshipTest(String name) throws Exception { - super(name); - } - - public void testTwoTables() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX, true)) { - Database db = open(testDB); - Table t1 = db.getTable("Table1"); - Table t2 = db.getTable("Table2"); - Table t3 = db.getTable("Table3"); - - List<Relationship> rels = db.getRelationships(t1, t2); - assertEquals(1, rels.size()); - Relationship rel = rels.get(0); - assertEquals("Table2Table1", rel.getName()); - assertEquals(t2, rel.getFromTable()); - assertEquals(Arrays.asList(t2.getColumn("id")), - rel.getFromColumns()); - assertEquals(t1, rel.getToTable()); - assertEquals(Arrays.asList(t1.getColumn("otherfk1")), - rel.getToColumns()); - assertTrue(rel.hasReferentialIntegrity()); - assertEquals(4096, ((RelationshipImpl)rel).getFlags()); - assertTrue(rel.cascadeDeletes()); - assertSameRelationships(rels, db.getRelationships(t2, t1), true); - - rels = db.getRelationships(t2, t3); - assertTrue(db.getRelationships(t2, t3).isEmpty()); - assertSameRelationships(rels, db.getRelationships(t3, t2), true); - - rels = db.getRelationships(t1, t3); - assertEquals(1, rels.size()); - rel = rels.get(0); - assertEquals("Table3Table1", rel.getName()); - assertEquals(t3, rel.getFromTable()); - assertEquals(Arrays.asList(t3.getColumn("id")), - rel.getFromColumns()); - assertEquals(t1, rel.getToTable()); - assertEquals(Arrays.asList(t1.getColumn("otherfk2")), - rel.getToColumns()); - assertTrue(rel.hasReferentialIntegrity()); - assertEquals(256, ((RelationshipImpl)rel).getFlags()); - assertTrue(rel.cascadeUpdates()); - assertSameRelationships(rels, db.getRelationships(t3, t1), true); - - try { - db.getRelationships(t1, t1); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException ignored) { - // success - } - } - } - - public void testOneTable() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX, true)) { - Database db = open(testDB); - Table t1 = db.getTable("Table1"); - Table t2 = db.getTable("Table2"); - Table t3 = db.getTable("Table3"); - - List<Relationship> expected = new ArrayList<Relationship>(); - expected.addAll(db.getRelationships(t1, t2)); - expected.addAll(db.getRelationships(t2, t3)); - - assertSameRelationships(expected, db.getRelationships(t2), false); - - } - } - - public void testNoTables() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX, true)) { - Database db = open(testDB); - Table t1 = db.getTable("Table1"); - Table t2 = db.getTable("Table2"); - Table t3 = db.getTable("Table3"); - - List<Relationship> expected = new ArrayList<Relationship>(); - expected.addAll(db.getRelationships(t1, t2)); - expected.addAll(db.getRelationships(t2, t3)); - expected.addAll(db.getRelationships(t1, t3)); - - assertSameRelationships(expected, db.getRelationships(), false); - } - } - - private static void assertSameRelationships( - List<Relationship> expected, List<Relationship> found, boolean ordered) - { - assertEquals(expected.size(), found.size()); - if(!ordered) { - Collections.sort(expected, REL_COMP); - Collections.sort(found, REL_COMP); - } - for(int i = 0; i < expected.size(); ++i) { - Relationship eRel = expected.get(i); - Relationship fRel = found.get(i); - assertEquals(eRel.getName(), fRel.getName()); - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/TableTest.java b/test/src/java/com/healthmarketscience/jackcess/TableTest.java deleted file mode 100644 index b70c045..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/TableTest.java +++ /dev/null @@ -1,221 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.List; -import java.util.TimeZone; - -import com.healthmarketscience.jackcess.impl.ColumnImpl; -import com.healthmarketscience.jackcess.impl.JetFormat; -import com.healthmarketscience.jackcess.impl.PageChannel; -import com.healthmarketscience.jackcess.impl.TableImpl; -import junit.framework.TestCase; - -/** - * @author Tim McCune - */ -public class TableTest extends TestCase { - - private final PageChannel _pageChannel = new PageChannel(true) {}; - private List<ColumnImpl> _columns = new ArrayList<ColumnImpl>(); - private TableImpl _testTable; - private int _varLenIdx; - private int _fixedOffset; - - - public TableTest(String name) { - super(name); - } - - private void reset() { - _testTable = null; - _columns = new ArrayList<ColumnImpl>(); - _varLenIdx = 0; - _fixedOffset = 0; - } - - public void testCreateRow() throws Exception { - reset(); - newTestColumn(DataType.INT, false); - newTestColumn(DataType.TEXT, false); - newTestColumn(DataType.TEXT, false); - newTestTable(); - - int colCount = _columns.size(); - ByteBuffer buffer = createRow(9, "Tim", "McCune"); - - assertEquals((short) colCount, buffer.getShort()); - assertEquals((short) 9, buffer.getShort()); - assertEquals((byte) 'T', buffer.get()); - assertEquals((short) 22, buffer.getShort(22)); - assertEquals((short) 10, buffer.getShort(24)); - assertEquals((short) 4, buffer.getShort(26)); - assertEquals((short) 2, buffer.getShort(28)); - assertEquals((byte) 7, buffer.get(30)); - } - - public void testUnicodeCompression() throws Exception { - reset(); - newTestColumn(DataType.TEXT, false); - newTestColumn(DataType.MEMO, false); - newTestTable(); - - String small = "this is a string"; - String smallNotAscii = "this is a string\0"; - String large = DatabaseTest.createString(30); - String largeNotAscii = large + "\0"; - - ByteBuffer[] buf1 = encodeColumns(small, large); - ByteBuffer[] buf2 = encodeColumns(smallNotAscii, largeNotAscii); - - reset(); - newTestColumn(DataType.TEXT, true); - newTestColumn(DataType.MEMO, true); - newTestTable(); - - ByteBuffer[] bufCmp1 = encodeColumns(small, large); - ByteBuffer[] bufCmp2 = encodeColumns(smallNotAscii, largeNotAscii); - - assertEquals(buf1[0].remaining(), - (bufCmp1[0].remaining() + small.length() - 2)); - assertEquals(buf1[1].remaining(), - (bufCmp1[1].remaining() + large.length() - 2)); - - for(int i = 0; i < buf2.length; ++i) { - assertTrue(Arrays.equals(toBytes(buf2[i]), toBytes(bufCmp2[i]))); - } - - assertEquals(Arrays.asList(small, large), - Arrays.asList(decodeColumns(bufCmp1))); - assertEquals(Arrays.asList(smallNotAscii, largeNotAscii), - Arrays.asList(decodeColumns(bufCmp2))); - - } - - private ByteBuffer createRow(Object... row) - throws IOException - { - return _testTable.createRow( - row, _testTable.getPageChannel().createPageBuffer()); - } - - private ByteBuffer[] encodeColumns(Object... row) - throws IOException - { - ByteBuffer[] result = new ByteBuffer[_columns.size()]; - for(int i = 0; i < _columns.size(); ++i) { - ColumnImpl col = _columns.get(i); - result[i] = col.write(row[i], _testTable.getFormat().MAX_ROW_SIZE); - } - return result; - } - - private Object[] decodeColumns(ByteBuffer[] buffers) - throws IOException - { - Object[] result = new Object[_columns.size()]; - for(int i = 0; i < _columns.size(); ++i) { - ColumnImpl col = _columns.get(i); - result[i] = col.read(toBytes(buffers[i])); - } - return result; - } - - private static byte[] toBytes(ByteBuffer buffer) { - buffer.rewind(); - byte[] b = new byte[buffer.remaining()]; - buffer.get(b); - return b; - } - - private TableImpl newTestTable() - throws Exception - { - _testTable = new TableImpl(true, _columns) { - @Override - public PageChannel getPageChannel() { - return _pageChannel; - } - @Override - public JetFormat getFormat() { - return JetFormat.VERSION_4; - } - }; - return _testTable; - } - - private void newTestColumn(DataType type, final boolean compressedUnicode) { - - int nextColIdx = _columns.size(); - int nextVarLenIdx = 0; - int nextFixedOff = 0; - - if(type.isVariableLength()) { - nextVarLenIdx = _varLenIdx++; - } else { - nextFixedOff = _fixedOffset; - _fixedOffset += type.getFixedSize(); - } - - ColumnImpl col = new ColumnImpl(null, type, nextColIdx, nextFixedOff, nextVarLenIdx) { - @Override - public TableImpl getTable() { - return _testTable; - } - @Override - public JetFormat getFormat() { - return getTable().getFormat(); - } - @Override - public PageChannel getPageChannel() { - return getTable().getPageChannel(); - } - @Override - protected Charset getCharset() { - return getFormat().CHARSET; - } - @Override - protected Calendar getCalendar() { - return Calendar.getInstance(); - } - @Override - public boolean isCompressedUnicode() { - return compressedUnicode; - } - }; - - _columns.add(col); - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/impl/CodecHandlerTest.java b/test/src/java/com/healthmarketscience/jackcess/impl/CodecHandlerTest.java deleted file mode 100644 index 47a832a..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/impl/CodecHandlerTest.java +++ /dev/null @@ -1,304 +0,0 @@ -/* -Copyright (c) 2012 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess.impl; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.charset.Charset; -import java.util.Iterator; -import java.util.Map; - -import com.healthmarketscience.jackcess.ColumnBuilder; -import com.healthmarketscience.jackcess.Cursor; -import com.healthmarketscience.jackcess.CursorBuilder; -import com.healthmarketscience.jackcess.DataType; -import com.healthmarketscience.jackcess.Database; -import com.healthmarketscience.jackcess.DatabaseBuilder; -import com.healthmarketscience.jackcess.DatabaseTest; -import com.healthmarketscience.jackcess.DatabaseTest; -import com.healthmarketscience.jackcess.IndexBuilder; -import com.healthmarketscience.jackcess.Table; -import com.healthmarketscience.jackcess.TableBuilder; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import junit.framework.TestCase; - -/** - * - * @author James Ahlborn - */ -public class CodecHandlerTest extends TestCase -{ - private static final CodecProvider SIMPLE_PROVIDER = new CodecProvider() { - public CodecHandler createHandler(PageChannel channel, Charset charset) - throws IOException - { - return new SimpleCodecHandler(channel); - } - }; - private static final CodecProvider FULL_PROVIDER = new CodecProvider() { - public CodecHandler createHandler(PageChannel channel, Charset charset) - throws IOException - { - return new FullCodecHandler(channel); - } - }; - - - public CodecHandlerTest(String name) throws Exception { - super(name); - } - - public void testCodecHandler() throws Exception - { - doTestCodecHandler(true); - doTestCodecHandler(false); - } - - private static void doTestCodecHandler(boolean simple) throws Exception - { - for(Database.FileFormat ff : SUPPORTED_FILEFORMATS) { - Database db = DatabaseTest.create(ff); - int pageSize = ((DatabaseImpl)db).getFormat().PAGE_SIZE; - File dbFile = db.getFile(); - db.close(); - - // apply encoding to file - encodeFile(dbFile, pageSize, simple); - - db = new DatabaseBuilder(dbFile) - .setCodecProvider(simple ? SIMPLE_PROVIDER : FULL_PROVIDER) - .open(); - - Table t1 = new TableBuilder("test1") - .addColumn(new ColumnBuilder("id", DataType.LONG).setAutoNumber(true)) - .addColumn(new ColumnBuilder("data", DataType.TEXT).setLength(250)) - .setPrimaryKey("id") - .addIndex(new IndexBuilder("data_idx").addColumns("data")) - .toTable(db); - - Table t2 = new TableBuilder("test2") - .addColumn(new ColumnBuilder("id", DataType.LONG).setAutoNumber(true)) - .addColumn(new ColumnBuilder("data", DataType.TEXT).setLength(250)) - .setPrimaryKey("id") - .addIndex(new IndexBuilder("data_idx").addColumns("data")) - .toTable(db); - - int autonum = 1; - for(int i = 1; i < 2; ++i) { - writeData(t1, t2, autonum, autonum + 100); - autonum += 100; - } - - db.close(); - } - } - - private static void writeData(Table t1, Table t2, int start, int end) - throws Exception - { - for(int i = start; i < end; ++i) { - t1.addRow(null, "rowdata-" + i + DatabaseTest.createString(100)); - t2.addRow(null, "rowdata-" + i + DatabaseTest.createString(100)); - } - - Cursor c1 = t1.newCursor().setIndex(t1.getPrimaryKeyIndex()) - .toCursor(); - Cursor c2 = t2.newCursor().setIndex(t2.getPrimaryKeyIndex()) - .toCursor(); - - Iterator<? extends Map<String,Object>> i1 = c1.iterator(); - Iterator<? extends Map<String,Object>> i2 = c2.newIterable().reverse().iterator(); - - int t1rows = 0; - int t2rows = 0; - while(i1.hasNext() || i2.hasNext()) { - if(i1.hasNext()) { - checkRow(i1.next()); - i1.remove(); - ++t1rows; - } - if(i2.hasNext()) { - checkRow(i2.next()); - i2.remove(); - ++t2rows; - } - } - - assertEquals(100, t1rows); - assertEquals(100, t2rows); - } - - private static void checkRow(Map<String,Object> row) - { - int id = (Integer)row.get("id"); - String value = (String)row.get("data"); - String valuePrefix = "rowdata-" + id; - assertTrue(value.startsWith(valuePrefix)); - assertEquals(valuePrefix.length() + 100, value.length()); - } - - private static void encodeFile(File dbFile, int pageSize, boolean simple) - throws Exception - { - long dbLen = dbFile.length(); - FileChannel fileChannel = new RandomAccessFile(dbFile, "rw").getChannel(); - ByteBuffer bb = ByteBuffer.allocate(pageSize) - .order(PageChannel.DEFAULT_BYTE_ORDER); - for(long offset = pageSize; offset < dbLen; offset += pageSize) { - - bb.clear(); - fileChannel.read(bb, offset); - - int pageNumber = (int)(offset / pageSize); - if(simple) { - simpleEncode(bb.array(), bb.array(), pageNumber, 0, pageSize); - } else { - fullEncode(bb.array(), bb.array(), pageNumber); - } - - bb.rewind(); - fileChannel.write(bb, offset); - } - fileChannel.close(); - } - - private static void simpleEncode(byte[] inBuffer, byte[] outBuffer, - int pageNumber, int offset, int limit) { - for(int i = offset; i < limit; ++i) { - int mask = (i + pageNumber) % 256; - outBuffer[i] = (byte)(inBuffer[i] ^ mask); - } - } - - private static void simpleDecode(byte[] inBuffer, byte[] outBuffer, - int pageNumber) { - simpleEncode(inBuffer, outBuffer, pageNumber, 0, inBuffer.length); - } - - private static void fullEncode(byte[] inBuffer, byte[] outBuffer, - int pageNumber) { - int accum = 0; - for(int i = 0; i < inBuffer.length; ++i) { - int mask = (i + pageNumber + accum) % 256; - accum += inBuffer[i]; - outBuffer[i] = (byte)(inBuffer[i] ^ mask); - } - } - - private static void fullDecode(byte[] inBuffer, byte[] outBuffer, - int pageNumber) { - int accum = 0; - for(int i = 0; i < inBuffer.length; ++i) { - int mask = (i + pageNumber + accum) % 256; - outBuffer[i] = (byte)(inBuffer[i] ^ mask); - accum += outBuffer[i]; - } - } - - private static final class SimpleCodecHandler implements CodecHandler - { - private final TempBufferHolder _bufH = TempBufferHolder.newHolder( - TempBufferHolder.Type.HARD, true); - private final PageChannel _channel; - - private SimpleCodecHandler(PageChannel channel) { - _channel = channel; - } - - public boolean canEncodePartialPage() { - return true; - } - - public boolean canDecodeInline() { - return true; - } - - public void decodePage(ByteBuffer inPage, ByteBuffer outPage, - int pageNumber) - throws IOException - { - byte[] arr = inPage.array(); - simpleDecode(arr, arr, pageNumber); - } - - public ByteBuffer encodePage(ByteBuffer page, int pageNumber, - int pageOffset) - throws IOException - { - ByteBuffer bb = _bufH.getPageBuffer(_channel); - bb.clear(); - simpleEncode(page.array(), bb.array(), pageNumber, pageOffset, - page.limit()); - return bb; - } - } - - private static final class FullCodecHandler implements CodecHandler - { - private final TempBufferHolder _bufH = TempBufferHolder.newHolder( - TempBufferHolder.Type.HARD, true); - private final PageChannel _channel; - - private FullCodecHandler(PageChannel channel) { - _channel = channel; - } - - public boolean canEncodePartialPage() { - return false; - } - - public boolean canDecodeInline() { - return true; - } - - public void decodePage(ByteBuffer inPage, ByteBuffer outPage, - int pageNumber) - throws IOException - { - byte[] arr = inPage.array(); - fullDecode(arr, arr, pageNumber); - } - - public ByteBuffer encodePage(ByteBuffer page, int pageNumber, - int pageOffset) - throws IOException - { - assertEquals(0, pageOffset); - assertEquals(_channel.getFormat().PAGE_SIZE, page.limit()); - - ByteBuffer bb = _bufH.getPageBuffer(_channel); - bb.clear(); - fullEncode(page.array(), bb.array(), pageNumber); - return bb; - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/impl/FKEnforcerTest.java b/test/src/java/com/healthmarketscience/jackcess/impl/FKEnforcerTest.java deleted file mode 100644 index 7ea3123..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/impl/FKEnforcerTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* -Copyright (c) 2012 James Ahlborn - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA -*/ - -package com.healthmarketscience.jackcess.impl; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.healthmarketscience.jackcess.Column; -import com.healthmarketscience.jackcess.Cursor; -import com.healthmarketscience.jackcess.CursorBuilder; -import com.healthmarketscience.jackcess.Database; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.Row; -import com.healthmarketscience.jackcess.Table; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import junit.framework.TestCase; - -/** - * - * @author James Ahlborn - */ -public class FKEnforcerTest extends TestCase -{ - - public FKEnforcerTest(String name) throws Exception { - super(name); - } - - public void testNoEnforceForeignKeys() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX)) { - - Database db = openCopy(testDB); - db.setEnforceForeignKeys(false); - Table t1 = db.getTable("Table1"); - Table t2 = db.getTable("Table2"); - Table t3 = db.getTable("Table3"); - - t1.addRow(20, 0, 20, "some data", 20); - - Cursor c = CursorBuilder.createCursor(t2); - c.moveToNextRow(); - c.updateCurrentRow(30, "foo30"); - - c = CursorBuilder.createCursor(t3); - c.moveToNextRow(); - c.deleteCurrentRow(); - - db.close(); - } - - } - - public void testEnforceForeignKeys() throws Exception { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX)) { - - Database db = openCopy(testDB); - Table t1 = db.getTable("Table1"); - Table t2 = db.getTable("Table2"); - Table t3 = db.getTable("Table3"); - - try { - t1.addRow(20, 0, 20, "some data", 20); - fail("IOException should have been thrown"); - } catch(IOException ignored) { - // success - assertTrue(ignored.getMessage().contains("Table1[otherfk2]")); - } - - try { - Cursor c = CursorBuilder.createCursor(t2); - c.moveToNextRow(); - c.updateCurrentRow(30, "foo30"); - fail("IOException should have been thrown"); - } catch(IOException ignored) { - // success - assertTrue(ignored.getMessage().contains("Table2[id]")); - } - - try { - Cursor c = CursorBuilder.createCursor(t3); - c.moveToNextRow(); - c.deleteCurrentRow(); - fail("IOException should have been thrown"); - } catch(IOException ignored) { - // success - assertTrue(ignored.getMessage().contains("Table3[id]")); - } - - Cursor c = CursorBuilder.createCursor(t3); - Column col = t3.getColumn("id"); - for(Map<String,Object> row : c) { - int id = (Integer)row.get("id"); - id += 20; - c.setCurrentRowValue(col, id); - } - - List<? extends Map<String, Object>> expectedRows = - createExpectedTable( - createT1Row(0, 0, 30, "baz0", 0), - createT1Row(1, 1, 31, "baz11", 0), - createT1Row(2, 1, 31, "baz11-2", 0), - createT1Row(3, 2, 33, "baz13", 0)); - - assertTable(expectedRows, t1); - - c = CursorBuilder.createCursor(t2); - for(Iterator<?> iter = c.iterator(); iter.hasNext(); ) { - iter.next(); - iter.remove(); - } - - assertEquals(0, t1.getRowCount()); - - db.close(); - } - - } - - private static Row createT1Row( - int id1, int fk1, int fk2, String data, int fk3) - { - return createExpectedRow("id", id1, "otherfk1", fk1, "otherfk2", fk2, - "data", data, "otherfk3", fk3); - } -} diff --git a/test/src/java/com/healthmarketscience/jackcess/impl/IndexCodesTest.java b/test/src/java/com/healthmarketscience/jackcess/impl/IndexCodesTest.java deleted file mode 100644 index 62565ac..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/impl/IndexCodesTest.java +++ /dev/null @@ -1,798 +0,0 @@ -/* -Copyright (c) 2008 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess.impl; - -import java.io.File; -import java.lang.reflect.Field; -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.healthmarketscience.jackcess.ColumnBuilder; -import com.healthmarketscience.jackcess.Cursor; -import com.healthmarketscience.jackcess.CursorBuilder; -import com.healthmarketscience.jackcess.DataType; -import com.healthmarketscience.jackcess.Database; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.Index; -import com.healthmarketscience.jackcess.Table; -import com.healthmarketscience.jackcess.TableBuilder; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import junit.framework.TestCase; - -/** - * @author James Ahlborn - */ -public class IndexCodesTest extends TestCase { - - private static final Map<Character,String> SPECIAL_CHARS = - new HashMap<Character,String>(); - static { - SPECIAL_CHARS.put('\b', "\\b"); - SPECIAL_CHARS.put('\t', "\\t"); - SPECIAL_CHARS.put('\n', "\\n"); - SPECIAL_CHARS.put('\f', "\\f"); - SPECIAL_CHARS.put('\r', "\\r"); - SPECIAL_CHARS.put('\"', "\\\""); - SPECIAL_CHARS.put('\'', "\\'"); - SPECIAL_CHARS.put('\\', "\\\\"); - } - - public IndexCodesTest(String name) throws Exception { - super(name); - } - - public void testIndexCodes() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX_CODES)) { - Database db = openMem(testDB); - - for(Table t : db) { - for(Index index : t.getIndexes()) { - // System.out.println("Checking " + t.getName() + "." + index.getName()); - checkIndexEntries(testDB, t, index); - } - } - - db.close(); - } - } - - private static void checkIndexEntries(final TestDB testDB, Table t, Index index) throws Exception - { -// index.initialize(); -// System.out.println("Ind " + index); - - Cursor cursor = CursorBuilder.createCursor(index); - while(cursor.moveToNextRow()) { - - Map<String,Object> row = cursor.getCurrentRow(); - Cursor.Position curPos = cursor.getSavepoint().getCurrentPosition(); - boolean success = false; - try { - findRow(testDB, t, index, row, curPos); - success = true; - } finally { - if(!success) { - System.out.println("CurPos: " + curPos); - System.out.println("Value: " + row + ": " + - toUnicodeStr(row.get("data"))); - } - } - } - - } - - private static void findRow(final TestDB testDB, Table t, Index index, - Map<String,Object> expectedRow, - Cursor.Position expectedPos) - throws Exception - { - Object[] idxRow = ((IndexImpl)index).constructIndexRow(expectedRow); - Cursor cursor = CursorBuilder.createCursor(index, idxRow, idxRow); - - Cursor.Position startPos = cursor.getSavepoint().getCurrentPosition(); - - cursor.beforeFirst(); - while(cursor.moveToNextRow()) { - Map<String,Object> row = cursor.getCurrentRow(); - if(expectedRow.equals(row)) { - // verify that the entries are indeed equal - Cursor.Position curPos = cursor.getSavepoint().getCurrentPosition(); - assertEquals(entryToString(expectedPos), entryToString(curPos)); - return; - } - } - - // TODO long rows not handled completely yet in V2010 - // seems to truncate entry at 508 bytes with some trailing 2 byte seq - if(testDB.getExpectedFileFormat() == Database.FileFormat.V2010) { - String rowId = (String)expectedRow.get("name"); - String tName = t.getName(); - if(("Table11".equals(tName) || "Table11_desc".equals(tName)) && - ("row10".equals(rowId) || "row11".equals(rowId) || - "row12".equals(rowId))) { - System.out.println( - "TODO long rows not handled completely yet in V2010: " + tName + - ", " + rowId); - return; - } - } - - fail("testDB: " + testDB + ";\nCould not find expected row " + expectedRow + " starting at " + - entryToString(startPos)); - } - - - ////// - // - // The code below is for use in reverse engineering index entries. - // - ////// - - public void testNothing() throws Exception { - // keep this so build doesn't fail if other tests are disabled - } - - public void x_testCreateIsoFile() throws Exception - { - Database db = create(Database.FileFormat.V2000, true); - - Table t = new TableBuilder("test") - .addColumn(new ColumnBuilder("row", DataType.TEXT)) - .addColumn(new ColumnBuilder("data", DataType.TEXT)) - .toTable(db); - - for(int i = 0; i < 256; ++i) { - String str = "AA" + ((char)i) + "AA"; - t.addRow("row" + i, str); - } - - db.close(); - } - - public void x_testCreateAltIsoFile() throws Exception - { - Database db = openCopy(Database.FileFormat.V2000, new File("/tmp/test_ind.mdb"), true); - - Table t = db.getTable("Table1"); - - for(int i = 0; i < 256; ++i) { - String str = "AA" + ((char)i) + "AA"; - t.addRow("row" + i, str, - (byte)42 + i, (short)53 + i, 13 * i, - (6.7d / i), null, null, true); - } - - db.close(); - } - - public void x_testWriteAllCodesMdb() throws Exception - { - Database db = create(Database.FileFormat.V2000, true); - -// Table t = new TableBuilder("Table1") -// .addColumn(new ColumnBuilder("key", DataType.TEXT)) -// .addColumn(new ColumnBuilder("data", DataType.TEXT)) -// .toTable(db); - -// for(int i = 0; i <= 0xFFFF; ++i) { -// // skip non-char chars -// char c = (char)i; -// if(Character.isHighSurrogate(c) || Character.isLowSurrogate(c)) { -// continue; -// } -// String key = toUnicodeStr(c); -// String str = "AA" + c + "AA"; -// t.addRow(key, str); -// } - - Table t = new TableBuilder("Table5") - .addColumn(new ColumnBuilder("name", DataType.TEXT)) - .addColumn(new ColumnBuilder("data", DataType.TEXT)) - .toTable(db); - - char c = (char)0x3041; // crazy 7F 02 ... A0 - char c2 = (char)0x30A2; // crazy 7F 02 ... - char c3 = (char)0x2045; // inat 27 ... 1C - char c4 = (char)0x3043; // crazy 7F 03 ... A0 - char c5 = (char)0x3046; // crazy 7F 04 ... - char c6 = (char)0x30F6; // crazy 7F 0D ... A0 - char c7 = (char)0x3099; // unprint 03 - char c8 = (char)0x0041; // A - char c9 = (char)0x002D; // - (unprint) - char c10 = (char)0x20E1; // unprint F2 - char c11 = (char)0x309A; // unprint 04 - char c12 = (char)0x01C4; // (long extra) - char c13 = (char)0x005F; // _ (long inline) - char c14 = (char)0xFFFE; // removed - - char[] cs = new char[]{c7, c8, c3, c12, c13, c14, c, c2, c9}; - addCombos(t, 0, "", cs, 5); - -// t = new TableBuilder("Table2") -// .addColumn(new ColumnBuilder("data", DataType.TEXT)) -// .toTable(db); - -// writeChars(0x0000, t); - -// t = new TableBuilder("Table3") -// .addColumn(new ColumnBuilder("data", DataType.TEXT)) -// .toTable(db); - -// writeChars(0x0400, t); - - - db.close(); - } - - public void x_testReadAllCodesMdb() throws Exception - { -// Database db = openCopy(new File("/data2/jackcess_test/testAllIndexCodes.mdb")); -// Database db = openCopy(new File("/data2/jackcess_test/testAllIndexCodes_orig.mdb")); -// Database db = openCopy(new File("/data2/jackcess_test/testSomeMoreCodes.mdb")); - Database db = openCopy(Database.FileFormat.V2000, new File("/data2/jackcess_test/testStillMoreCodes.mdb")); - Table t = db.getTable("Table5"); - - Index ind = t.getIndexes().iterator().next(); - ((IndexImpl)ind).initialize(); - - System.out.println("Ind " + ind); - - Cursor cursor = CursorBuilder.createCursor(ind); - while(cursor.moveToNextRow()) { - System.out.println("======="); - String entryStr = - entryToString(cursor.getSavepoint().getCurrentPosition()); - System.out.println("Entry Bytes: " + entryStr); - System.out.println("Value: " + cursor.getCurrentRow() + "; " + - toUnicodeStr(cursor.getCurrentRow().get("data"))); - } - - db.close(); - } - - private int addCombos(Table t, int rowNum, String s, char[] cs, int len) - throws Exception - { - if(s.length() >= len) { - return rowNum; - } - - for(int i = 0; i < cs.length; ++i) { - String name = "row" + (rowNum++); - String ss = s + cs[i]; - t.addRow(name, ss); - rowNum = addCombos(t, rowNum, ss, cs, len); - } - - return rowNum; - } - - private void writeChars(int hibyte, Table t) throws Exception - { - char other = (char)(hibyte | 0x41); - for(int i = 0; i < 0xFF; ++i) { - char c = (char)(hibyte | i); - String str = "" + other + c + other; - t.addRow(str); - } - } - - public void x_testReadIsoMdb() throws Exception - { -// Database db = open(new File("/tmp/test_ind.mdb")); -// Database db = open(new File("/tmp/test_ind2.mdb")); - Database db = open(Database.FileFormat.V2000, new File("/tmp/test_ind3.mdb")); -// Database db = open(new File("/tmp/test_ind4.mdb")); - - Table t = db.getTable("Table1"); - Index index = t.getIndex("B"); - ((IndexImpl)index).initialize(); - System.out.println("Ind " + index); - - Cursor cursor = CursorBuilder.createCursor(index); - while(cursor.moveToNextRow()) { - System.out.println("======="); - System.out.println("Savepoint: " + cursor.getSavepoint()); - System.out.println("Value: " + cursor.getCurrentRow()); - } - - db.close(); - } - - public void x_testReverseIsoMdb2010() throws Exception - { - Database db = open(Database.FileFormat.V2010, new File("/data2/jackcess_test/testAllIndexCodes3_2010.accdb")); - - Table t = db.getTable("Table1"); - Index index = t.getIndexes().iterator().next(); - ((IndexImpl)index).initialize(); - System.out.println("Ind " + index); - - Pattern inlinePat = Pattern.compile("7F 0E 02 0E 02 (.*)0E 02 0E 02 01 00"); - Pattern unprintPat = Pattern.compile("01 01 01 80 (.+) 06 (.+) 00"); - Pattern unprint2Pat = Pattern.compile("0E 02 0E 02 0E 02 0E 02 01 02 (.+) 00"); - Pattern inatPat = Pattern.compile("7F 0E 02 0E 02 (.*)0E 02 0E 02 01 02 02 (.+) 00"); - Pattern inat2Pat = Pattern.compile("7F 0E 02 0E 02 (.*)0E 02 0E 02 01 (02 02 (.+))?01 01 (.*)FF 02 80 FF 80 00"); - - Map<Character,String[]> inlineCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> unprintCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> unprint2Codes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inatInlineCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inatExtraCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inat2Codes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inat2ExtraCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inat2CrazyCodes = new TreeMap<Character,String[]>(); - - - Cursor cursor = CursorBuilder.createCursor(index); - while(cursor.moveToNextRow()) { -// System.out.println("======="); -// System.out.println("Savepoint: " + cursor.getSavepoint()); -// System.out.println("Value: " + cursor.getCurrentRow()); - Cursor.Savepoint savepoint = cursor.getSavepoint(); - String entryStr = entryToString(savepoint.getCurrentPosition()); - - Map<String,Object> row = cursor.getCurrentRow(); - String value = (String)row.get("data"); - String key = (String)row.get("key"); - char c = value.charAt(2); - - System.out.println("======="); - System.out.println("RowId: " + - savepoint.getCurrentPosition().getRowId()); - System.out.println("Entry: " + entryStr); -// System.out.println("Row: " + row); - System.out.println("Value: (" + key + ")" + value); - System.out.println("Char: " + c + ", " + (int)c + ", " + - toUnicodeStr(c)); - - String type = null; - if(entryStr.endsWith("01 00")) { - - // handle inline codes - type = "INLINE"; - Matcher m = inlinePat.matcher(entryStr); - m.find(); - handleInlineEntry(m.group(1), c, inlineCodes); - - } else if(entryStr.contains("01 01 01 80")) { - - // handle most unprintable codes - type = "UNPRINTABLE"; - Matcher m = unprintPat.matcher(entryStr); - m.find(); - handleUnprintableEntry(m.group(2), c, unprintCodes); - - } else if(entryStr.contains("01 02 02") && - !entryStr.contains("FF 02 80 FF 80")) { - - // handle chars w/ symbols - type = "CHAR_WITH_SYMBOL"; - Matcher m = inatPat.matcher(entryStr); - m.find(); - handleInternationalEntry(m.group(1), m.group(2), c, - inatInlineCodes, inatExtraCodes); - - } else if(entryStr.contains("0E 02 0E 02 0E 02 0E 02 01 02")) { - - // handle chars w/ symbols - type = "UNPRINTABLE_2"; - Matcher m = unprint2Pat.matcher(entryStr); - m.find(); - handleUnprintable2Entry(m.group(1), c, unprint2Codes); - - } else if(entryStr.contains("FF 02 80 FF 80")) { - - type = "CRAZY_INAT"; - Matcher m = inat2Pat.matcher(entryStr); - m.find(); - handleInternational2Entry(m.group(1), m.group(3), m.group(4), c, - inat2Codes, inat2ExtraCodes, - inat2CrazyCodes); - - } else { - - // throw new RuntimeException("unhandled " + entryStr); - System.out.println("unhandled " + entryStr); - } - - System.out.println("Type: " + type); - } - - System.out.println("\n***CODES"); - for(int i = 0; i <= 0xFFFF; ++i) { - - if(i == 256) { - System.out.println("\n***EXTENDED CODES"); - } - - // skip non-char chars - char c = (char)i; - if(Character.isHighSurrogate(c) || Character.isLowSurrogate(c)) { - continue; - } - - if(c == (char)0xFFFE) { - // this gets replaced with FFFD, treat it the same - c = (char)0xFFFD; - } - - Character cc = c; - String[] chars = inlineCodes.get(cc); - if(chars != null) { - if((chars.length == 1) && (chars[0].length() == 0)) { - System.out.println("X"); - } else { - System.out.println("S" + toByteString(chars)); - } - continue; - } - - chars = inatInlineCodes.get(cc); - if(chars != null) { - String[] extra = inatExtraCodes.get(cc); - System.out.println("I" + toByteString(chars) + "," + - toByteString(extra)); - continue; - } - - chars = unprintCodes.get(cc); - if(chars != null) { - System.out.println("U" + toByteString(chars)); - continue; - } - - chars = unprint2Codes.get(cc); - if(chars != null) { - if(chars.length > 1) { - throw new RuntimeException("long unprint codes"); - } - int val = Integer.parseInt(chars[0], 16) - 2; - String valStr = ByteUtil.toHexString(new byte[]{(byte)val}).trim(); - System.out.println("P" + valStr); - continue; - } - - chars = inat2Codes.get(cc); - if(chars != null) { - String [] crazyCodes = inat2CrazyCodes.get(cc); - String crazyCode = ""; - if(crazyCodes != null) { - if((crazyCodes.length != 1) || !"A0".equals(crazyCodes[0])) { - throw new RuntimeException("CC " + Arrays.asList(crazyCodes)); - } - crazyCode = "1"; - } - - String[] extra = inat2ExtraCodes.get(cc); - System.out.println("Z" + toByteString(chars) + "," + - toByteString(extra) + "," + - crazyCode); - continue; - } - - throw new RuntimeException("Unhandled char " + toUnicodeStr(c)); - } - System.out.println("\n***END CODES"); - - db.close(); - } - - public void x_testReverseIsoMdb() throws Exception - { - Database db = open(Database.FileFormat.V2000, new File("/data2/jackcess_test/testAllIndexCodes3.mdb")); - - Table t = db.getTable("Table1"); - Index index = t.getIndexes().iterator().next(); - ((IndexImpl)index).initialize(); - System.out.println("Ind " + index); - - Pattern inlinePat = Pattern.compile("7F 4A 4A (.*)4A 4A 01 00"); - Pattern unprintPat = Pattern.compile("01 01 01 80 (.+) 06 (.+) 00"); - Pattern unprint2Pat = Pattern.compile("4A 4A 4A 4A 01 02 (.+) 00"); - Pattern inatPat = Pattern.compile("7F 4A 4A (.*)4A 4A 01 02 02 (.+) 00"); - Pattern inat2Pat = Pattern.compile("7F 4A 4A (.*)4A 4A 01 (02 02 (.+))?01 01 (.*)FF 02 80 FF 80 00"); - - Map<Character,String[]> inlineCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> unprintCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> unprint2Codes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inatInlineCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inatExtraCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inat2Codes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inat2ExtraCodes = new TreeMap<Character,String[]>(); - Map<Character,String[]> inat2CrazyCodes = new TreeMap<Character,String[]>(); - - - Cursor cursor = CursorBuilder.createCursor(index); - while(cursor.moveToNextRow()) { -// System.out.println("======="); -// System.out.println("Savepoint: " + cursor.getSavepoint()); -// System.out.println("Value: " + cursor.getCurrentRow()); - Cursor.Savepoint savepoint = cursor.getSavepoint(); - String entryStr = entryToString(savepoint.getCurrentPosition()); - - Map<String,Object> row = cursor.getCurrentRow(); - String value = (String)row.get("data"); - String key = (String)row.get("key"); - char c = value.charAt(2); - System.out.println("======="); - System.out.println("RowId: " + - savepoint.getCurrentPosition().getRowId()); - System.out.println("Entry: " + entryStr); -// System.out.println("Row: " + row); - System.out.println("Value: (" + key + ")" + value); - System.out.println("Char: " + c + ", " + (int)c + ", " + - toUnicodeStr(c)); - - String type = null; - if(entryStr.endsWith("01 00")) { - - // handle inline codes - type = "INLINE"; - Matcher m = inlinePat.matcher(entryStr); - m.find(); - handleInlineEntry(m.group(1), c, inlineCodes); - - } else if(entryStr.contains("01 01 01 80")) { - - // handle most unprintable codes - type = "UNPRINTABLE"; - Matcher m = unprintPat.matcher(entryStr); - m.find(); - handleUnprintableEntry(m.group(2), c, unprintCodes); - - } else if(entryStr.contains("01 02 02") && - !entryStr.contains("FF 02 80 FF 80")) { - - // handle chars w/ symbols - type = "CHAR_WITH_SYMBOL"; - Matcher m = inatPat.matcher(entryStr); - m.find(); - handleInternationalEntry(m.group(1), m.group(2), c, - inatInlineCodes, inatExtraCodes); - - } else if(entryStr.contains("4A 4A 4A 4A 01 02")) { - - // handle chars w/ symbols - type = "UNPRINTABLE_2"; - Matcher m = unprint2Pat.matcher(entryStr); - m.find(); - handleUnprintable2Entry(m.group(1), c, unprint2Codes); - - } else if(entryStr.contains("FF 02 80 FF 80")) { - - type = "CRAZY_INAT"; - Matcher m = inat2Pat.matcher(entryStr); - m.find(); - handleInternational2Entry(m.group(1), m.group(3), m.group(4), c, - inat2Codes, inat2ExtraCodes, - inat2CrazyCodes); - - } else { - - throw new RuntimeException("unhandled " + entryStr); - } - - System.out.println("Type: " + type); - } - - System.out.println("\n***CODES"); - for(int i = 0; i <= 0xFFFF; ++i) { - - if(i == 256) { - System.out.println("\n***EXTENDED CODES"); - } - - // skip non-char chars - char c = (char)i; - if(Character.isHighSurrogate(c) || Character.isLowSurrogate(c)) { - continue; - } - - if(c == (char)0xFFFE) { - // this gets replaced with FFFD, treat it the same - c = (char)0xFFFD; - } - - Character cc = c; - String[] chars = inlineCodes.get(cc); - if(chars != null) { - if((chars.length == 1) && (chars[0].length() == 0)) { - System.out.println("X"); - } else { - System.out.println("S" + toByteString(chars)); - } - continue; - } - - chars = inatInlineCodes.get(cc); - if(chars != null) { - String[] extra = inatExtraCodes.get(cc); - System.out.println("I" + toByteString(chars) + "," + - toByteString(extra)); - continue; - } - - chars = unprintCodes.get(cc); - if(chars != null) { - System.out.println("U" + toByteString(chars)); - continue; - } - - chars = unprint2Codes.get(cc); - if(chars != null) { - if(chars.length > 1) { - throw new RuntimeException("long unprint codes"); - } - int val = Integer.parseInt(chars[0], 16) - 2; - String valStr = ByteUtil.toHexString(new byte[]{(byte)val}).trim(); - System.out.println("P" + valStr); - continue; - } - - chars = inat2Codes.get(cc); - if(chars != null) { - String [] crazyCodes = inat2CrazyCodes.get(cc); - String crazyCode = ""; - if(crazyCodes != null) { - if((crazyCodes.length != 1) || !"A0".equals(crazyCodes[0])) { - throw new RuntimeException("CC " + Arrays.asList(crazyCodes)); - } - crazyCode = "1"; - } - - String[] extra = inat2ExtraCodes.get(cc); - System.out.println("Z" + toByteString(chars) + "," + - toByteString(extra) + "," + - crazyCode); - continue; - } - - throw new RuntimeException("Unhandled char " + toUnicodeStr(c)); - } - System.out.println("\n***END CODES"); - - db.close(); - } - - private static String toByteString(String[] chars) - { - String str = join(chars, "", ""); - if(str.length() > 0 && str.charAt(0) == '0') { - str = str.substring(1); - } - return str; - } - - private static void handleInlineEntry( - String entryCodes, char c, Map<Character,String[]> inlineCodes) - throws Exception - { - inlineCodes.put(c, entryCodes.trim().split(" ")); - } - - private static void handleUnprintableEntry( - String entryCodes, char c, Map<Character,String[]> unprintCodes) - throws Exception - { - unprintCodes.put(c, entryCodes.trim().split(" ")); - } - - private static void handleUnprintable2Entry( - String entryCodes, char c, Map<Character,String[]> unprintCodes) - throws Exception - { - unprintCodes.put(c, entryCodes.trim().split(" ")); - } - - private static void handleInternationalEntry( - String inlineCodes, String entryCodes, char c, - Map<Character,String[]> inatInlineCodes, - Map<Character,String[]> inatExtraCodes) - throws Exception - { - inatInlineCodes.put(c, inlineCodes.trim().split(" ")); - inatExtraCodes.put(c, entryCodes.trim().split(" ")); - } - - private static void handleInternational2Entry( - String inlineCodes, String entryCodes, String crazyCodes, char c, - Map<Character,String[]> inatInlineCodes, - Map<Character,String[]> inatExtraCodes, - Map<Character,String[]> inatCrazyCodes) - throws Exception - { - inatInlineCodes.put(c, inlineCodes.trim().split(" ")); - if(entryCodes != null) { - inatExtraCodes.put(c, entryCodes.trim().split(" ")); - } - if((crazyCodes != null) && (crazyCodes.length() > 0)) { - inatCrazyCodes.put(c, crazyCodes.trim().split(" ")); - } - } - - private static String toUnicodeStr(Object obj) throws Exception { - StringBuilder sb = new StringBuilder(); - for(char c : obj.toString().toCharArray()) { - sb.append(toUnicodeStr(c)).append(" "); - } - return sb.toString(); - } - - private static String toUnicodeStr(char c) throws Exception { - String specialStr = SPECIAL_CHARS.get(c); - if(specialStr != null) { - return specialStr; - } - - String digits = Integer.toHexString(c).toUpperCase(); - while(digits.length() < 4) { - digits = "0" + digits; - } - return "\\u" + digits; - } - - private static String join(String[] strs, String joinStr, String prefixStr) { - if(strs == null) { - return ""; - } - StringBuilder builder = new StringBuilder(); - for(int i = 0; i < strs.length; ++i) { - if(strs[i].length() == 0) { - continue; - } - builder.append(prefixStr).append(strs[i]); - if(i < (strs.length - 1)) { - builder.append(joinStr); - } - } - return builder.toString(); - } - - public static String entryToString(Cursor.Position curPos) - throws Exception - { - Field eField = curPos.getClass().getDeclaredField("_entry"); - eField.setAccessible(true); - IndexData.Entry entry = (IndexData.Entry)eField.get(curPos); - Field ebField = entry.getClass().getDeclaredField("_entryBytes"); - ebField.setAccessible(true); - byte[] entryBytes = (byte[])ebField.get(entry); - - return ByteUtil.toHexString(ByteBuffer.wrap(entryBytes), - entryBytes.length) - .trim().replaceAll("\\p{Space}+", " "); - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/impl/JetFormatTest.java b/test/src/java/com/healthmarketscience/jackcess/impl/JetFormatTest.java deleted file mode 100644 index 962a6f0..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/impl/JetFormatTest.java +++ /dev/null @@ -1,243 +0,0 @@ -package com.healthmarketscience.jackcess.impl; - -import java.io.File; -import java.io.IOException; -import java.nio.channels.FileChannel; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; - -import com.healthmarketscience.jackcess.Database; -import static com.healthmarketscience.jackcess.Database.*; -import com.healthmarketscience.jackcess.DatabaseBuilder; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import junit.framework.TestCase; - - -/** - * @author Dan Rollo - * Date: Mar 5, 2010 - * Time: 12:44:21 PM - */ -public class JetFormatTest extends TestCase { - - public static final File DIR_TEST_DATA = new File("test/data"); - - /** - * Defines known valid db test file base names. - */ - public static enum Basename { - - BIG_INDEX("bigIndexTest"), - COMP_INDEX("compIndexTest"), - DEL_COL("delColTest"), - DEL("delTest"), - FIXED_NUMERIC("fixedNumericTest"), - FIXED_TEXT("fixedTextTest"), - INDEX_CURSOR("indexCursorTest"), - INDEX("indexTest"), - OVERFLOW("overflowTest"), - QUERY("queryTest"), - TEST("test"), - TEST2("test2"), - INDEX_CODES("testIndexCodes"), - INDEX_PROPERTIES("testIndexProperties"), - PROMOTION("testPromotion"), - COMPLEX("complexDataTest"), - UNSUPPORTED("unsupportedFieldsTest"), - LINKED("linkerTest"); - - private final String _basename; - - Basename(String fileBasename) { - _basename = fileBasename; - } - - @Override - public String toString() { return _basename; } - } - - /** Defines currently supported db file formats. (can be modified at - runtime via the system property - "com.healthmarketscience.jackcess.testFormats") */ - public final static FileFormat[] SUPPORTED_FILEFORMATS; - public final static FileFormat[] SUPPORTED_FILEFORMATS_FOR_READ; - - static { - String testFormatStr = System.getProperty("com.healthmarketscience.jackcess.testFormats"); - Set<FileFormat> testFormats = EnumSet.allOf(FileFormat.class); - if((testFormatStr != null) && (testFormatStr.length() > 0)) { - testFormats.clear(); - for(String tmp : testFormatStr.split(",")) { - testFormats.add(FileFormat.valueOf(tmp.toUpperCase())); - } - } - - List<FileFormat> supported = new ArrayList<FileFormat>(); - List<FileFormat> supportedForRead = new ArrayList<FileFormat>(); - for(FileFormat ff : FileFormat.values()) { - if(!testFormats.contains(ff)) { - continue; - } - supportedForRead.add(ff); - if(DatabaseImpl.getFileFormatDetails(ff).getFormat().READ_ONLY || - (ff == FileFormat.MSISAM)) { - continue; - } - supported.add(ff); - } - - SUPPORTED_FILEFORMATS = supported.toArray(new FileFormat[0]); - SUPPORTED_FILEFORMATS_FOR_READ = - supportedForRead.toArray(new FileFormat[0]); - } - - /** - * Defines known valid test database files, and their jet format version. - */ - public static final class TestDB { - - private final File dbFile; - private final FileFormat expectedFileFormat; - - private TestDB(File databaseFile, - FileFormat expectedDBFileFormat) { - - dbFile = databaseFile; - expectedFileFormat = expectedDBFileFormat; - } - - public final File getFile() { return dbFile; } - - public final FileFormat getExpectedFileFormat() { - return expectedFileFormat; - } - - public final JetFormat getExpectedFormat() { - return DatabaseImpl.getFileFormatDetails(expectedFileFormat).getFormat(); - } - - @Override - public final String toString() { - return "dbFile: " + dbFile.getAbsolutePath() - + "; expectedFileFormat: " + expectedFileFormat; - } - - public static List<TestDB> getSupportedForBasename(Basename basename) { - return getSupportedForBasename(basename, false); - } - - public static List<TestDB> getSupportedForBasename(Basename basename, - boolean readOnly) { - - List<TestDB> supportedTestDBs = new ArrayList<TestDB>(); - for (FileFormat fileFormat : - (readOnly ? SUPPORTED_FILEFORMATS_FOR_READ : - SUPPORTED_FILEFORMATS)) { - File testFile = getFileForBasename(basename, fileFormat); - if(!testFile.exists()) { - continue; - } - - // verify that the db is the file format expected - try { - Database db = new DatabaseBuilder(testFile).setReadOnly(true).open(); - FileFormat dbFileFormat = db.getFileFormat(); - db.close(); - if(dbFileFormat != fileFormat) { - throw new IllegalStateException("Expected " + fileFormat + - " was " + dbFileFormat); - } - } catch(Exception e) { - throw new RuntimeException(e); - } - - supportedTestDBs.add(new TestDB(testFile, fileFormat)); - } - return supportedTestDBs; - } - - private static File getFileForBasename( - Basename basename, FileFormat fileFormat) { - - return new File(DIR_TEST_DATA, - fileFormat.name() + File.separator + - basename + fileFormat.name() + - fileFormat.getFileExtension()); - } - } - - public static final List<TestDB> SUPPORTED_DBS_TEST = - TestDB.getSupportedForBasename(Basename.TEST); - public static final List<TestDB> SUPPORTED_DBS_TEST_FOR_READ = - TestDB.getSupportedForBasename(Basename.TEST, true); - - - public void testGetFormat() throws Exception { - try { - JetFormat.getFormat(null); - fail("npe"); - } catch (NullPointerException e) { - // success - } - - for (final TestDB testDB : SUPPORTED_DBS_TEST_FOR_READ) { - - final FileChannel channel = DatabaseImpl.openChannel(testDB.dbFile, false); - try { - - JetFormat fmtActual = JetFormat.getFormat(channel); - assertEquals("Unexpected JetFormat for dbFile: " + - testDB.dbFile.getAbsolutePath(), - testDB.getExpectedFormat(), fmtActual); - - } finally { - channel.close(); - } - - } - } - - public void testReadOnlyFormat() throws Exception { - - for (final TestDB testDB : SUPPORTED_DBS_TEST_FOR_READ) { - - Database db = null; - IOException failure = null; - try { - db = openCopy(testDB); - } catch(IOException e) { - failure = e; - } finally { - if(db != null) { - db.close(); - } - } - - if(!testDB.getExpectedFormat().READ_ONLY) { - assertNull(failure); - } else { - assertTrue(failure.getMessage().contains("does not support writing")); - } - - } - } - - public void testFileFormat() throws Exception { - - for (final TestDB testDB : SUPPORTED_DBS_TEST_FOR_READ) { - - Database db = null; - try { - db = open(testDB); - assertEquals(testDB.getExpectedFileFormat(), db.getFileFormat()); - } finally { - if(db != null) { - db.close(); - } - } - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/impl/UsageMapTest.java b/test/src/java/com/healthmarketscience/jackcess/impl/UsageMapTest.java deleted file mode 100644 index aad1ddf..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/impl/UsageMapTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.healthmarketscience.jackcess.impl; - -import java.io.File; -import java.io.IOException; - -import com.healthmarketscience.jackcess.Database; -import com.healthmarketscience.jackcess.DatabaseBuilder; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import junit.framework.TestCase; - -/** - * @author Dan Rollo - * Date: Mar 5, 2010 - * Time: 2:21:22 PM - */ -public final class UsageMapTest extends TestCase { - - public void testRead() throws Exception { - for (final TestDB testDB : SUPPORTED_DBS_TEST) { - final int expectedFirstPage; - final int expectedLastPage; - final Database.FileFormat expectedFileFormat = testDB.getExpectedFileFormat(); - if (Database.FileFormat.V2000.equals(expectedFileFormat)) { - expectedFirstPage = 743; - expectedLastPage = 767; - } else if (Database.FileFormat.V2003.equals(expectedFileFormat)) { - expectedFirstPage = 16; - expectedLastPage = 799; - } else if (Database.FileFormat.V2007.equals(expectedFileFormat)) { - expectedFirstPage = 94; - expectedLastPage = 511; - } else if (Database.FileFormat.V2010.equals(expectedFileFormat)) { - expectedFirstPage = 109; - expectedLastPage = 511; - } else { - throw new IllegalAccessException("Unknown file format: " + expectedFileFormat); - } - checkUsageMapRead(testDB.getFile(), expectedFirstPage, expectedLastPage); - } - } - - private static void checkUsageMapRead(final File dbFile, - final int expectedFirstPage, final int expectedLastPage) - throws IOException { - - final Database db = DatabaseBuilder.open(dbFile); - final UsageMap usageMap = UsageMap.read((DatabaseImpl)db, - PageChannel.PAGE_GLOBAL_USAGE_MAP, - PageChannel.ROW_GLOBAL_USAGE_MAP, - true); - assertEquals("Unexpected FirstPageNumber.", expectedFirstPage, usageMap.getFirstPageNumber()); - assertEquals("Unexpected LastPageNumber.", expectedLastPage, usageMap.getLastPageNumber()); - } -} diff --git a/test/src/java/com/healthmarketscience/jackcess/impl/scsu/CompressMain.java b/test/src/java/com/healthmarketscience/jackcess/impl/scsu/CompressMain.java deleted file mode 100644 index 52b9e86..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/impl/scsu/CompressMain.java +++ /dev/null @@ -1,574 +0,0 @@ -package com.healthmarketscience.jackcess.impl.scsu; - -import java.io.*; -import java.util.*; - -/** - * This sample software accompanies Unicode Technical Report #6 and - * distributed as is by Unicode, Inc., subject to the following: - * - * Copyright 1996-1998 Unicode, Inc.. All Rights Reserved. - * - * Permission to use, copy, modify, and distribute this software - * without fee is hereby granted provided that this copyright notice - * appears in all copies. - * - * UNICODE, INC. MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE - * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING - * BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. - * UNICODE, INC., SHALL NOT BE LIABLE FOR ANY ERRORS OR OMISSIONS, AND - * SHALL NOT BE LIABLE FOR ANY DAMAGES, INCLUDING CONSEQUENTIAL AND - * INCIDENTAL DAMAGES, SUFFERED BY YOU AS A RESULT OF USING, MODIFYING - * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. - * - * @author Asmus Freytag - * - * @version 001 Dec 25 1996 - * @version 002 Jun 25 1997 - * @version 003 Jul 25 1997 - * @version 004 Aug 25 1997 - * @version 005 Sep 30 1998 - * - * Unicode and the Unicode logo are trademarks of Unicode, Inc., - * and are registered in some jurisdictions. - **/ - -/** - Class CompressMain - - A small commandline driver interface for the compression routines - Use the /? to get usage -*/ -public class CompressMain -{ - static void usage() - { - System.err.println("java CompressMain /? : this usage information\n"); - System.err.println("java CompressMain /random : random test\n"); - System.err.println("java CompressMain /suite : suite test\n"); - System.err.println("java CompressMain /suite <file> : file test (file data may include \\uXXXX)\n"); - System.err.println("java CompressMain <string> : string test (string may include \\uXXXX)\n"); - System.err.println("java CompressMain /roundtrip <file>: check Unicode file for roundtrip\n"); - System.err.println("java CompressMain /compress <file> : compresses Unicode files (no \\uXXXX)\n"); - System.err.println("java CompressMain /expand <file> : expands into Unicode files\n"); - System.err.println("java CompressMain /byteswap <files>: swaps byte order of Unicode files\n"); - System.err.println("java CompressMain /display <files> : like expand, but creates a dump instead\n"); - System.err.println("java CompressMain /parse <files> : parses \\uXXXX into binary Unicode\n"); - } - - static void analyze(String text, int inlength, String result, int outlength) - { - boolean fSuccess = text.equals(result); - Debug.out(fSuccess ? "Round trip OK" : "Round trip FAILED"); - if (!fSuccess && result != null) - { - int iLim = Math.min(text.length(), result.length()); - for (int i = 0; i < iLim; i++) - { - if (text.charAt(i) != result.charAt(i)) - { - Debug.out("First Mismatch at "+ i +"=", result.charAt(i) ); - Debug.out("Original character "+ i +"=", text.charAt(i) ); - break; - } - } - } - else - { - Debug.out("Compressed: "+inlength+" chars to "+outlength+" bytes."); - Debug.out(" Ratio: "+(outlength == 0 ? 0 :(outlength * 50 / inlength))+"%."); - } - } - - static void test2(String text) - { - byte bytes[] = null; - String result = null; - Debug.out("SCSU:\n"); - Compress compressor = new Compress(); - try - { - bytes = compressor.compress(text); - Expand display = new Expand(); - result = display.expand(bytes); - Debug.out("Input: ", text.toCharArray()); - Debug.out("Result: ", result.toCharArray()); - Debug.out(""); - Expand expander = new Expand(); - result = expander.expand(bytes); - } - catch (Exception e) - { - System.out.println(e); - } - int inlength = compressor.charsRead(); - int outlength = compressor.bytesWritten(); - analyze(text, inlength, result, outlength); - } - - static void test(String text) throws Exception - { - test(text, false); - } - - static void test(String text, boolean shouldFail) - throws Exception - { - // Create an instance of the compressor - Compress compressor = new Compress(); - - byte [] bytes = null; - String result = null; - Exception failure = null; - try { - // perform compression - bytes = compressor.compress(text); - } - catch(Exception e) - { - failure = e; - } - - if(shouldFail) { - if(failure == null) { - throw new RuntimeException("Did not fail"); - } - return; - } - - if(failure != null) { - throw failure; - } - - Expand expander = new Expand(); - // perform expansion - result = expander.expand(bytes); - - // analyze the results - int inlength = compressor.charsRead(); - int outlength = compressor.bytesWritten(); - analyze(text, inlength, result, outlength); - - } - - public static void display(byte [] input) - { - try - { - Expand expand = new Expand(); - String text = expand.expand(input); - Debug.out(text.toCharArray()); - } - catch (Exception e) - { - System.out.println(e); - } - } - - public static String parse(String input) - { - StringTokenizer st = new StringTokenizer(input, "\\", true); - Debug.out("Input: ", input); - - StringBuffer sb = new StringBuffer(); - - while(st.hasMoreTokens()) - { - String token = st.nextToken(); - Debug.out("Token: ", token); - if (token.charAt(0) == '\\' && token.length() == 1) - { - if(st.hasMoreTokens()) - { - token = st.nextToken(); - } - if(token.charAt(0) == 'u') - { - Debug.out("Token: "+ token+ " ", sb.toString()); - String hexnum; - if (token.length() > 5) - { - hexnum = token.substring(1,5); - token = token.substring(5); - } - else - { - hexnum = token.substring(1); - token = ""; - } - sb.append((char)Integer.parseInt(hexnum, 16)); - } - } - sb.append(token); - } - return sb.toString(); - } - - public static void randomTest(int nTest) - throws Exception - { - Random random = new Random(); - - for(int n=0; n < nTest; n++) - { - int iLen = (int) (20 * random.nextFloat()); - StringBuffer sb = new StringBuffer(iLen); - - for(int i = 0; i < iLen; i++) - { - sb.append((char) (0xFFFF * random.nextFloat())); - } - - test(sb.toString()); - } - } - - @SuppressWarnings("deprecation") - public static void fileTest(String name) - throws Exception - { - DataInputStream dis = new DataInputStream(new FileInputStream(name)); - - int iLine = 0; - - while(dis.available() != 0) - { - String line = dis.readLine(); - Debug.out("Line "+ iLine++ +" "+line); - test(parse(line), false ); //false);// initially no debug info - } - } - - public static void displayFile(String name) - throws IOException - { - DataInputStream dis = new DataInputStream(new FileInputStream(name)); - - byte bytes[] = new byte[dis.available()]; - dis.read(bytes); - display(bytes); - } - - public static void decodeTest(String name) - throws IOException - { - DataInputStream dis = new DataInputStream(new FileInputStream(name)); - - byte bytes[] = new byte[dis.available()]; - dis.read(bytes); - - Expand expand = new Expand(); - - char [] chars = null; - try - { - String text = expand.expand(bytes); - chars = text.toCharArray(); - } - catch (Exception e) - { - System.out.println(e); - } - int inlength = expand.bytesRead(); - int iDot = name.lastIndexOf('.'); - StringBuffer sb = new StringBuffer(name); - sb.setLength(iDot + 1); - sb.append("txt"); - String outName = sb.toString(); - - int outlength = expand.charsWritten(); - - Debug.out("Expanded "+name+": "+inlength+" bytes to "+outName+" " +outlength+" chars." + " Ratio: "+(outlength == 0 ? 0 :(outlength * 200 / inlength))+"%."); - - if (chars == null) - return; - - writeUnicodeFile(outName, chars); - } - - /** most of the next 3 functions should not be needed by JDK11 and later */ - private static int iMSB = 1; - - public static String readUnicodeFile(String name) - { - try - { - FileInputStream dis = new FileInputStream(name); - - byte b[] = new byte[2]; - StringBuffer sb = new StringBuffer(); - char ch = 0; - - iMSB = 1; - int i = 0; - for(i = 0; (dis.available() != 0); i++) - { - b[i%2] = (byte) dis.read(); - - if ((i & 1) == 1) - { - ch = Expand.charFromTwoBytes(b[(i + iMSB)%2], b[(i + iMSB + 1) % 2]); - } - else - { - continue; - } - if (i == 1 && ch == '\uFEFF') - continue; // throw away byte order mark - - if (i == 1 && ch == '\uFFFE') - { - iMSB ++; // flip byte order - continue; // throw away byte order mark - } - sb.append(ch); - } - - return sb.toString(); - } - catch (IOException e) - { - System.err.println(e); - return ""; - } - } - - public static void writeUnicodeFile(String outName, char [] chars) - throws IOException - { - DataOutputStream dos = new DataOutputStream(new FileOutputStream(outName)); - if ((iMSB & 1) == 1) - { - dos.writeByte(0xFF); - dos.writeByte(0xFE); - } - else - { - dos.writeByte(0xFE); - dos.writeByte(0xFF); - } - byte b[] = new byte[2]; - for (int ich = 0; ich < chars.length; ich++) - { - b[(iMSB + 0)%2] = (byte) (chars[ich] >>> 8); - b[(iMSB + 1)%2] = (byte) (chars[ich] & 0xFF); - dos.write(b, 0, 2); - } - } - - static void byteswap(String name) - throws IOException - { - String text = readUnicodeFile(name); - char chars[] = text.toCharArray(); - writeUnicodeFile(name, chars); - } - - @SuppressWarnings("deprecation") - public static void parseFile(String name) - throws IOException - { - DataInputStream dis = new DataInputStream(new FileInputStream(name)); - - byte bytes[] = new byte[dis.available()]; - dis.read(bytes); - - // simplistic test - int bom = (char) bytes[0] + (char) bytes[1]; - if (bom == 131069) - { - // FEFF or FFFE detected (either one sums to 131069) - Debug.out(name + " is already in Unicode!"); - return; - } - - // definitely assumes an ASCII file at this point - String text = new String(bytes, 0); - - char chars[] = parse(text).toCharArray(); - writeUnicodeFile(name, chars); - return; - } - - public static void encodeTest(String name) - throws Exception - { - String text = readUnicodeFile(name); - - // Create an instance of the compressor - Compress compressor = new Compress(); - - byte [] bytes = null; - - // perform compression - bytes = compressor.compress(text); - - int inlength = compressor.charsRead(); - int iDot = name.lastIndexOf('.'); - StringBuffer sb = new StringBuffer(name); - sb.setLength(iDot + 1); - sb.append("csu"); - String outName = sb.toString(); - - DataOutputStream dos = new DataOutputStream(new FileOutputStream(outName)); - dos.write(bytes, 0, bytes.length); - - int outlength = compressor.bytesWritten(); - - Debug.out("Compressed "+name+": "+inlength+" chars to "+outName+" " +outlength+" bytes." + " Ratio: "+(outlength == 0 ? 0 :(outlength * 50 / inlength))+"%."); - } - - public static void roundtripTest(String name) - throws Exception - { - test(readUnicodeFile(name), false);// no debug info - } - - /** The Main function */ - public static void main(String args[]) - throws Exception - { - int iArg = args.length; - - try - { - if (iArg != 0) - { - if (args[0].equalsIgnoreCase("/compress")) - { - while (--iArg > 0) - { - encodeTest(args[args.length - iArg]); - } - } - else if (args[0].equalsIgnoreCase("/parse")) - { - while (--iArg > 0) - { - parseFile(args[args.length - iArg]); - } - } - else if (args[0].equalsIgnoreCase("/expand")) - { - while (--iArg > 0) - { - decodeTest(args[args.length - iArg]); - } - } - else if (args[0].equalsIgnoreCase("/display")) - { - while (--iArg > 0) - { - displayFile(args[args.length - iArg]); - } - } - else if (args[0].equalsIgnoreCase("/roundtrip")) - { - while (--iArg > 0) - { - roundtripTest(args[args.length - iArg]); - } - } - else if (args[0].equalsIgnoreCase("/byteswap")) - { - while (--iArg > 0) - { - byteswap(args[args.length - iArg]); - } - }else if (args[0].equalsIgnoreCase("/random")) - { - randomTest(8); - } - else if (args[0].equalsIgnoreCase("/suite")) - { - if (iArg == 1) - { - suiteTest(); - } - else - { - while (--iArg > 0) - { - fileTest(args[args.length - iArg]); - } - } - } - else if (args[0].equalsIgnoreCase("/?")) - { - usage(); - } - else - { - while (iArg > 0) - { - test2(parse(args[--iArg])); - } - } - } - else - { - usage(); - } - } - catch (IOException e) - { - System.err.println(e); - } - try - { - System.err.println("Done. Press enter to exit"); - System.in.read(); - } - catch (IOException e) - { - - } - } - - static void suiteTest() - throws Exception - { - Debug.out("Standard Compression test suite:"); - test("Hello \u9292 \u9192 World!"); - test("Hell\u0429o \u9292 \u9192 W\u00e4rld!"); - test("Hell\u0429o \u9292 \u9292W\u00e4rld!"); - - test("\u0648\u06c8"); // catch missing reset - test("\u0648\u06c8"); - - test("\u4444\uE001"); // lowest quotable - test("\u4444\uf2FF"); // highest quotable - test("\u4444\uf188\u4444"); - test("\u4444\uf188\uf288"); - test("\u4444\uf188abc\0429\uf288"); - test("\u9292\u2222"); - test("Hell\u0429\u04230o \u9292 \u9292W\u00e4\u0192rld!"); - test("Hell\u0429o \u9292 \u9292W\u00e4rld!"); - test("Hello World!123456"); - test("Hello W\u0081\u011f\u0082!"); // Latin 1 run - - test("abc\u0301\u0302"); // uses SQn for u301 u302 - test("abc\u4411d"); // uses SQU - test("abc\u4411\u4412d");// uses SCU - test("abc\u0401\u0402\u047f\u00a5\u0405"); // uses SQn for ua5 - test("\u9191\u9191\u3041\u9191\u3041\u3041\u3000"); // SJIS like data - test("\u9292\u2222"); - test("\u9191\u9191\u3041\u9191\u3041\u3041\u3000"); - test("\u9999\u3051\u300c\u9999\u9999\u3060\u9999\u3065\u3065\u3065\u300c"); - test("\u3000\u266a\u30ea\u30f3\u30b4\u53ef\u611b\u3044\u3084\u53ef\u611b\u3044\u3084\u30ea\u30f3\u30b4\u3002"); - - test(""); // empty input - test("\u0000"); // smallest BMP character - test("\uFFFF"); // largest BMP character - - test("\ud800\udc00"); // smallest surrogate - test("\ud8ff\udcff"); // largest surrogate pair - - - Debug.out("\nTHESE TESTS ARE SUPPOSED TO FAIL:"); - test("\ud800 \udc00", true); // unpaired surrogate (1) - test("\udc00", true); // unpaired surrogate (2) - test("\ud800", true); // unpaired surrogate (3) - } -} diff --git a/test/src/java/com/healthmarketscience/jackcess/impl/scsu/CompressTest.java b/test/src/java/com/healthmarketscience/jackcess/impl/scsu/CompressTest.java deleted file mode 100644 index b9dc13a..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/impl/scsu/CompressTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess.impl.scsu; - -import junit.framework.TestCase; - -/** - * @author James Ahlborn - */ -public class CompressTest extends TestCase -{ - - public CompressTest(String name) throws Exception { - super(name); - } - - public void testCompression() throws Exception - { - CompressMain.suiteTest(); - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/query/QueryTest.java b/test/src/java/com/healthmarketscience/jackcess/query/QueryTest.java deleted file mode 100644 index ade3ec1..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/query/QueryTest.java +++ /dev/null @@ -1,533 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess.query; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import com.healthmarketscience.jackcess.DataType; -import com.healthmarketscience.jackcess.Database; -import com.healthmarketscience.jackcess.DatabaseTest; -import com.healthmarketscience.jackcess.impl.query.QueryImpl; -import com.healthmarketscience.jackcess.impl.query.QueryImpl.Row; -import junit.framework.TestCase; -import org.apache.commons.lang.StringUtils; - -import static org.apache.commons.lang.SystemUtils.LINE_SEPARATOR; -import static com.healthmarketscience.jackcess.impl.query.QueryFormat.*; - -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; - - -/** - * @author James Ahlborn - */ -public class QueryTest extends TestCase -{ - - public QueryTest(String name) throws Exception { - super(name); - } - - public void testUnionQuery() throws Exception - { - String expr1 = "Select * from Table1"; - String expr2 = "Select * from Table2"; - - UnionQuery query = (UnionQuery)newQuery( - Query.Type.UNION, - newRow(TABLE_ATTRIBUTE, expr1, null, UNION_PART1), - newRow(TABLE_ATTRIBUTE, expr2, null, UNION_PART2)); - setFlag(query, 3); - - assertEquals(multiline("Select * from Table1", - "UNION Select * from Table2;"), - query.toSQLString()); - - setFlag(query, 1); - - assertEquals(multiline("Select * from Table1", - "UNION ALL Select * from Table2;"), - query.toSQLString()); - - addRows(query, newRow(ORDERBY_ATTRIBUTE, "Table1.id", - null, null)); - - assertEquals(multiline("Select * from Table1", - "UNION ALL Select * from Table2", - "ORDER BY Table1.id;"), - query.toSQLString()); - - removeRows(query, TABLE_ATTRIBUTE); - - try { - query.toSQLString(); - fail("IllegalStateException should have been thrown"); - } catch(IllegalStateException e) { - // success - } - - } - - public void testPassthroughQuery() throws Exception - { - String expr = "Select * from Table1"; - String constr = "ODBC;"; - - PassthroughQuery query = (PassthroughQuery)newQuery( - Query.Type.PASSTHROUGH, expr, constr); - - assertEquals(expr, query.toSQLString()); - assertEquals(constr, query.getConnectionString()); - } - - public void testDataDefinitionQuery() throws Exception - { - String expr = "Drop table Table1"; - - DataDefinitionQuery query = (DataDefinitionQuery)newQuery( - Query.Type.DATA_DEFINITION, expr, null); - - assertEquals(expr, query.toSQLString()); - } - - public void testUpdateQuery() throws Exception - { - UpdateQuery query = (UpdateQuery)newQuery( - Query.Type.UPDATE, - newRow(TABLE_ATTRIBUTE, null, "Table1", null), - newRow(COLUMN_ATTRIBUTE, "\"some string\"", null, "Table1.id"), - newRow(COLUMN_ATTRIBUTE, "42", null, "Table1.col1")); - - assertEquals( - multiline("UPDATE Table1", - "SET Table1.id = \"some string\", Table1.col1 = 42;"), - query.toSQLString()); - - addRows(query, newRow(WHERE_ATTRIBUTE, "(Table1.col2 < 13)", - null, null)); - - assertEquals( - multiline("UPDATE Table1", - "SET Table1.id = \"some string\", Table1.col1 = 42", - "WHERE (Table1.col2 < 13);"), - query.toSQLString()); - } - - public void testSelectQuery() throws Exception - { - SelectQuery query = (SelectQuery)newQuery( - Query.Type.SELECT, - newRow(TABLE_ATTRIBUTE, null, "Table1", null)); - setFlag(query, 1); - - assertEquals(multiline("SELECT *", - "FROM Table1;"), - query.toSQLString()); - - doTestColumns(query); - doTestSelectFlags(query); - doTestParameters(query); - doTestTables(query); - doTestRemoteDb(query); - doTestJoins(query); - doTestWhereExpression(query); - doTestGroupings(query); - doTestHavingExpression(query); - doTestOrderings(query); - } - - public void testBadQueries() throws Exception - { - List<Row> rowList = new ArrayList<Row>(); - rowList.add(newRow(TYPE_ATTRIBUTE, null, -1, null, null)); - QueryImpl query = QueryImpl.create(-1, "TestQuery", rowList, 13); - try { - query.toSQLString(); - fail("UnsupportedOperationException should have been thrown"); - } catch(UnsupportedOperationException e) { - // success - } - - addRows(query, newRow(TYPE_ATTRIBUTE, null, -1, null, null)); - - try { - query.getTypeRow(); - fail("IllegalStateException should have been thrown"); - } catch(IllegalStateException e) { - // success - } - - try { - new QueryImpl("TestQuery", rowList, 13, Query.Type.UNION.getObjectFlag(), - Query.Type.UNION) { - @Override protected void toSQLString(StringBuilder builder) { - throw new UnsupportedOperationException(); - }}; - fail("IllegalStateException should have been thrown"); - } catch(IllegalStateException e) { - // success - } - - } - - public void testReadQueries() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.QUERY, true)) { - Map<String,String> expectedQueries = new HashMap<String,String>(); - expectedQueries.put( - "SelectQuery", multiline( - "SELECT DISTINCT Table1.*, Table2.col1, Table2.col2, Table3.col3", - "FROM (Table1 LEFT JOIN Table3 ON Table1.col1 = Table3.col1) INNER JOIN Table2 ON (Table3.col1 = Table2.col1) AND (Table3.col1 = Table2.col2)", - "WHERE (((Table2.col2)=\"foo\" Or (Table2.col2) In (\"buzz\",\"bazz\")))", - "ORDER BY Table2.col1;")); - expectedQueries.put( - "DeleteQuery", multiline( - "DELETE Table1.col1, Table1.col2, Table1.col3", - "FROM Table1", - "WHERE (((Table1.col1)>\"blah\"));")); - expectedQueries.put( - "AppendQuery",multiline( - "INSERT INTO Table3", - "SELECT [Table1].[col2], [Table2].[col2], [Table2].[col3]", - "FROM Table3, Table1 INNER JOIN Table2 ON [Table1].[col1]=[Table2].[col1];")); - expectedQueries.put( - "UpdateQuery",multiline( - "PARAMETERS User Name Text;", - "UPDATE Table1", - "SET Table1.col1 = \"foo\", Table1.col2 = [Table2].[col3], [[Table2]].[[col1]] = [User Name]", - "WHERE ((([Table2].[col1]) Is Not Null));")); - expectedQueries.put( - "MakeTableQuery",multiline( - "SELECT Max(Table2.col1) AS MaxOfcol1, Table2.col2, Table3.col2 INTO Table4", - "FROM (Table2 INNER JOIN Table1 ON Table2.col1 = Table1.col2) RIGHT JOIN Table3 ON Table1.col2 = Table3.col3", - "GROUP BY Table2.col2, Table3.col2", - "HAVING (((Max(Table2.col1))=\"buzz\") AND ((Table2.col2)<>\"blah\"));")); - expectedQueries.put( - "CrosstabQuery", multiline( - "TRANSFORM Count([Table2].[col2]) AS CountOfcol2", - "SELECT Table2_1.col1, [Table2].[col3], Avg(Table2_1.col2) AS AvgOfcol2", - "FROM (Table1 INNER JOIN Table2 ON [Table1].[col1]=[Table2].[col1]) INNER JOIN Table2 AS Table2_1 ON [Table2].[col1]=Table2_1.col3", - "WHERE ((([Table1].[col1])>\"10\") And ((Table2_1.col1) Is Not Null) And ((Avg(Table2_1.col2))>\"10\"))", - "GROUP BY Table2_1.col1, [Table2].[col3]", - "ORDER BY [Table2].[col3]", - "PIVOT [Table1].[col1];")); - expectedQueries.put( - "UnionQuery", multiline( - "Select Table1.col1, Table1.col2", - "where Table1.col1 = \"foo\"", - "UNION", - "Select Table2.col1, Table2.col2", - "UNION ALL Select Table3.col1, Table3.col2", - "where Table3.col3 > \"blah\";")); - expectedQueries.put( - "PassthroughQuery", multiline( - "ALTER TABLE Table4 DROP COLUMN col5;\0")); - expectedQueries.put( - "DataDefinitionQuery", multiline( - "CREATE TABLE Table5 (col1 CHAR, col2 CHAR);\0")); - - Database db = DatabaseTest.open(testDB); - - for(Query q : db.getQueries()) { - assertEquals(expectedQueries.remove(q.getName()), q.toSQLString()); - } - - assertTrue(expectedQueries.isEmpty()); - - db.close(); - } - } - - private void doTestColumns(SelectQuery query) throws Exception - { - addRows(query, newRow(COLUMN_ATTRIBUTE, "Table1.id", null, null)); - addRows(query, newRow(COLUMN_ATTRIBUTE, "Table1.col", "Some.Alias", null)); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias], *", - "FROM Table1;"), - query.toSQLString()); - } - - private void doTestSelectFlags(SelectQuery query) throws Exception - { - setFlag(query, 3); - - assertEquals(multiline("SELECT DISTINCT Table1.id, Table1.col AS [Some.Alias], *", - "FROM Table1;"), - query.toSQLString()); - - setFlag(query, 9); - - assertEquals(multiline("SELECT DISTINCTROW Table1.id, Table1.col AS [Some.Alias], *", - "FROM Table1;"), - query.toSQLString()); - - setFlag(query, 7); - - assertEquals(multiline("SELECT DISTINCT Table1.id, Table1.col AS [Some.Alias], *", - "FROM Table1", - "WITH OWNERACCESS OPTION;"), - query.toSQLString()); - - replaceRows(query, - newRow(FLAG_ATTRIBUTE, null, 49, null, "5", null)); - - assertEquals(multiline("SELECT TOP 5 PERCENT Table1.id, Table1.col AS [Some.Alias], *", - "FROM Table1;"), - query.toSQLString()); - - setFlag(query, 0); - } - - private void doTestParameters(SelectQuery query) throws Exception - { - addRows(query, newRow(PARAMETER_ATTRIBUTE, null, DataType.INT.getValue(), "INT_VAL", null)); - - assertEquals(multiline("PARAMETERS INT_VAL Short;", - "SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1;"), - query.toSQLString()); - - addRows(query, newRow(PARAMETER_ATTRIBUTE, null, DataType.TEXT.getValue(), 50, "TextVal", null), - newRow(PARAMETER_ATTRIBUTE, null, 0, 50, "[Some Value]", null)); - - assertEquals(multiline("PARAMETERS INT_VAL Short, TextVal Text(50), [Some Value] Value;", - "SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1;"), - query.toSQLString()); - - addRows(query, newRow(PARAMETER_ATTRIBUTE, null, -1, "BadVal", null)); - try { - query.toSQLString(); - fail("IllegalStateException should have been thrown"); - } catch(IllegalStateException e) { - // success - } - - removeRows(query, PARAMETER_ATTRIBUTE); - } - - private void doTestTables(SelectQuery query) throws Exception - { - addRows(query, newRow(TABLE_ATTRIBUTE, null, "Table2", "Another Table")); - addRows(query, newRow(TABLE_ATTRIBUTE, "Select val from Table3", "val", "Table3Val")); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val;"), - query.toSQLString()); - } - - private void doTestRemoteDb(SelectQuery query) throws Exception - { - addRows(query, newRow(REMOTEDB_ATTRIBUTE, null, 2, "other_db.mdb", null)); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val IN 'other_db.mdb';"), - query.toSQLString()); - - replaceRows(query, newRow(REMOTEDB_ATTRIBUTE, "MDB_FILE;", 2, "other_db.mdb", null)); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val IN 'other_db.mdb' [MDB_FILE;];"), - query.toSQLString()); - - replaceRows(query, newRow(REMOTEDB_ATTRIBUTE, "MDB_FILE;", 2, null, null)); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val IN '' [MDB_FILE;];"), - query.toSQLString()); - - removeRows(query, REMOTEDB_ATTRIBUTE); - } - - private void doTestJoins(SelectQuery query) throws Exception - { - addRows(query, newRow(JOIN_ATTRIBUTE, "(Table1.id = [Another Table].id)", 1, "Table1", "Another Table")); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM [Select val from Table3].val AS Table3Val, Table1 INNER JOIN Table2 AS [Another Table] ON (Table1.id = [Another Table].id);"), - query.toSQLString()); - - addRows(query, newRow(JOIN_ATTRIBUTE, "(Table1.id = Table3Val.id)", 2, "Table1", "Table3Val")); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM (Table1 INNER JOIN Table2 AS [Another Table] ON (Table1.id = [Another Table].id)) LEFT JOIN [Select val from Table3].val AS Table3Val ON (Table1.id = Table3Val.id);"), - query.toSQLString()); - - addRows(query, newRow(JOIN_ATTRIBUTE, "(Table1.id = Table3Val.id)", 5, "Table1", "Table3Val")); - - try { - query.toSQLString(); - fail("IllegalStateException should have been thrown"); - } catch(IllegalStateException e) { - // success - } - - removeLastRows(query, 1); - query.toSQLString(); - - addRows(query, newRow(JOIN_ATTRIBUTE, "(Table1.id = Table3Val.id)", 1, "BogusTable", "Table3Val")); - - try { - query.toSQLString(); - fail("IllegalStateException should have been thrown"); - } catch(IllegalStateException e) { - // success - } - - removeRows(query, JOIN_ATTRIBUTE); - } - - private void doTestWhereExpression(SelectQuery query) throws Exception - { - addRows(query, newRow(WHERE_ATTRIBUTE, "(Table1.col2 < 13)", - null, null)); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val", - "WHERE (Table1.col2 < 13);"), - query.toSQLString()); - } - - private void doTestGroupings(SelectQuery query) throws Exception - { - addRows(query, newRow(GROUPBY_ATTRIBUTE, "Table1.id", null, null), - newRow(GROUPBY_ATTRIBUTE, "SUM(Table1.val)", null, null)); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val", - "WHERE (Table1.col2 < 13)", - "GROUP BY Table1.id, SUM(Table1.val);"), - query.toSQLString()); - } - - private void doTestHavingExpression(SelectQuery query) throws Exception - { - addRows(query, newRow(HAVING_ATTRIBUTE, "(SUM(Table1.val) = 500)", null, null)); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val", - "WHERE (Table1.col2 < 13)", - "GROUP BY Table1.id, SUM(Table1.val)", - "HAVING (SUM(Table1.val) = 500);"), - query.toSQLString()); - } - - private void doTestOrderings(SelectQuery query) throws Exception - { - addRows(query, newRow(ORDERBY_ATTRIBUTE, "Table1.id", null, null), - newRow(ORDERBY_ATTRIBUTE, "Table2.val", "D", null)); - - assertEquals(multiline("SELECT Table1.id, Table1.col AS [Some.Alias]", - "FROM Table1, Table2 AS [Another Table], [Select val from Table3].val AS Table3Val", - "WHERE (Table1.col2 < 13)", - "GROUP BY Table1.id, SUM(Table1.val)", - "HAVING (SUM(Table1.val) = 500)", - "ORDER BY Table1.id, Table2.val DESC;"), - query.toSQLString()); - } - - - private static Query newQuery(Query.Type type, Row... rows) - { - return newQuery(type, null, null, rows); - } - - private static Query newQuery(Query.Type type, String typeExpr, - String typeName1, Row... rows) - { - List<Row> rowList = new ArrayList<Row>(); - rowList.add(newRow(TYPE_ATTRIBUTE, typeExpr, type.getValue(), - null, typeName1, null)); - rowList.addAll(Arrays.asList(rows)); - return QueryImpl.create(type.getObjectFlag(), "TestQuery", rowList, 13); - } - - private static Row newRow(Byte attr, String expr, String name1, String name2) - { - return newRow(attr, expr, null, null, name1, name2); - } - - private static Row newRow(Byte attr, String expr, Number flagNum, - String name1, String name2) - { - return newRow(attr, expr, flagNum, null, name1, name2); - } - - private static Row newRow(Byte attr, String expr, Number flagNum, - Number extraNum, String name1, String name2) - { - Short flag = ((flagNum != null) ? flagNum.shortValue() : null); - Integer extra = ((extraNum != null) ? extraNum.intValue() : null); - return new Row(null, attr, expr, flag, extra, name1, name2, null, null); - } - - private static void setFlag(Query query, Number newFlagNum) - { - replaceRows(query, - newRow(FLAG_ATTRIBUTE, null, newFlagNum, null, null, null)); - } - - private static void addRows(Query query, Row... rows) - { - ((QueryImpl)query).getRows().addAll(Arrays.asList(rows)); - } - - private static void replaceRows(Query query, Row... rows) - { - removeRows(query, rows[0].attribute); - addRows(query, rows); - } - - private static void removeRows(Query query, Byte attr) - { - for(Iterator<Row> iter = ((QueryImpl)query).getRows().iterator(); iter.hasNext(); ) { - if(attr.equals(iter.next().attribute)) { - iter.remove(); - } - } - } - - private static void removeLastRows(Query query, int num) - { - List<Row> rows = ((QueryImpl)query).getRows(); - int size = rows.size(); - rows.subList(size - num, size).clear(); - } - - private static String multiline(String... strs) - { - return StringUtils.join(strs, LINE_SEPARATOR); - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/util/ErrorHandlerTest.java b/test/src/java/com/healthmarketscience/jackcess/util/ErrorHandlerTest.java deleted file mode 100644 index 6431ad8..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/util/ErrorHandlerTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess.util; - -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.nio.ByteOrder; -import java.util.List; - -import com.healthmarketscience.jackcess.Column; -import com.healthmarketscience.jackcess.ColumnBuilder; -import com.healthmarketscience.jackcess.Cursor; -import com.healthmarketscience.jackcess.CursorBuilder; -import com.healthmarketscience.jackcess.DataType; -import com.healthmarketscience.jackcess.Database; -import static com.healthmarketscience.jackcess.Database.*; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.Table; -import com.healthmarketscience.jackcess.TableBuilder; -import com.healthmarketscience.jackcess.impl.ColumnImpl; -import com.healthmarketscience.jackcess.impl.JetFormatTest; -import com.healthmarketscience.jackcess.impl.TableImpl; -import junit.framework.TestCase; - -/** - * @author James Ahlborn - */ -public class ErrorHandlerTest extends TestCase -{ - - public ErrorHandlerTest(String name) { - super(name); - } - - public void testErrorHandler() throws Exception - { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - - Table table = - new TableBuilder("test") - .addColumn(new ColumnBuilder("col", DataType.TEXT)) - .addColumn(new ColumnBuilder("val", DataType.LONG)) - .toTable(db); - - table.addRow("row1", 1); - table.addRow("row2", 2); - table.addRow("row3", 3); - - assertTable(createExpectedTable( - createExpectedRow("col", "row1", - "val", 1), - createExpectedRow("col", "row2", - "val", 2), - createExpectedRow("col", "row3", - "val", 3)), - table); - - - replaceColumn(table, "val"); - - table.reset(); - try { - table.getNextRow(); - fail("IOException should have been thrown"); - } catch(IOException e) { - // success - } - - table.reset(); - table.setErrorHandler(new ReplacementErrorHandler()); - - assertTable(createExpectedTable( - createExpectedRow("col", "row1", - "val", null), - createExpectedRow("col", "row2", - "val", null), - createExpectedRow("col", "row3", - "val", null)), - table); - - Cursor c1 = CursorBuilder.createCursor(table); - Cursor c2 = CursorBuilder.createCursor(table); - Cursor c3 = CursorBuilder.createCursor(table); - - c2.setErrorHandler(new DebugErrorHandler("#error")); - c3.setErrorHandler(ErrorHandler.DEFAULT); - - assertCursor(createExpectedTable( - createExpectedRow("col", "row1", - "val", null), - createExpectedRow("col", "row2", - "val", null), - createExpectedRow("col", "row3", - "val", null)), - c1); - - assertCursor(createExpectedTable( - createExpectedRow("col", "row1", - "val", "#error"), - createExpectedRow("col", "row2", - "val", "#error"), - createExpectedRow("col", "row3", - "val", "#error")), - c2); - - try { - c3.getNextRow(); - fail("IOException should have been thrown"); - } catch(IOException e) { - // success - } - - table.setErrorHandler(null); - c1.setErrorHandler(null); - c1.reset(); - try { - c1.getNextRow(); - fail("IOException should have been thrown"); - } catch(IOException e) { - // success - } - - - db.close(); - } - } - - @SuppressWarnings("unchecked") - private static void replaceColumn(Table t, String colName) throws Exception - { - Field colsField = TableImpl.class.getDeclaredField("_columns"); - colsField.setAccessible(true); - List<Column> cols = (List<Column>)colsField.get(t); - - Column srcCol = null; - ColumnImpl destCol = new BogusColumn(t); - destCol.setName(colName); - for(int i = 0; i < cols.size(); ++i) { - srcCol = cols.get(i); - if(srcCol.getName().equals(colName)) { - cols.set(i, destCol); - break; - } - } - - // copy fields from source to dest - for(Field f : Column.class.getDeclaredFields()) { - if(!Modifier.isFinal(f.getModifiers())) { - f.setAccessible(true); - f.set(destCol, f.get(srcCol)); - } - } - - } - - private static class BogusColumn extends ColumnImpl - { - private BogusColumn(Table table) { - super((TableImpl)table, DataType.LONG, 1, 0, 0); - } - - @Override - public Object read(byte[] data, ByteOrder order) throws IOException { - throw new IOException("bogus column"); - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/util/ExportTest.java b/test/src/java/com/healthmarketscience/jackcess/util/ExportTest.java deleted file mode 100644 index a271771..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/util/ExportTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess.util; - -import java.io.BufferedWriter; -import java.io.StringWriter; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.healthmarketscience.jackcess.ColumnBuilder; -import com.healthmarketscience.jackcess.DataType; -import com.healthmarketscience.jackcess.Database; -import static com.healthmarketscience.jackcess.Database.*; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.Table; -import com.healthmarketscience.jackcess.TableBuilder; -import com.healthmarketscience.jackcess.impl.JetFormatTest; -import junit.framework.TestCase; -import org.apache.commons.lang.SystemUtils; - -/** - * - * @author James Ahlborn - */ -public class ExportTest extends TestCase -{ - private static final String NL = SystemUtils.LINE_SEPARATOR; - - - public ExportTest(String name) { - super(name); - } - - public void testExportToFile() throws Exception - { - DateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss"); - df.setTimeZone(TEST_TZ); - - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - db.setTimeZone(TEST_TZ); - - Table t = new TableBuilder("test") - .addColumn(new ColumnBuilder("col1", DataType.TEXT)) - .addColumn(new ColumnBuilder("col2", DataType.LONG)) - .addColumn(new ColumnBuilder("col3", DataType.DOUBLE)) - .addColumn(new ColumnBuilder("col4", DataType.OLE)) - .addColumn(new ColumnBuilder("col5", DataType.BOOLEAN)) - .addColumn(new ColumnBuilder("col6", DataType.SHORT_DATE_TIME)) - .toTable(db); - - Date testDate = df.parse("19801231 00:00:00"); - t.addRow("some text||some more", 13, 13.25, createString(30).getBytes(), - true, testDate); - - t.addRow("crazy'data\"here", -345, -0.000345, createString(7).getBytes(), - true, null); - - t.addRow("C:\\temp\\some_file.txt", 25, 0.0, null, false, null); - - StringWriter out = new StringWriter(); - - new ExportUtil.Builder(db, "test") - .exportWriter(new BufferedWriter(out)); - - String expected = - "some text||some more,13,13.25,\"61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78\n79 7A 61 62 63 64\",true," + testDate + NL + - "\"crazy'data\"\"here\",-345,-3.45E-4,61 62 63 64 65 66 67,true," + NL + - "C:\\temp\\some_file.txt,25,0.0,,false," + NL; - - assertEquals(expected, out.toString()); - - out = new StringWriter(); - - new ExportUtil.Builder(db, "test") - .setHeader(true) - .setDelimiter("||") - .setQuote('\'') - .exportWriter(new BufferedWriter(out)); - - expected = - "col1||col2||col3||col4||col5||col6" + NL + - "'some text||some more'||13||13.25||'61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78\n79 7A 61 62 63 64'||true||" + testDate + NL + - "'crazy''data\"here'||-345||-3.45E-4||61 62 63 64 65 66 67||true||" + NL + - "C:\\temp\\some_file.txt||25||0.0||||false||" + NL; - assertEquals(expected, out.toString()); - - ExportFilter oddFilter = new SimpleExportFilter() { - private int _num; - @Override - public Object[] filterRow(Object[] row) { - if((_num++ % 2) == 1) { - return null; - } - return row; - } - }; - - out = new StringWriter(); - - new ExportUtil.Builder(db, "test") - .setFilter(oddFilter) - .exportWriter(new BufferedWriter(out)); - - expected = - "some text||some more,13,13.25,\"61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 71 72 73 74 75 76 77 78\n79 7A 61 62 63 64\",true," + testDate + NL + - "C:\\temp\\some_file.txt,25,0.0,,false," + NL; - - assertEquals(expected, out.toString()); - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/util/ImportTest.java b/test/src/java/com/healthmarketscience/jackcess/util/ImportTest.java deleted file mode 100644 index 49be97c..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/util/ImportTest.java +++ /dev/null @@ -1,333 +0,0 @@ -/* -Copyright (c) 2007 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess.util; - -import java.io.File; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.sql.ResultSet; -import java.sql.ResultSetMetaData; -import java.sql.Types; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; - -import com.healthmarketscience.jackcess.Column; -import com.healthmarketscience.jackcess.ColumnBuilder; -import com.healthmarketscience.jackcess.DataType; -import com.healthmarketscience.jackcess.Database; -import static com.healthmarketscience.jackcess.Database.*; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.Table; -import com.healthmarketscience.jackcess.TableBuilder; -import com.healthmarketscience.jackcess.impl.JetFormatTest; -import junit.framework.TestCase; - -/** - * @author Rob Di Marco - */ -public class ImportTest extends TestCase -{ - - public ImportTest(String name) { - super(name); - } - - public void testImportFromFile() throws Exception - { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - String tableName = new ImportUtil.Builder(db, "test") - .setDelimiter("\\t") - .importFile(new File("test/data/sample-input.tab")); - Table t = db.getTable(tableName); - - List<String> colNames = new ArrayList<String>(); - for(Column c : t.getColumns()) { - colNames.add(c.getName()); - } - assertEquals(Arrays.asList("Test1", "Test2", "Test3"), colNames); - - List<? extends Map<String, Object>> expectedRows = - createExpectedTable( - createExpectedRow( - "Test1", "Foo", - "Test2", "Bar", - "Test3", "Ralph"), - createExpectedRow( - "Test1", "S", - "Test2", "Mouse", - "Test3", "Rocks"), - createExpectedRow( - "Test1", "", - "Test2", "Partial line", - "Test3", null), - createExpectedRow( - "Test1", " Quoted Value", - "Test2", " bazz ", - "Test3", " Really \"Crazy" + ImportUtil.LINE_SEPARATOR - + "value\""), - createExpectedRow( - "Test1", "buzz", - "Test2", "embedded\tseparator", - "Test3", "long") - ); - assertTable(expectedRows, t); - - t = new TableBuilder("test2") - .addColumn(new ColumnBuilder("T1", DataType.TEXT)) - .addColumn(new ColumnBuilder("T2", DataType.TEXT)) - .addColumn(new ColumnBuilder("T3", DataType.TEXT)) - .toTable(db); - - new ImportUtil.Builder(db, "test2") - .setDelimiter("\\t") - .setUseExistingTable(true) - .setHeader(false) - .importFile(new File("test/data/sample-input.tab")); - - expectedRows = - createExpectedTable( - createExpectedRow( - "T1", "Test1", - "T2", "Test2", - "T3", "Test3"), - createExpectedRow( - "T1", "Foo", - "T2", "Bar", - "T3", "Ralph"), - createExpectedRow( - "T1", "S", - "T2", "Mouse", - "T3", "Rocks"), - createExpectedRow( - "T1", "", - "T2", "Partial line", - "T3", null), - createExpectedRow( - "T1", " Quoted Value", - "T2", " bazz ", - "T3", " Really \"Crazy" + ImportUtil.LINE_SEPARATOR - + "value\""), - createExpectedRow( - "T1", "buzz", - "T2", "embedded\tseparator", - "T3", "long") - ); - assertTable(expectedRows, t); - - - ImportFilter oddFilter = new SimpleImportFilter() { - private int _num; - @Override - public Object[] filterRow(Object[] row) { - if((_num++ % 2) == 1) { - return null; - } - return row; - } - }; - - tableName = new ImportUtil.Builder(db, "test3") - .setDelimiter("\\t") - .setFilter(oddFilter) - .importFile(new File("test/data/sample-input.tab")); - t = db.getTable(tableName); - - colNames = new ArrayList<String>(); - for(Column c : t.getColumns()) { - colNames.add(c.getName()); - } - assertEquals(Arrays.asList("Test1", "Test2", "Test3"), colNames); - - expectedRows = - createExpectedTable( - createExpectedRow( - "Test1", "Foo", - "Test2", "Bar", - "Test3", "Ralph"), - createExpectedRow( - "Test1", "", - "Test2", "Partial line", - "Test3", null), - createExpectedRow( - "Test1", "buzz", - "Test2", "embedded\tseparator", - "Test3", "long") - ); - assertTable(expectedRows, t); - - db.close(); - } - } - - public void testImportFromFileWithOnlyHeaders() throws Exception - { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - Database db = create(fileFormat); - String tableName = new ImportUtil.Builder(db, "test") - .setDelimiter("\\t") - .importFile(new File("test/data/sample-input-only-headers.tab")); - - Table t = db.getTable(tableName); - - List<String> colNames = new ArrayList<String>(); - for(Column c : t.getColumns()) { - colNames.add(c.getName()); - } - assertEquals(Arrays.asList( - "RESULT_PHYS_ID", "FIRST", "MIDDLE", "LAST", "OUTLIER", - "RANK", "CLAIM_COUNT", "PROCEDURE_COUNT", - "WEIGHTED_CLAIM_COUNT", "WEIGHTED_PROCEDURE_COUNT"), - colNames); - - db.close(); - } - } - - public void testCopySqlHeaders() throws Exception - { - for (final FileFormat fileFormat : JetFormatTest.SUPPORTED_FILEFORMATS) { - - TestResultSet rs = new TestResultSet(); - - rs.addColumn(Types.INTEGER, "col1"); - rs.addColumn(Types.VARCHAR, "col2", 60, 0, 0); - rs.addColumn(Types.VARCHAR, "col3", 500, 0, 0); - rs.addColumn(Types.BINARY, "col4", 128, 0, 0); - rs.addColumn(Types.BINARY, "col5", 512, 0, 0); - rs.addColumn(Types.NUMERIC, "col6", 0, 7, 15); - rs.addColumn(Types.VARCHAR, "col7", Integer.MAX_VALUE, 0, 0); - - Database db = create(fileFormat); - ImportUtil.importResultSet((ResultSet)Proxy.newProxyInstance( - Thread.currentThread().getContextClassLoader(), - new Class[]{ResultSet.class}, - rs), db, "Test1"); - - Table t = db.getTable("Test1"); - List<? extends Column> columns = t.getColumns(); - assertEquals(7, columns.size()); - - Column c = columns.get(0); - assertEquals("col1", c.getName()); - assertEquals(DataType.LONG, c.getType()); - - c = columns.get(1); - assertEquals("col2", c.getName()); - assertEquals(DataType.TEXT, c.getType()); - assertEquals(120, c.getLength()); - - c = columns.get(2); - assertEquals("col3", c.getName()); - assertEquals(DataType.MEMO, c.getType()); - assertEquals(0, c.getLength()); - - c = columns.get(3); - assertEquals("col4", c.getName()); - assertEquals(DataType.BINARY, c.getType()); - assertEquals(128, c.getLength()); - - c = columns.get(4); - assertEquals("col5", c.getName()); - assertEquals(DataType.OLE, c.getType()); - assertEquals(0, c.getLength()); - - c = columns.get(5); - assertEquals("col6", c.getName()); - assertEquals(DataType.NUMERIC, c.getType()); - assertEquals(17, c.getLength()); - assertEquals(7, c.getScale()); - assertEquals(15, c.getPrecision()); - - c = columns.get(6); - assertEquals("col7", c.getName()); - assertEquals(DataType.MEMO, c.getType()); - assertEquals(0, c.getLength()); - } - } - - - private static class TestResultSet implements InvocationHandler - { - private List<Integer> _types = new ArrayList<Integer>(); - private List<String> _names = new ArrayList<String>(); - private List<Integer> _displaySizes = new ArrayList<Integer>(); - private List<Integer> _scales = new ArrayList<Integer>(); - private List<Integer> _precisions = new ArrayList<Integer>(); - - public Object invoke(Object proxy, Method method, Object[] args) - { - String methodName = method.getName(); - if(methodName.equals("getMetaData")) { - return Proxy.newProxyInstance( - Thread.currentThread().getContextClassLoader(), - new Class[]{ResultSetMetaData.class}, - this); - } else if(methodName.equals("next")) { - return Boolean.FALSE; - } else if(methodName.equals("getColumnCount")) { - return _types.size(); - } else if(methodName.equals("getColumnName")) { - return getValue(_names, args[0]); - } else if(methodName.equals("getColumnDisplaySize")) { - return getValue(_displaySizes, args[0]); - } else if(methodName.equals("getColumnType")) { - return getValue(_types, args[0]); - } else if(methodName.equals("getScale")) { - return getValue(_scales, args[0]); - } else if(methodName.equals("getPrecision")) { - return getValue(_precisions, args[0]); - } else { - throw new UnsupportedOperationException(methodName); - } - } - - public void addColumn(int type, String name) - { - addColumn(type, name, 0, 0, 0); - } - - public void addColumn(int type, String name, int displaySize, - int scale, int precision) - { - _types.add(type); - _names.add(name); - _displaySizes.add(displaySize); - _scales.add(scale); - _precisions.add(precision); - } - - private static <T> T getValue(List<T> values, Object index) { - return values.get((Integer)index - 1); - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/util/JoinerTest.java b/test/src/java/com/healthmarketscience/jackcess/util/JoinerTest.java deleted file mode 100644 index f6de03b..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/util/JoinerTest.java +++ /dev/null @@ -1,209 +0,0 @@ -/* -Copyright (c) 2011 James Ahlborn - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA -*/ - -package com.healthmarketscience.jackcess.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.healthmarketscience.jackcess.Database; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.Index; -import com.healthmarketscience.jackcess.Row; -import com.healthmarketscience.jackcess.Table; -import com.healthmarketscience.jackcess.impl.RowImpl; -import static com.healthmarketscience.jackcess.impl.JetFormatTest.*; -import junit.framework.TestCase; - -/** - * - * @author James Ahlborn - */ -public class JoinerTest extends TestCase { - - public JoinerTest(String name) { - super(name); - } - - public void testJoiner() throws Exception - { - for (final TestDB testDB : TestDB.getSupportedForBasename(Basename.INDEX)) { - - Database db = openCopy(testDB); - Table t1 = db.getTable("Table1"); - Table t2 = db.getTable("Table2"); - Table t3 = db.getTable("Table3"); - - Index t1t2 = t1.getIndex("Table2Table1"); - Index t1t3 = t1.getIndex("Table3Table1"); - - Index t2t1 = t1t2.getReferencedIndex(); - assertSame(t2, t2t1.getTable()); - Joiner t2t1Join = Joiner.create(t2t1); - - assertSame(t2, t2t1Join.getFromTable()); - assertSame(t2t1, t2t1Join.getFromIndex()); - assertSame(t1, t2t1Join.getToTable()); - assertSame(t1t2, t2t1Join.getToIndex()); - - doTestJoiner(t2t1Join, createT2T1Data()); - - Index t3t1 = t1t3.getReferencedIndex(); - assertSame(t3, t3t1.getTable()); - Joiner t3t1Join = Joiner.create(t3t1); - - assertSame(t3, t3t1Join.getFromTable()); - assertSame(t3t1, t3t1Join.getFromIndex()); - assertSame(t1, t3t1Join.getToTable()); - assertSame(t1t3, t3t1Join.getToIndex()); - - doTestJoiner(t3t1Join, createT3T1Data()); - - doTestJoinerDelete(t2t1Join); - } - } - - private static void doTestJoiner( - Joiner join, Map<Integer,List<Row>> expectedData) - throws Exception - { - final Set<String> colNames = new HashSet<String>( - Arrays.asList("id", "data")); - - Joiner revJoin = join.createReverse(); - for(Row row : join.getFromTable()) { - Integer id = (Integer)row.get("id"); - - List<Row> joinedRows = - new ArrayList<Row>(); - for(Row t1Row : join.findRows(row)) { - joinedRows.add(t1Row); - } - - List<Row> expectedRows = expectedData.get(id); - assertEquals(expectedData.get(id), joinedRows); - - if(!expectedRows.isEmpty()) { - assertTrue(join.hasRows(row)); - assertEquals(expectedRows.get(0), join.findFirstRow(row)); - - assertEquals(row, revJoin.findFirstRow(expectedRows.get(0))); - } else { - assertFalse(join.hasRows(row)); - assertNull(join.findFirstRow(row)); - } - - List<Row> expectedRows2 = new ArrayList<Row>(); - for(Row tmpRow : expectedRows) { - Row tmpRow2 = new RowImpl(tmpRow); - tmpRow2.keySet().retainAll(colNames); - expectedRows2.add(tmpRow2); - } - - joinedRows = new ArrayList<Row>(); - for(Row t1Row : join.findRows(row).setColumnNames(colNames)) { - joinedRows.add(t1Row); - } - - assertEquals(expectedRows2, joinedRows); - - if(!expectedRows2.isEmpty()) { - assertEquals(expectedRows2.get(0), join.findFirstRow(row, colNames)); - } else { - assertNull(join.findFirstRow(row, colNames)); - } - } - } - - private static void doTestJoinerDelete(Joiner t2t1Join) throws Exception - { - assertEquals(4, countRows(t2t1Join.getToTable())); - - Row row = createExpectedRow("id", 1); - assertTrue(t2t1Join.hasRows(row)); - - assertTrue(t2t1Join.deleteRows(row)); - - assertFalse(t2t1Join.hasRows(row)); - assertFalse(t2t1Join.deleteRows(row)); - - assertEquals(2, countRows(t2t1Join.getToTable())); - for(Row t1Row : t2t1Join.getToTable()) { - assertFalse(t1Row.get("otherfk1").equals(1)); - } - } - - private static Map<Integer,List<Row>> createT2T1Data() - { - Map<Integer,List<Row>> data = new - HashMap<Integer,List<Row>>(); - - data.put(0, - createExpectedTable( - createExpectedRow("id", 0, "otherfk1", 0, "otherfk2", 10, - "data", "baz0", "otherfk3", 0))); - - data.put(1, - createExpectedTable( - createExpectedRow("id", 1, "otherfk1", 1, "otherfk2", 11, - "data", "baz11", "otherfk3", 0), - createExpectedRow("id", 2, "otherfk1", 1, "otherfk2", 11, - "data", "baz11-2", "otherfk3", 0))); - - data.put(2, - createExpectedTable( - createExpectedRow("id", 3, "otherfk1", 2, "otherfk2", 13, - "data", "baz13", "otherfk3", 0))); - - return data; - } - - private static Map<Integer,List<Row>> createT3T1Data() - { - Map<Integer,List<Row>> data = new HashMap<Integer,List<Row>>(); - - data.put(10, - createExpectedTable( - createExpectedRow("id", 0, "otherfk1", 0, "otherfk2", 10, - "data", "baz0", "otherfk3", 0))); - - data.put(11, - createExpectedTable( - createExpectedRow("id", 1, "otherfk1", 1, "otherfk2", 11, - "data", "baz11", "otherfk3", 0), - createExpectedRow("id", 2, "otherfk1", 1, "otherfk2", 11, - "data", "baz11-2", "otherfk3", 0))); - - data.put(12, - createExpectedTable()); - - data.put(13, - createExpectedTable( - createExpectedRow("id", 3, "otherfk1", 2, "otherfk2", 13, - "data", "baz13", "otherfk3", 0))); - - return data; - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/util/MemFileChannelTest.java b/test/src/java/com/healthmarketscience/jackcess/util/MemFileChannelTest.java deleted file mode 100644 index 3e78a2c..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/util/MemFileChannelTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/* -Copyright (c) 2012 James Ahlborn - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA -*/ - -package com.healthmarketscience.jackcess.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.channels.NonWritableChannelException; -import java.util.Arrays; - -import junit.framework.TestCase; - -import com.healthmarketscience.jackcess.DatabaseTest; - -/** - * - * @author James Ahlborn - */ -public class MemFileChannelTest extends TestCase -{ - - public MemFileChannelTest(String name) { - super(name); - } - - public void testReadOnlyChannel() throws Exception - { - File testFile = new File("test/data/V1997/compIndexTestV1997.mdb"); - MemFileChannel ch = MemFileChannel.newChannel(testFile, "r"); - assertEquals(testFile.length(), ch.size()); - assertEquals(0L, ch.position()); - - try { - ByteBuffer bb = ByteBuffer.allocate(1024); - ch.write(bb); - fail("NonWritableChannelException should have been thrown"); - } catch(NonWritableChannelException ignored) { - // success - } - - try { - ch.truncate(0L); - fail("NonWritableChannelException should have been thrown"); - } catch(NonWritableChannelException ignored) { - // success - } - - try { - ch.transferFrom(null, 0L, 10L); - fail("NonWritableChannelException should have been thrown"); - } catch(NonWritableChannelException ignored) { - // success - } - - assertEquals(testFile.length(), ch.size()); - assertEquals(0L, ch.position()); - - ch.close(); - } - - public void testChannel() throws Exception - { - ByteBuffer bb = ByteBuffer.allocate(1024); - - MemFileChannel ch = MemFileChannel.newChannel(); - assertTrue(ch.isOpen()); - assertEquals(0L, ch.size()); - assertEquals(0L, ch.position()); - assertEquals(-1, ch.read(bb)); - - ch.close(); - - assertFalse(ch.isOpen()); - - File testFile = new File("test/data/V1997/compIndexTestV1997.mdb"); - ch = MemFileChannel.newChannel(testFile, "r"); - assertEquals(testFile.length(), ch.size()); - assertEquals(0L, ch.position()); - - try { - ch.position(-1); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException ignored) { - // success - } - - MemFileChannel ch2 = MemFileChannel.newChannel(); - ch.transferTo(ch2); - ch2.force(true); - assertEquals(testFile.length(), ch2.size()); - assertEquals(testFile.length(), ch2.position()); - - try { - ch2.truncate(-1L); - fail("IllegalArgumentException should have been thrown"); - } catch(IllegalArgumentException ignored) { - // success - } - - long trucSize = ch2.size()/3; - ch2.truncate(trucSize); - assertEquals(trucSize, ch2.size()); - assertEquals(trucSize, ch2.position()); - ch2.position(0L); - copy(ch, ch2, bb); - - File tmpFile = File.createTempFile("chtest_", ".dat"); - tmpFile.deleteOnExit(); - FileOutputStream fc = new FileOutputStream(tmpFile); - - ch2.transferTo(fc); - - fc.close(); - - assertEquals(testFile.length(), tmpFile.length()); - - assertTrue(Arrays.equals(DatabaseTest.toByteArray(testFile), - DatabaseTest.toByteArray(tmpFile))); - - ch2.truncate(0L); - assertTrue(ch2.isOpen()); - assertEquals(0L, ch2.size()); - assertEquals(0L, ch2.position()); - assertEquals(-1, ch2.read(bb)); - - ch2.close(); - assertFalse(ch2.isOpen()); - } - - private static void copy(FileChannel src, FileChannel dst, ByteBuffer bb) - throws IOException - { - src.position(0L); - while(true) { - bb.clear(); - if(src.read(bb) < 0) { - break; - } - bb.flip(); - dst.write(bb); - } - } - -} diff --git a/test/src/java/com/healthmarketscience/jackcess/util/RowFilterTest.java b/test/src/java/com/healthmarketscience/jackcess/util/RowFilterTest.java deleted file mode 100644 index 7808a08..0000000 --- a/test/src/java/com/healthmarketscience/jackcess/util/RowFilterTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* -Copyright (c) 2008 Health Market Science, Inc. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library 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 -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 -USA - -You can contact Health Market Science at info@healthmarketscience.com -or at the following address: - -Health Market Science -2700 Horizon Drive -Suite 200 -King of Prussia, PA 19406 -*/ - -package com.healthmarketscience.jackcess.util; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import com.healthmarketscience.jackcess.DataType; -import static com.healthmarketscience.jackcess.DatabaseTest.*; -import com.healthmarketscience.jackcess.Row; -import com.healthmarketscience.jackcess.impl.ColumnImpl; -import junit.framework.TestCase; - -/** - * @author James Ahlborn - */ -public class RowFilterTest extends TestCase -{ - private static final String ID_COL = "id"; - private static final String COL1 = "col1"; - private static final String COL2 = "col2"; - private static final String COL3 = "col3"; - - - public RowFilterTest(String name) { - super(name); - } - - @SuppressWarnings("unchecked") - public void testFilter() throws Exception - { - Row row0 = createExpectedRow(ID_COL, 0, COL1, "foo", COL2, 13, COL3, "bar"); - Row row1 = createExpectedRow(ID_COL, 1, COL1, "bar", COL2, 42, COL3, null); - Row row2 = createExpectedRow(ID_COL, 2, COL1, "foo", COL2, 55, COL3, "bar"); - Row row3 = createExpectedRow(ID_COL, 3, COL1, "baz", COL2, 42, COL3, "bar"); - Row row4 = createExpectedRow(ID_COL, 4, COL1, "foo", COL2, 13, COL3, null); - Row row5 = createExpectedRow(ID_COL, 5, COL1, "bla", COL2, 13, COL3, "bar"); - - - List<Row> rows = Arrays.asList(row0, row1, row2, row3, row4, row5); - - ColumnImpl testCol = new ColumnImpl(null, DataType.TEXT, 0, 0, 0) {}; - testCol.setName(COL1); - assertEquals(Arrays.asList(row0, row2, row4), - toList(RowFilter.matchPattern(testCol, - "foo").apply(rows))); - assertEquals(Arrays.asList(row1, row3, row5), - toList(RowFilter.invert( - RowFilter.matchPattern( - testCol, - "foo")).apply(rows))); - - assertEquals(Arrays.asList(row0, row2, row4), - toList(RowFilter.matchPattern( - createExpectedRow(COL1, "foo")) - .apply(rows))); - assertEquals(Arrays.asList(row0, row2), - toList(RowFilter.matchPattern( - createExpectedRow(COL1, "foo", COL3, "bar")) - .apply(rows))); - assertEquals(Arrays.asList(row4), - toList(RowFilter.matchPattern( - createExpectedRow(COL1, "foo", COL3, null)) - .apply(rows))); - assertEquals(Arrays.asList(row0, row4, row5), - toList(RowFilter.matchPattern( - createExpectedRow(COL2, 13)) - .apply(rows))); - assertEquals(Arrays.asList(row1), - toList(RowFilter.matchPattern(row1) - .apply(rows))); - - assertEquals(rows, toList(RowFilter.apply(null, rows))); - assertEquals(Arrays.asList(row1), - toList(RowFilter.apply(RowFilter.matchPattern(row1), - rows))); - } - - public static List<Row> toList(Iterable<Row> rows) - { - List<Row> rowList = new ArrayList<Row>(); - for(Row row : rows) { - rowList.add(row); - } - return rowList; - } - -} |