@Before
  public void setUp() throws Exception {
    dbi = new DBI("jdbc:h2:mem:" + UUID.randomUUID());
    dbi.registerMapper(new SomethingMapper());
    handle = dbi.open();

    handle.execute("create table something (id int primary key, name varchar(100))");
  }
  @BeforeMethod
  public void setup() throws Exception {
    H2EmbeddedDataSourceConfig dataSourceConfig =
        new H2EmbeddedDataSourceConfig().setFilename("mem:");
    DataSource dataSource = new H2EmbeddedDataSource(dataSourceConfig);
    DBI h2Dbi = new DBI(dataSource);
    handle = h2Dbi.open();
    dao = handle.attach(ShardManagerDao.class);

    ShardManagerDao.Utils.createShardTablesWithRetry(dao);
  }
  /**
   * The run method uses the Configuration and Environment references to: i. Build a DBIFactory ii.
   * Run the necessary DB pre-requisites iii. Build the Resource class and register the same.
   */
  @Override
  public void run(ExpenseManagerConfiguration configuration, Environment environment)
      throws Exception {
    log.debug("Run application");
    final DBIFactory factory = new DBIFactory();
    final DBI jdbi = factory.build(environment, configuration.getDsFactory(), "expense-database");
    final ExpenseDAO dao = jdbi.onDemand(ExpenseDAO.class);

    /*Create the underlying table/s required by the application*/
    dao.createDatabaseSchema();
    dao.createExpenseSchemaTable();

    final ExpenseManagerResource resource = new ExpenseManagerResource(dao);
    environment.jersey().register(resource);
  }
 @Override
 public void addService(
     final Optional<Draft> customerDraftOptional,
     final Optional<Draft> agreementDraftOptional,
     final Draft serviceDraft) {
   checkDraftEntityIs(SERVICES, serviceDraft);
   checkDraftStatusIs(APPROVED, serviceDraft);
   dbi.inTransaction(
       new TransactionCallback<Void>() {
         @Override
         public Void inTransaction(Handle handle, TransactionStatus status) throws Exception {
           if (customerDraftOptional.isPresent()) {
             final Draft customerDraft = customerDraftOptional.get();
             checkDraftStatusIs(APPROVED, customerDraft);
             insertCustomerOf(customerDraft, handle);
             updateDraftStatusTo(IMPORTED, customerDraft.id(), handle);
           }
           if (agreementDraftOptional.isPresent()) {
             final Draft agreementDraft = agreementDraftOptional.get();
             checkDraftStatusIs(APPROVED, agreementDraft);
             insertAgreementOf(agreementDraft, handle);
             updateDraftStatusTo(IMPORTED, agreementDraft.id(), handle);
           }
           insertServiceOf(serviceDraft, handle);
           updateDraftStatusTo(IMPORTED, serviceDraft.id(), handle);
           updateCustomerStatusOf(
               customerDraftOptional, agreementDraftOptional, serviceDraft, handle);
           return null;
         }
       });
 }
Esempio n. 5
0
 public long insertWithTxCallback(final Team team) {
   return dbi.inTransaction(
       new TransactionCallback<Long>() {
         @Override
         public Long inTransaction(Handle handle, TransactionStatus status) throws Exception {
           long teamId;
           /**
            * Notice that the onDemand dao's are not used here, but instead new instances are
            * created and attached to the same handle so that they will execute in the same TX.
            */
           TeamDao teamDao = handle.attach(TeamDao.class);
           TeamPersonDao teamPersonDao = handle.attach(TeamPersonDao.class);
           if (team.getPointOfContact() != null) {
             teamId = teamDao.insertWithPoC(team);
           } else {
             teamId = teamDao.insertWithoutPoC(team);
           }
           for (Person p : team.getMembers()) {
             // update the team->person mapping table
             teamPersonDao.insert(new TeamPerson(teamId, p.getId()));
           }
           // add test code for checking that TX is handled correctly
           checkIfTxShouldBeRolledBack(team);
           return teamId;
         }
       });
 }
