Java Code Examples for com.j256.ormlite.jdbc.JdbcConnectionSource

The following examples show how to use com.j256.ormlite.jdbc.JdbcConnectionSource. These examples are extracted from open source projects. 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 Project: PacketProxy   Source File: Database.java    License: Apache License 2.0 6 votes vote down vote up
private void createDB() throws Exception
{
	PacketProxyUtility util = PacketProxyUtility.getInstance();
	if (! Files.exists(databaseDir)) {
		util.packetProxyLog(databaseDir.toAbsolutePath() + " directory is not found...");
		util.packetProxyLog("creating the directory...");
		Files.createDirectories(databaseDir);
		System.out.println("success!");
	} else {
		if (! Files.isDirectory(databaseDir)) {
			util.packetProxyLogErr(databaseDir.toAbsolutePath() + " file is not directory...");
			util.packetProxyLogErr("Must be a directory");
			System.exit(1);
		}
	}

	System.setProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY, "error");
	source = new JdbcConnectionSource(getDatabaseURL());
	DatabaseConnection conn = source.getReadWriteConnection();
	conn.executeStatement("pragma auto_vacuum = full", DatabaseConnection.DEFAULT_RESULT_FLAGS);
}
 
Example 2
Source Project: PacketProxy   Source File: Database.java    License: Apache License 2.0 6 votes vote down vote up
public void saveWithoutLog(String path) throws Exception
{
	setChanged();
	notifyObservers(DatabaseMessage.PAUSE);
	clearChanged();

	Path src = databasePath;
	Path dest = FileSystems.getDefault().getPath(path);
	Files.copy(src,  dest, StandardCopyOption.REPLACE_EXISTING);
	JdbcConnectionSource new_db = new JdbcConnectionSource("jdbc:sqlite:"+dest);
	DatabaseConnection conn = new_db.getReadWriteConnection();
	conn.executeStatement("delete from packets", DatabaseConnection.DEFAULT_RESULT_FLAGS);
	conn.close();
	new_db.close();

	setChanged();
	notifyObservers(DatabaseMessage.RESUME);
	clearChanged();
}
 
Example 3
public OrmLiteSqlStorage(String backend, String path) {
    if (StringUtils.isBlank(backend)) {
        throw new ConfigurationException("storage.backend");
    }

    if (StringUtils.isBlank(path)) {
        throw new ConfigurationException("Storage destination cannot be empty");
    }

    withCatcher(() -> {
        ConnectionSource connPool = new JdbcConnectionSource("jdbc:" + backend + ":" + path);
        invDao = createDaoAndTable(connPool, ThreePidInviteIO.class);
        expInvDao = createDaoAndTable(connPool, HistoricalThreePidInviteIO.class);
        sessionDao = createDaoAndTable(connPool, ThreePidSessionDao.class);
        asTxnDao = createDaoAndTable(connPool, ASTransactionDao.class);
    });
}
 
Example 4
public static void main(String[] args) throws Exception {
  if (args.length != 1) {
    System.err.println("CreateTables (database name)");
    System.exit(1);
  }
  String databaseName = args[0];

  int exitCode = 0;

  String databaseUrl = ManagerFactory.DATABASE_URL.replace("/mitro", "/" + databaseName);
  JdbcConnectionSource connection = new JdbcConnectionSource(databaseUrl);
  try {
    Manager.createTablesIfNotExists(connection);
  } catch (SQLException e) {
    exitCode = 1;
    System.err.println("Failed: Some exception was thrown:");
    e.printStackTrace(System.err);
  } finally {
    connection.close();
  }
  System.exit(exitCode);
}
 
