Java Code Examples for com.healthmarketscience.jackcess.Database#getTable()

The following examples show how to use com.healthmarketscience.jackcess.Database#getTable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FKEnforcerTest.java    From jackcess with Apache License 2.0 6 votes vote down vote up
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();
  }
  
}
 
Example 2
Source File: MdbLoader.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void loadData(List<Tuple<String, File>> files, Importer importer) throws InvalidFileException, IOException {
  Database database = DatabaseBuilder.open(files.get(0).getRight());
  for (String tableName : database.getTableNames()) {
    importer.startCollection(tableName);
    Table table = database.getTable(tableName);
    List<? extends Column> columns = table.getColumns();
    for (int i = 0; i < columns.size(); i++) {
      importer.registerPropertyName(i, columns.get(i).getName());
    }

    for (Row row : table) {
      importer.startEntity();
      for (int colNum = 0 ; colNum < columns.size(); colNum++) {
        Object cellValue = row.get(columns.get(colNum).getName());
        if (cellValue == null) {
          cellValue = "";
        }
        importer.setValue(colNum, "" + cellValue);
      }
      importer.finishEntity();
    }
    importer.finishCollection();
  }
}
 
Example 3
Source File: ImportUtil.java    From jackcess with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new table with a unique name and the given table definition.
 */
private static Table createUniqueTable(Database db, String name,
                                       List<ColumnBuilder> columns,
                                       ResultSetMetaData md,
                                       ImportFilter filter)
  throws IOException, SQLException
{
  // otherwise, find unique name and create new table
  String baseName = name;
  int counter = 2;
  while(db.getTable(name) != null) {
    name = baseName + (counter++);
  }

  return new TableBuilder(name)
    .addColumns(filter.filterColumns(columns, md))
    .toTable(db);
}
 
Example 4
Source File: DatabaseReadWriteTest.java    From jackcess with Apache License 2.0 6 votes vote down vote up
private static void doTestWriteAndRead(Database db) throws Exception {
    createTestTable(db);
    Object[] row = createTestRow();
    row[3] = null;
    Table table = db.getTable("Test");
    int count = 1000;
    ((DatabaseImpl)db).getPageChannel().startWrite();
    try {
      for (int i = 0; i < count; i++) {
        table.addRow(row);
      }
    } finally {
      ((DatabaseImpl)db).getPageChannel().finishWrite();
    }
    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"));
    }
}
 
Example 5
Source File: ImportTest.java    From jackcess with Apache License 2.0 6 votes vote down vote up
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("src/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();
  }
}
 
Example 6
Source File: LongValueTest.java    From jackcess with Apache License 2.0 6 votes vote down vote up
public void testLongValueAsMiddleColumn() throws Exception
{
  for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) {
    Database db = createMem(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();
  }
}
 