Esempio n. 6
0
 private long update(final Team team) {
   // Must update 2 tables here, so will do this in a transaction
   return dbi.inTransaction(
       new TransactionCallback<Long>() {
         @Override
         public Long inTransaction(Handle conn, TransactionStatus status) throws Exception {
           // attach the dao's to the same handle
           TeamDao teamDao = conn.attach(TeamDao.class);
           TeamPersonDao teamPersonDao = conn.attach(TeamPersonDao.class);
           if (team.getPointOfContact() != null) {
             teamDao.updateWithPoC(team);
           } else {
             teamDao.updateWithoutPoC(team);
           }
           for (Person p : team.getMembers()) {
             // update the team->person mapping table
             TeamPerson tp = new TeamPerson(team.getId(), p.getId());
             if (!teamPersonDao.findByTeamId(team.getId()).contains(tp)) {
               teamPersonDao.insert(tp);
             }
           }
           return team.getId();
         }
       });
 }
Esempio n. 7
0
  public Template getByName(String name) {
    if (name == null) {
      return null;
    }

    TemplateDao dao = dbi.onDemand(TemplateDao.class);
    return dao.getByName(name);
  }
Esempio n. 8
0
  public void setUp() throws Exception {
    JdbcDataSource ds = new JdbcDataSource();
    ds.setURL("jdbc:h2:mem:test;MVCC=TRUE");
    dbi = new DBI(ds);
    handle = dbi.open();

    handle.execute("create table something (id int primary key, name varchar(100))");
  }
Esempio n. 9
0
  public boolean delete(int id) {
    if (id < 0) {
      return false;
    }

    TemplateDao dao = dbi.onDemand(TemplateDao.class);
    return dao.delete(id) > 0;
  }
Esempio n. 10
0
  public Template getById(int id) {
    if (id < 0) {
      return null;
    }

    TemplateDao dao = dbi.onDemand(TemplateDao.class);
    return dao.getById(id);
  }
Esempio n. 11
0
  public List<Template> query(int id) {
    if (id < 0) {
      return null;
    }

    TemplateDao dao = dbi.onDemand(TemplateDao.class);
    return dao.query(id);
  }
  @Before
  public void setUp() throws Exception {
    UUID uuid = UUID.randomUUID();
    dbi = new DBI("jdbc:h2:mem:" + uuid);
    handle = dbi.open();

    handle.execute("create table something (id int primary key, name varchar(100))");
  }
  @Ignore
  @Test
  public void testGetGeneratedKeys() throws Exception {
    DAO dao = dbi.open(DAO.class);

    Long fooId = dao.insert("Foo");
    long barId = dao.insert("Bar");

    assertThat(dao.findNameById(fooId), equalTo("Foo"));
    assertThat(dao.findNameById(barId), equalTo("Bar"));
  }
 @After
 public void tearDown() throws Exception {
   dbi.withHandle(
       new HandleCallback<Object>() {
         public Object withHandle(Handle handle) throws Exception {
           handle.execute("drop table something");
           handle.execute("drop sequence something_id_sequence");
           return null;
         }
       });
 }
 @Override
 public Service addService(final Service service) {
   return dbi.withHandle(
       new HandleCallback<Service>() {
         @Override
         public Service withHandle(Handle handle) throws Exception {
           log.debug("inserting service '{}'", service.id().value());
           insertRecordWithoutKey(SERVICES_TABLE, service.record(), handle);
           return new Service(getRecord(SERVICES_TABLE, service.id().value(), handle));
         }
       });
 }
 @Override
 public Agreement add(final Agreement agreement) {
   return dbi.withHandle(
       new HandleCallback<Agreement>() {
         @Override
         public Agreement withHandle(Handle handle) throws Exception {
           log.debug("inserting agreement '{}'", agreement.id().value());
           insertRecordWithoutKey(AGREEMENTS_TABLE, agreement.record(), handle);
           return new Agreement(getRecord(AGREEMENTS_TABLE, agreement.id().value(), handle));
         }
       });
 }
  @Test
  public void testTransactionPropagates() throws Exception {
    Foo foo = dbi.onDemand(Foo.class);

    try {
      foo.insertAndFail(1, "Jeff");
      fail("should have raised an exception");
    } catch (Exception e) {
    }
    Something n = foo.createBar().findById(1);
    assertThat(n, nullValue());
  }