Example 5
@Before
public void memorySetUp() throws SQLException, CyclicGroupError, CryptoError, MitroServletException {
  // Create a fake SecretsBundle
  TwoFactorSigningService.initialize(SecretsBundle.generateForTest());
  groupToPrivateKeyMap = Maps.newHashMap();
  JdbcConnectionSource connectionSource = new JdbcConnectionSource(DATABASE_URL);
  connectionSource.getReadWriteConnection().executeStatement(
      "DROP ALL OBJECTS", DatabaseConnection.DEFAULT_RESULT_FLAGS);
  managerFactory = new ManagerFactory(DATABASE_URL, new Manager.Pool(),
      ManagerFactory.IDLE_TXN_POLL_SECONDS, TimeUnit.SECONDS, ConnectionMode.READ_WRITE);
  manager = managerFactory.newManager();
  testIdentityKey = keyFactory.generate();
  testIdentity = createIdentity("[email protected]", testIdentityKey);
  testIdentityLoginToken = GetMyPrivateKey.makeLoginTokenString(testIdentity, null, null);
  testIdentityLoginTokenSignature = testIdentityKey.sign(testIdentityLoginToken);

  testIdentity2 = createIdentity("[email protected]", null);
     
  testGroup = createGroupContainingIdentity(testIdentity);
  manager.commitTransaction();

  // remove the audit log that commit writes so that tests start with an empty log
  connectionSource.getReadWriteConnection().executeStatement(
      "DELETE FROM audit;", DatabaseConnection.DEFAULT_RESULT_FLAGS);
  connectionSource.getReadWriteConnection().commit(null);
}
 
Example 6
@Test
public void testTimeZone() throws SQLException {
  // create a temporary H2 connection
  JdbcConnectionSource connection = new JdbcConnectionSource("jdbc:h2:mem:");
  TableUtils.createTable(connection, DBEmailQueue.class);
  Dao<DBEmailQueue, Integer> dao = DaoManager.createDao(connection, DBEmailQueue.class);

  DBEmailQueue email = DBEmailQueue.makeInvitation("[email protected]", "[email protected]", "pw");
  dao.create(email);

  // Force a daylight savings time string in the DB
  setRawDate(connection, email.getId(), "2013-05-17T14:47:59.864022");
  Date t = dao.queryForId(email.getId()).getAttemptedTime();
  assertEquals("2013-05-17T14:47:59.864Z", DBEmailQueue.getUtcIsoFormat().format(t));
  assertEquals(1368802079864L, t.getTime());

  // Set a date/time in standard time, not daylight time
  setRawDate(connection, email.getId(), "2013-11-04T15:38:11.997012");
  t = dao.queryForId(email.getId()).getAttemptedTime();
  assertEquals("2013-11-04T15:38:11.997Z", DBEmailQueue.getUtcIsoFormat().format(t));
  assertEquals(1383579491997L, t.getTime());
}
 
Example 7
public LocalSqliteDriverImpl(String sqlite_filename) throws MaeDBException {
    SQLITE_FILENAME = sqlite_filename;
    logger = LoggerFactory.getLogger(this.getClass().getName() + SQLITE_FILENAME);
    try {
        cs = new JdbcConnectionSource(JDBC_DRIVER + SQLITE_FILENAME);
        idHandler = new IdHandler();
        this.setupDatabase(cs);
        // put a placeholder for task metadata in DB
        workingTask = new Task(SQLITE_FILENAME);
        taskDao.create(workingTask);
    } catch (SQLException e) {
        throw catchSQLException(e);
    }
    logger.info("New JDBC SQLite Driver is initialized, using a local file: " + SQLITE_FILENAME);
    workChanged = false;

}
 
Example 8
Source Project: ormlite-jdbc   Source File: BaseJdbcDatabaseTypeTest.java    License: ISC License 6 votes vote down vote up
@Test
public void testFileSystem() throws Exception {
	File dbDir = new File(DB_DIRECTORY);
	TestUtils.deleteDirectory(dbDir);
	dbDir.mkdirs();
	assertEquals(0, dbDir.list().length);
	closeConnectionSource();
	String dbUrl = "jdbc:h2:" + dbDir.getPath() + "/" + DATABASE_NAME;
	connectionSource = new JdbcConnectionSource(dbUrl);
	DatabaseConnection conn = connectionSource.getReadWriteConnection(null);
	try {
		databaseType = DatabaseTypeUtils.createDatabaseType(dbUrl);
		assertTrue(dbDir.list().length != 0);
	} finally {
		connectionSource.releaseConnection(conn);
	}
}
 