Example 7
Source File: CalcFieldTest.java    From jackcess with Apache License 2.0 6 votes vote down vote up
public void testReadCalcFields() throws Exception {

    for(TestDB testDB : TestDB.getSupportedForBasename(Basename.CALC_FIELD)) {
      Database db = open(testDB);
      Table t = db.getTable("Table1");

      List<String> rows = new ArrayList<String>();
      for(Row r : t) {
        rows.add(r.entrySet().toString());
      }

      List<String> expectedRows = Arrays.asList(
          "[ID=1, FirstName=Bruce, LastName=Wayne, LastFirst=Wayne, Bruce, City=Gotham, LastFirstLen=12, Salary=1000000.0000, MonthlySalary=83333.3333, IsRich=true, AllNames=Wayne, Bruce=Wayne, Bruce, WeeklySalary=19230.7692307692, SalaryTest=1000000.0000, BoolTest=true, Popularity=50.325000, DecimalTest=50.325000, FloatTest=2583.2092, BigNumTest=56505085819.424791296572280180]",
          "[ID=2, FirstName=Bart, LastName=Simpson, LastFirst=Simpson, Bart, City=Springfield, LastFirstLen=13, Salary=-1.0000, MonthlySalary=-0.0833, IsRich=false, AllNames=Simpson, Bart=Simpson, Bart, WeeklySalary=-0.0192307692307692, SalaryTest=-1.0000, BoolTest=true, Popularity=-36.222200, DecimalTest=-36.222200, FloatTest=0.0035889593, BigNumTest=-0.0784734499180612994241100748]",
          "[ID=3, FirstName=John, LastName=Doe, LastFirst=Doe, John, City=Nowhere, LastFirstLen=9, Salary=0.0000, MonthlySalary=0.0000, IsRich=false, AllNames=Doe, John=Doe, John, WeeklySalary=0, SalaryTest=0.0000, BoolTest=true, Popularity=0.012300, DecimalTest=0.012300, FloatTest=0.0, BigNumTest=0E-8]",
          "[ID=4, FirstName=Test, LastName=User, LastFirst=User, Test, City=Hockessin, LastFirstLen=10, Salary=100.0000, MonthlySalary=8.3333, IsRich=false, AllNames=User, Test=User, Test, WeeklySalary=1.92307692307692, SalaryTest=100.0000, BoolTest=true, Popularity=102030405060.654321, DecimalTest=102030405060.654321, FloatTest=1.27413E-10, BigNumTest=2.787019289824216980830E-7]");

      assertEquals(expectedRows, rows);

      db.close();
    }    
  }
 
Example 8
Source File: IndexCodesTest.java    From jackcess with Apache License 2.0 6 votes vote down vote up
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();
  }
 
Example 9
Source File: IndexCodesTest.java    From jackcess with Apache License 2.0 6 votes vote down vote up
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();
  }
 
Example 10
Source File: IndexCodesTest.java    From jackcess with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 11
Source File: AutoNumberTest.java    From jackcess with Apache License 2.0 5 votes vote down vote up
public void testAutoNumberPK() throws Exception 
{
  for (final TestDB testDB : SUPPORTED_DBS_TEST) {
    Database db = openMem(testDB);

    Table table = db.getTable("Table3");

    doTestAutoNumber(table);

    db.close();
  }
}
 
Example 12
Source File: DatabaseReadWriteTest.java    From jackcess with Apache License 2.0 5 votes vote down vote up
public void testWriteAndReadInBatch() throws Exception {
  for (final FileFormat fileFormat : SUPPORTED_FILEFORMATS) {
    Database db = createMem(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();
  }
}
 
Example 13
Source File: JoinerTest.java    From jackcess with Apache License 2.0 5 votes vote down vote up
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);
  }    
}
 
Example 14
Source File: WorshipHimParser.java    From Quelea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a list of the songs contained in the given pack.
 *
 * @param location the location of the txt file.
 * @return a list of the songs found.
 */
@Override
public List<SongDisplayable> getSongs(File location, StatusPanel statusPanel) {
    List<SongDisplayable> ret = new ArrayList<>();
    try {
        Database d = new DatabaseBuilder()
                .setCharset(Charset.forName("CP1252"))
                .setReadOnly(true)
                .setFile(location)
                .open();
        Table table = d.getTable("Song list");
        for (Row row : table) {
            String title = row.get("Song").toString();
            if(title.trim().isEmpty()) continue; //Ignore empty titled songs
            String author = row.get("Author name").toString();
            StringBuilder lyricsBuilder = new StringBuilder();
            addToLyrics(lyricsBuilder, "Verse", 1, row.get("Stanza 1"));
            for (int i = 1; i <= 5; i++) {
                addToLyrics(lyricsBuilder, "Chorus", i, row.get("Refrain " + i));
            }
            for (int i = 2; i <= 13; i++) {
                addToLyrics(lyricsBuilder, "Verse", i, row.get("Stanza " + i));
            }
            for (int i = 1; i <= 5; i++) {
                addToLyrics(lyricsBuilder, "Bridge", i, row.get("Bridge " + i));
            }
            String lyrics = lyricsBuilder.toString().trim();

            SongDisplayable song = new SongDisplayable(title, author);
            song.setLyrics(lyrics);
            ret.add(song);
        }
    } catch (IOException ex) {
        LOGGER.log(Level.WARNING, "Error importing worship hymn library", ex);
    }
    return ret;
}
 