Esempio n. 18
0
  public H2QueryRunner() {
    handle = DBI.open("jdbc:h2:mem:test" + System.nanoTime());
    TpchMetadata tpchMetadata = new TpchMetadata("");

    handle.execute(
        "CREATE TABLE orders (\n"
            + "  orderkey BIGINT PRIMARY KEY,\n"
            + "  custkey BIGINT NOT NULL,\n"
            + "  orderstatus CHAR(1) NOT NULL,\n"
            + "  totalprice DOUBLE NOT NULL,\n"
            + "  orderdate DATE NOT NULL,\n"
            + "  orderpriority CHAR(15) NOT NULL,\n"
            + "  clerk CHAR(15) NOT NULL,\n"
            + "  shippriority BIGINT NOT NULL,\n"
            + "  comment VARCHAR(79) NOT NULL\n"
            + ")");
    handle.execute("CREATE INDEX custkey_index ON orders (custkey)");
    TpchTableHandle ordersHandle =
        tpchMetadata.getTableHandle(
            null, new SchemaTableName(TINY_SCHEMA_NAME, ORDERS.getTableName()));
    insertRows(
        tpchMetadata.getTableMetadata(ordersHandle),
        handle,
        createTpchRecordSet(ORDERS, ordersHandle.getScaleFactor()));

    handle.execute(
        "CREATE TABLE lineitem (\n"
            + "  orderkey BIGINT,\n"
            + "  partkey BIGINT NOT NULL,\n"
            + "  suppkey BIGINT NOT NULL,\n"
            + "  linenumber BIGINT,\n"
            + "  quantity BIGINT NOT NULL,\n"
            + "  extendedprice DOUBLE NOT NULL,\n"
            + "  discount DOUBLE NOT NULL,\n"
            + "  tax DOUBLE NOT NULL,\n"
            + "  returnflag CHAR(1) NOT NULL,\n"
            + "  linestatus CHAR(1) NOT NULL,\n"
            + "  shipdate DATE NOT NULL,\n"
            + "  commitdate DATE NOT NULL,\n"
            + "  receiptdate DATE NOT NULL,\n"
            + "  shipinstruct VARCHAR(25) NOT NULL,\n"
            + "  shipmode VARCHAR(10) NOT NULL,\n"
            + "  comment VARCHAR(44) NOT NULL,\n"
            + "  PRIMARY KEY (orderkey, linenumber)"
            + ")");
    TpchTableHandle lineItemHandle =
        tpchMetadata.getTableHandle(
            null, new SchemaTableName(TINY_SCHEMA_NAME, LINE_ITEM.getTableName()));
    insertRows(
        tpchMetadata.getTableMetadata(lineItemHandle),
        handle,
        createTpchRecordSet(LINE_ITEM, lineItemHandle.getScaleFactor()));
  }
Esempio n. 19
0
  public boolean insert(Template template) {
    if (template == null) {
      return false;
    }

    Handle handle = dbi.open();
    try {
      TemplateDao db = handle.attach(TemplateDao.class);
      return db.insertBean(template) > 0;
    } finally {
      handle.close();
    }
  }
 @Before
 public void setUp() throws Exception {
   dbi = new DBI("jdbc:oracle:thin:@localhost:test", "oracle", "oracle");
   dbi.withHandle(
       new HandleCallback<Object>() {
         public Object withHandle(Handle handle) throws Exception {
           handle.execute("create sequence something_id_sequence INCREMENT BY 1 START WITH 100");
           handle.execute(
               "create table something (name varchar(200), id int, constraint something_id primary key (id))");
           return null;
         }
       });
 }
  @Test
  public void testTxActuallyCommits() throws Exception {
    Handle h2 = dbi.open();
    Dao one = handle.attach(Dao.class);
    Dao two = h2.attach(Dao.class);

    // insert in @Transaction method
    Something inserted = one.insertAndFetch(1, "Brian");

    // fetch from another connection
    Something fetched = two.findById(1);
    assertThat(fetched, equalTo(inserted));
  }
  @Test
  public void testConcurrent() throws Exception {
    ExecutorService es = Executors.newFixedThreadPool(3);

    final CountDownLatch inserted = new CountDownLatch(1);
    final CountDownLatch committed = new CountDownLatch(1);

    final Other o = dbi.onDemand(Other.class);
    Future<Void> rf =
        es.submit(
            new Callable<Void>() {
              @Override
              public Void call() throws Exception {
                try {
                  o.insert(inserted, 1, "diwaker");
                  committed.countDown();

                  return null;
                } catch (Exception e) {
                  e.printStackTrace();
                  fail(e.getMessage());
                  return null;
                }
              }
            });

    Future<Void> tf =
        es.submit(
            new Callable<Void>() {
              @Override
              public Void call() throws Exception {
                try {
                  inserted.await();
                  committed.await();

                  Something s2 = o.find(1);
                  assertThat(s2, equalTo(new Something(1, "diwaker")));
                  return null;
                } catch (Exception e) {
                  e.printStackTrace();
                  fail(e.getMessage());
                  return null;
                }
              }
            });

    rf.get();
    tf.get();

    es.shutdown();
  }
  @Inject
  public DatabaseProjectStoreManager(DBI dbi, ConfigMapper cfm, DatabaseConfig config) {
    super(config.getType(), dao(config.getType()), dbi);

    dbi.registerMapper(new StoredProjectMapper(cfm));
    dbi.registerMapper(new StoredRevisionMapper(cfm));
    dbi.registerMapper(new StoredWorkflowDefinitionMapper(cfm));
    dbi.registerMapper(new StoredWorkflowDefinitionWithProjectMapper(cfm));
    dbi.registerMapper(new WorkflowConfigMapper());
    dbi.registerMapper(new IdNameMapper());
    dbi.registerMapper(new ScheduleStatusMapper());
    dbi.registerArgumentFactory(cfm.getArgumentFactory());

    this.cfm = cfm;
  }
 private boolean detectSchema(final DBI dbi, final String schemaName) {
   return dbi.withHandle(
       new HandleCallback<Boolean>() {
         @Override
         public Boolean withHandle(final Handle handle) {
           return handle
                   .createQuery("#mojo:detect_schema")
                   .bind("schema_name", schemaName)
                   .map(IntegerMapper.FIRST)
                   .first()
               != 0;
         }
       });
 }