Example 9
Source Project: ormlite-jdbc   Source File: H2DatabaseTypeTest.java    License: ISC License 6 votes vote down vote up
@Test(expected = SQLException.class)
public void testRemotePort() throws Exception {
	File dbDir = new File(DB_DIRECTORY);
	TestUtils.deleteDirectory(dbDir);
	dbDir.mkdirs();
	// bad port
	int notTheRightPort = 12345;
	closeConnectionSource();
	// try to disable the retry feature which delays this test failure
	System.setProperty("h2.socketConnectRetry", "0");
	String dbUrl = "jdbc:h2:tcp://localhost:" + notTheRightPort + "/" + dbDir.getPath() + "/" + DATABASE_NAME;
	connectionSource = new JdbcConnectionSource(dbUrl);
	DatabaseConnection conn = connectionSource.getReadOnlyConnection(null);
	try {
		DatabaseTypeUtils.createDatabaseType(dbUrl);
	} finally {
		connectionSource.releaseConnection(conn);
	}
}
 
Example 10
private void tryCreateTables() {
  try {
    JdbcConnectionSource connectionSource = new JdbcConnectionSource(databaseUrl);
    try {
      Manager.createTablesIfNotExists(connectionSource);
    } finally {
      connectionSource.closeQuietly();
    }
  } catch (SQLException e) {
    // TODO: Don't just ignore this?
    logger.error("Exception while creating tables:", e);
  }
}
 
Example 11
/**
 * Returns a new manager, registered with the connection pool.
 *
 * TODO: Rethink the Manager/Factory/Pool interfaces; it is hard to use
 * pooled Managers correctly: technically, this should be locked/unlocked
 * when used, since the Pool periodically checks for idle managers.
 */
public Manager newManager() throws SQLException {
  // TODO: Use a different DB for the auditConnection?
  JdbcConnectionSource connection = new JdbcConnectionSource(databaseUrl);
  // we use a separate connection so it is a different transaction
  JdbcConnectionSource auditConnection = new JdbcConnectionSource(databaseUrl);

  // TODO: support creating unpooled connections?
  Manager m = new Manager(pool, connection, auditConnection, mode);
  pool.addManagerToPool(m);
  return m;
}
 
Example 12
@Test
public void readOnlyAuditLog() throws Exception {
  // create an organization to test that path
  createOrganization(testIdentity, testIdentity.getName(), 
      Lists.newArrayList(testIdentity), Lists.newArrayList(testIdentity));

  // this must be a disk db for reopening as read-only to work (it seems)
  // Another alternative would be to create a read-only user, but I can't get that to work either
  final String PATH = tempFolder.newFile().getAbsolutePath();
  final String OTHER_DB_URL = "jdbc:h2:file:" + PATH + ";DATABASE_TO_UPPER=FALSE";
  // create a ManagerFactory just to create the tables (yuck)
  new ManagerFactory(OTHER_DB_URL, new Manager.Pool(), ManagerFactory.IDLE_TXN_POLL_SECONDS, TimeUnit.SECONDS, ManagerFactory.ConnectionMode.READ_WRITE);

  // create a read-only connection for the audit log
  JdbcConnectionSource readOnlyConnection = new JdbcConnectionSource(
      OTHER_DB_URL + ";ACCESS_MODE_DATA=r");
  try {
    readOnlyConnection.getReadWriteConnection().executeStatement(
        "UPDATE email_queue SET arg_string='';", DatabaseConnection.DEFAULT_RESULT_FLAGS);
    fail("expected exception");
  } catch (JdbcSQLException e) {
    assertThat(e.getMessage(), CoreMatchers.containsString("database is read only"));
  }
  Manager readOnlyAuditManager = new Manager(
      new Manager.Pool(),
      (JdbcConnectionSource) manager.identityDao.getConnectionSource(),
      readOnlyConnection,
      ManagerFactory.ConnectionMode.READ_WRITE);

  assertEquals(1, manager.auditDao.countOf());
  StatsGenerator.Snapshot output = StatsGenerator.generateStatistics(null, readOnlyAuditManager);
  assertEquals(1, manager.auditDao.countOf());
  assertEquals(2, output.userStateObjects.size());
  assertEquals(1, output.orgStateObjects.size());
}
 