Example 15
Source File: SongProParser.java    From Quelea with GNU General Public License v3.0 4 votes vote down vote up
/**
     * Parse the file to get the songs.
     * <p>
     * @param file the Songs.SDB file.
     * @param statusPanel the status panel to update.
     * @return a list of the songs found in the Songs.SDB file.
     * @throws IOException if something went wrong with the import.
     */
    @Override
    public List<SongDisplayable> getSongs(File file, StatusPanel statusPanel) throws IOException {
        List<SongDisplayable> ret = new ArrayList<>();
        Database db = new DatabaseBuilder(file).setCharset(Charset.forName("ISO-8859-1")).setReadOnly(true).open();
        Table table = db.getTable("Chorus");
        int total = table.getRowCount();
        int iter = 0;
        for (Row r1 : table) {
            statusPanel.setProgress((double) iter / total);
            String title = r1.getString("Title");
            String author = r1.getString("Author");
            String copyright = r1.getString("Copyright");
            String key = r1.getString("Key");
            String comments = r1.getString("Comments");
//                String sequence = r1.getString("Sequence"); //TODO: For future use when we implement song sequences?

            StringBuilder lyrics = new StringBuilder();
            for (int i = 1; i <= 8; i++) {
                String versesec = getSection("Verse " + i, r1.getString("Verse" + i));
                if (versesec != null && !versesec.trim().isEmpty()) {
                    lyrics.append(versesec);
                }
            }
            String chorussec = getSection("Chorus", r1.getString("Chorus"));
            if (chorussec != null && !chorussec.trim().isEmpty()) {
                lyrics.append(chorussec);
            }
            String bridgesec = getSection("Bridge", r1.getString("Bridge"));
            if (bridgesec != null && !bridgesec.trim().isEmpty()) {
                lyrics.append(bridgesec);
            }

            SongDisplayable song = new SongDisplayable(title, author);
            song.setLyrics(lyrics.toString().trim());
            song.setKey(key);
            song.setInfo(comments);
            song.setCopyright(copyright);
            ret.add(song);
            iter++;
        }
        statusPanel.done();
        return ret;
    }
 
Example 16
Source File: JobEntryMSAccessBulkLoad.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
private boolean importFile( String sourceFilename, String delimiter, String targetFilename, String tablename,
  Result result, Job parentJob ) {
  boolean retval = false;

  try {

    incrFilesToProcess();

    File sourceDataFile = new File( sourceFilename );
    File targetDbFile = new File( targetFilename );

    // create database if needed
    if ( !targetDbFile.exists() ) {
      Database.create( targetDbFile );
      logBasic( BaseMessages.getString( PKG, "JobEntryMSAccessBulkLoad.Log.DbCreated", targetFilename ) );
    } else {
      // Database exists
      Database db = Database.open( targetDbFile );
      logBasic( BaseMessages.getString( PKG, "JobEntryMSAccessBulkLoad.Log.DbOpened", targetFilename ) );
      // Let's check table
      if ( db.getTable( tablename ) != null ) {
        logBasic( BaseMessages.getString( PKG, "JobEntryMSAccessBulkLoad.Log.TableExists", tablename ) );
      }

      // close database
      if ( db != null ) {
        db.close();
      }
      logBasic( BaseMessages.getString( PKG, "JobEntryMSAccessBulkLoad.Log.DbCosed", targetFilename ) );
    }
    // load data from file
    Database.open( targetDbFile ).importFile( tablename, sourceDataFile, delimiter );

    logBasic( BaseMessages.getString(
      PKG, "JobEntryMSAccessBulkLoad.Log.FileImported", sourceFilename, tablename, targetFilename ) );

    // add filename to result filename
    if ( add_result_filenames ) {
      addFileToResultFilenames( sourceFilename, result, parentJob );
    }

    retval = true;
  } catch ( Exception e ) {
    logError( BaseMessages.getString(
      PKG, "JobEntryMSAccessBulkLoad.Error.LoadingDataToFile", sourceFilename, targetFilename, e.getMessage() ) );

  }
  if ( retval ) {
    incrSuccess();
  } else {
    incrErrors();
  }
  return retval;
}
 