Esempio n. 25
0
  public void testJustJdbiTransactions() throws Exception {
    Handle h1 = dbi.open();
    Handle h2 = dbi.open();

    h1.execute("insert into something (id, name) values (8, 'Mike')");

    h1.begin();
    h1.execute("update something set name = 'Miker' where id = 8");

    assertEquals(
        "Mike",
        h2.createQuery("select name from something where id = 8").map(StringMapper.FIRST).first());
    h1.commit();
    h1.close();
    h2.close();
  }
 @Override
 public Customer addCustomer(final Customer customer) {
   return dbi.withHandle(
       new HandleCallback<Customer>() {
         @Override
         public Customer withHandle(Handle handle) throws Exception {
           log.debug("inserting service '{}'", customer.id().value());
           final Map<String, Object> record = Maps.newHashMap(customer.record());
           final DateTime now = DateTime.now();
           record.put("inserted_on", now);
           record.put("updated", now);
           record.put("history_id", lastValueOf(AUDIT_TABLE, "history_id", handle) + 1);
           // TODO: insert audit item on history
           insertRecordWithoutKey(CUSTOMERS_TABLE, record, handle);
           return new Customer(getRecord(CUSTOMERS_TABLE, customer.id().value(), handle));
         }
       });
 }
Esempio n. 27
0
  public static void createTable(final DBI dbi, final String tableName, final String sql) {
    try {
      dbi.withHandle(
          new HandleCallback<Void>() {
            @Override
            public Void withHandle(Handle handle) throws Exception {
              List<Map<String, Object>> table =
                  handle.select(String.format("SHOW tables LIKE '%s'", tableName));

              if (table.isEmpty()) {
                log.info("Creating table[%s]", tableName);
                handle.createStatement(sql).execute();
              } else {
                log.info("Table[%s] existed: [%s]", tableName, table);
              }

              return null;
            }
          });
    } catch (Exception e) {
      log.warn(e, "Exception creating table");
    }
  }
Esempio n. 28
0
 @Bean
 @Autowired
 public VisitEntryLogRepository visitEntryLogRepository(DBI dbi) {
   return dbi.onDemand(VisitEntryLogRepository.class);
 }
Esempio n. 29
0
 @Bean
 @Autowired
 public VendorRepository vendorRepository(DBI dbi) {
   return dbi.onDemand(VendorRepository.class);
 }
Esempio n. 30
0
 @Bean
 @Autowired
 public ServiceOfferingRepository serviceOfferingRepository(DBI dbi) {
   return dbi.onDemand(ServiceOfferingRepository.class);
 }