Example 13
public void setRawDate(JdbcConnectionSource connection, int emailQueueId, String dateTimeString)
    throws SQLException {
  // Do a raw update to ensure we get the right time string in the DB
  String raw = String.format("UPDATE email_queue SET attempted_time='%s' WHERE id=%d",
      dateTimeString, emailQueueId);
  int result = connection.getReadWriteConnection().executeStatement(
      raw, DatabaseConnection.DEFAULT_RESULT_FLAGS);
  // updates 1 row
  assertEquals(1, result);
}
 
Example 14
Source Project: ormlite-jdbc   Source File: DerbyEmbeddedDatabaseTypeTest.java    License: ISC License 5 votes vote down vote up
@Override
protected void setDatabaseParams() throws SQLException {
	System.setProperty("derby.stream.error.file", "target/derby.log");
	databaseUrl = "jdbc:derby:target/ormlitederby;create=true";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new DerbyEmbeddedDatabaseType();
}
 
Example 15
Source Project: passopolis-server   Source File: Manager.java    License: GNU General Public License v3.0 4 votes vote down vote up
public Manager(ManagerPool pool, JdbcConnectionSource connectionSource,
    JdbcConnectionSource auditConnectionSource, ManagerFactory.ConnectionMode mode)
        throws SQLException {
  this.mode = mode;
  this.sourcePool = pool;
  this.connectionSource = connectionSource;
  this.auditConnectionSource = null != auditConnectionSource ? auditConnectionSource
      : connectionSource;

  connectionSource.getReadWriteConnection().setAutoCommit(false);
  if (connectionSource.getDatabaseType() instanceof PostgresDatabaseType) {
    String type = "serializable";
    if (mode == ConnectionMode.READ_ONLY) {
      type = "repeatable read read only";
    }

    // this sets the default for all future transactions on this session:
    connectionSource.getReadWriteConnection().executeStatement(
        "set session characteristics as transaction isolation level " + type
            + ";", DatabaseConnection.DEFAULT_RESULT_FLAGS);

    // the documentation is unclear on whether the above affects the current
    // transaction,
    // so set it on the current transaction anyway.
    connectionSource.getReadWriteConnection().executeStatement(
        "set transaction isolation level " + type + ";",
        DatabaseConnection.DEFAULT_RESULT_FLAGS);
  } else {
    ; // we are not setting isolation mode
  }

  groupDao = createDao(DBGroup.class, this.connectionSource);
  aclDao = createDao(DBAcl.class, this.connectionSource);
  identityDao = createDao(DBIdentity.class, this.connectionSource);
  svsDao = createDao(DBServerVisibleSecret.class, this.connectionSource);
  groupSecretDao = createDao(DBGroupSecret.class, this.connectionSource);
  issueDao = createDao(DBIssue.class, this.connectionSource);
  emailDao = createDao(DBEmailQueue.class, this.connectionSource);
  futureAlertDao = createDao(DBFutureAlert.class, this.connectionSource);
  auditDao = createDao(DBAudit.class, this.auditConnectionSource);
  pendingGroupDao = createDao(DBPendingGroup.class, connectionSource);
  deviceSpecificDao = createDao(DBDeviceSpecificInfo.class, connectionSource);
  signupDao = createDao(DBSignup.class, this.connectionSource);
  historicalOrgDao = createDao(DBHistoricalOrgState.class, this.connectionSource);
  historicalUserDao = createDao(DBHistoricalUserState.class, this.connectionSource);
  processedAuditDao = createDao(DBProcessedAudit.class, this.connectionSource);
  userNameDao = createDao(DBUserName.class, this.connectionSource);
  emailRecordDao = createDao(DBEmailRecord.class, this.connectionSource);
  stripeCustomerDao = createDao(DBStripeCustomer.class, this.connectionSource);
  mitroAccessEmailDao = createDao(DBMitroAccessEmail.class, this.connectionSource);
}
 