Example 17
Source File: ImportTest.java    From jackcess with Apache License 2.0 4 votes vote down vote up
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());
  }
}
 
Example 18
Source File: LongValueTest.java    From jackcess with Apache License 2.0 4 votes vote down vote up
public void testUnicodeCompression() throws Exception
{
  File dbFile = new File("src/test/data/V2003/testUnicodeCompV2003.mdb");
  Database db = open(Database.FileFormat.V2003, new File("src/test/data/V2003/testUnicodeCompV2003.mdb"), true);

  StringBuilder sb = new StringBuilder(127);
  for(int i = 1; i <= 0xFF; ++i) {
    sb.append((char)i);
  }
  String longStr = sb.toString();

  String[] expectedStrs = {
    "only ascii chars",
    "\u00E4\u00E4kk\u00F6si\u00E4",
    "\u041C\u0438\u0440",
    "\u03F0\u03B1\u1F76 \u03C4\u1F79\u03C4' \u1F10\u03B3\u1F7C \u039A\u1F7B\u03F0\u03BB\u03C9\u03C0\u03B1",
    "\u6F22\u5B57\u4EEE\u540D\u4EA4\u3058\u308A\u6587",
    "3L9\u001D52\u0002_AB(\u00A5\u0005!!V",
    "\u00FCmlaut",
    longStr
  };

  Table t = db.getTable("Table");
  for(Row row : t) {
    int id = (Integer)row.get("ID");
    String str = (String)row.get("Unicode");
    assertEquals(expectedStrs[id-1], str);
  }


  ColumnImpl col = (ColumnImpl)t.getColumn("Unicode");

  ByteBuffer bb = col.write(longStr, 1000);

  assertEquals(longStr.length() + 2, bb.remaining());

  byte[] bytes = new byte[bb.remaining()];
  bb.get(bytes);
  assertEquals(longStr, col.read(bytes));


  longStr = longStr.replace('a', '\u0440');

  bb = col.write(longStr, 1000);

  assertEquals(longStr.length() * 2, bb.remaining());

  bytes = new byte[bb.remaining()];
  bb.get(bytes);
  assertEquals(longStr, col.read(bytes));
  

  db.close();
}
 