Example 16
Source Project: TinkerTime   Source File: MainModule.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Singleton
@Provides
ConnectionSource getConnectionSource(DbConnectionString connectionString) throws SQLException {
	return new JdbcConnectionSource(connectionString.getUrl());
}
 
Example 17
Source Project: mae-annotation   Source File: LinkTagTest.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {

    cs = new JdbcConnectionSource(MaeStrings.DB_DRIVER + MaeStrings.newTempTestDBFile());
    setupDatabase(cs);
}
 
Example 18
Source Project: mae-annotation   Source File: ExtentTagTest.java    License: GNU General Public License v3.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {

    cs = new JdbcConnectionSource(MaeStrings.DB_DRIVER + MaeStrings.newTempTestDBFile());
    this.setupDatabase(cs);
}
 
Example 19
Source Project: ormlite-jdbc   Source File: SqliteDatabaseTypeTest.java    License: ISC License 4 votes vote down vote up
@Override
protected void setDatabaseParams() throws SQLException {
	databaseUrl = "jdbc:sqlite:";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new SqliteDatabaseType();
}
 
Example 20
Source Project: ormlite-jdbc   Source File: MariaDbDatabaseTypeTest.java    License: ISC License 4 votes vote down vote up
@Override
protected void setDatabaseParams() throws SQLException {
	databaseUrl = "jdbc:mariadb:ormlite";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new MariaDbDatabaseType();
}
 
Example 21
Source Project: ormlite-jdbc   Source File: OracleDatabaseTypeTest.java    License: ISC License 4 votes vote down vote up
@Override
protected void setDatabaseParams() throws SQLException {
	databaseUrl = "jdbc:oracle:ormliteoracle";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new OracleDatabaseType();
}
 
Example 22
Source Project: ormlite-jdbc   Source File: HsqldbDatabaseTypeTest.java    License: ISC License 4 votes vote down vote up
@Override
protected void setDatabaseParams() throws SQLException {
	databaseUrl = "jdbc:hsqldb:ormlite";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new HsqldbDatabaseType();
}
 
Example 23
@Override
protected void setDatabaseParams() throws SQLException {
	databaseUrl = "jdbc:jtds:sqlserver://db/ormlite;ssl=request";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new SqlServerJtdsDatabaseType();
}
 
Example 24
Source Project: ormlite-jdbc   Source File: Db2DatabaseTypeTest.java    License: ISC License 4 votes vote down vote up
@Override
protected void setDatabaseParams() throws SQLException {
	databaseUrl = "jdbc:db2:ormlitedb2";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new Db2DatabaseType();
}
 
Example 25
Source Project: ormlite-jdbc   Source File: PostgresDatabaseTypeTest.java    License: ISC License 4 votes vote down vote up
@Override
protected void setDatabaseParams() throws SQLException {
	databaseUrl = "jdbc:postgresql:ormlitepostgres";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new PostgresDatabaseType();
}
 
Example 26
Source Project: ormlite-jdbc   Source File: SqlServerDatabaseTypeTest.java    License: ISC License 4 votes vote down vote up
@Override
protected void setDatabaseParams() throws SQLException {
	databaseUrl = "jdbc:sqlserver:db";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new SqlServerDatabaseType();
}
 
Example 27
Source Project: ormlite-jdbc   Source File: MysqlDatabaseTypeTest.java    License: ISC License 4 votes vote down vote up
@Override
protected void setDatabaseParams() throws SQLException {
	databaseUrl = "jdbc:mysql:ormlite";
	connectionSource = new JdbcConnectionSource(DEFAULT_DATABASE_URL);
	databaseType = new MysqlDatabaseType();
}
 
Example 28
Source Project: ormlite-jdbc   Source File: WrappedJdbcConnectionSource.java    License: ISC License 4 votes vote down vote up
public WrappedJdbcConnectionSource(JdbcConnectionSource cs) {
	super(cs);
}