Example 19
Source File: OleBlobTest.java    From jackcess with Apache License 2.0 4 votes vote down vote up
public void testReadBlob() throws Exception
{
  for(TestDB testDb : TestDB.getSupportedForBasename(Basename.BLOB, true)) {
    Database db = open(testDb);

    Table t = db.getTable("Table1");

    for(Row row : t) {

      OleBlob oleBlob = null;
      try {

        String name = row.getString("name");
        oleBlob = row.getBlob("ole_data");
        OleBlob.Content content = oleBlob.getContent();
        Attachment attach = null;
        if(content.getType() != OleBlob.ContentType.LINK) {
          attach = row.getForeignKey("attach_data").getAttachments().get(0);
        }

        switch(content.getType()) {
        case LINK:
          OleBlob.LinkContent lc = (OleBlob.LinkContent)content;
          if("test_link".equals(name)) {
            assertEquals("Z:\\jackcess_test\\ole\\test_data.txt", lc.getLinkPath());
          } else {
            assertEquals("Z:\\jackcess_test\\ole\\test_datau2.txt", lc.getLinkPath());
          }
          break;

        case SIMPLE_PACKAGE:
          OleBlob.SimplePackageContent spc = (OleBlob.SimplePackageContent)content;
          byte[] packageBytes = toByteArray(spc.getStream(), spc.length());
          assertTrue(Arrays.equals(attach.getFileData(), packageBytes));
          break;

        case COMPOUND_STORAGE:
          OleBlob.CompoundContent cc = (OleBlob.CompoundContent)content;
          if(cc.hasContentsEntry()) {
            OleBlob.CompoundContent.Entry entry = cc.getContentsEntry();
            byte[] entryBytes = toByteArray(entry.getStream(), entry.length());
            assertTrue(Arrays.equals(attach.getFileData(), entryBytes));
          } else {

            if("test_word.doc".equals(name)) {
              checkCompoundEntries(cc,
                                   "/%02OlePres000", 466,
                                   "/WordDocument", 4096,
                                   "/%05SummaryInformation", 4096,
                                   "/%05DocumentSummaryInformation", 4096,
                                   "/%03AccessObjSiteData", 56,
                                   "/%02OlePres001", 1620,
                                   "/1Table", 6380,
                                   "/%01CompObj", 114,
                                   "/%01Ole", 20);
              checkCompoundStorage(cc, attach);
            } else if("test_excel.xls".equals(name)) {
              checkCompoundEntries(cc,
                                   "/%02OlePres000", 1326,
                                   "/%03AccessObjSiteData", 56,
                                   "/%05SummaryInformation", 200,
                                   "/%05DocumentSummaryInformation", 264,
                                   "/%02OlePres001", 4208,
                                   "/%01CompObj", 107,
                                   "/Workbook", 13040,
                                   "/%01Ole", 20);
              // the excel data seems to be modified when embedded as ole,
              // so we can't reallly test it against the attachment data
            } else {
              throw new RuntimeException("unexpected compound entry " + name);
            }
          }
          break;

        case OTHER:
          OleBlob.OtherContent oc = (OleBlob.OtherContent)content;
          byte[] otherBytes = toByteArray(oc.getStream(), oc.length());
          assertTrue(Arrays.equals(attach.getFileData(), otherBytes));
          break;

        default:
          throw new RuntimeException("unexpected type " + content.getType());
        }

      } finally {
        ByteUtil.closeQuietly(oleBlob);
      }
    }

    db.close();
  }
}
 
Example 20
Source File: CustomLinkResolverTest.java    From jackcess with Apache License 2.0 4 votes vote down vote up
public void testCustomLinkResolver() throws Exception {
  for(final FileFormat fileFormat : SUPPORTED_FILEFORMATS) {
    Database db = create(fileFormat);

    db.setLinkResolver(new TestLinkResolver());

    db.createLinkedTable("Table1", "testFile1.txt", "Table1");
    db.createLinkedTable("Table2", "testFile2.txt", "OtherTable2");
    db.createLinkedTable("Table3", "missingFile3.txt", "MissingTable3");
    db.createLinkedTable("Table4", "testFile2.txt", "MissingTable4");

    Table t1 = db.getTable("Table1");
    assertNotNull(t1);
    assertNotSame(db, t1.getDatabase());

    assertTable(createExpectedTable(createExpectedRow("id", 0,
                                                      "data1", "row0"),
                                    createExpectedRow("id", 1,
                                                      "data1", "row1"),
                                    createExpectedRow("id", 2,
                                                      "data1", "row2")),
                t1);

    Table t2 = db.getTable("Table2");
    assertNotNull(t2);
    assertNotSame(db, t2.getDatabase());

    assertTable(createExpectedTable(createExpectedRow("id", 3,
                                                      "data2", "row3"),
                                    createExpectedRow("id", 4,
                                                      "data2", "row4"),
                                    createExpectedRow("id", 5,
                                                      "data2", "row5")),
                t2);

    assertNull(db.getTable("Table4"));

    try {
      db.getTable("Table3");
      fail("FileNotFoundException should have been thrown");
    } catch(FileNotFoundException e) {
      // success
    }

    db.close();
  }
}