net.java.ao.test.jdbc.H2Server Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of activeobjects-test Show documentation
Show all versions of activeobjects-test Show documentation
This is a library for Active Objects users to depend on for their own testing.
package net.java.ao.test.jdbc;
import com.google.common.io.Files;
import org.h2.tools.Server;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Configuration settings for the H2 instance, which is running
* as a TCP server.
*/
public class H2Server extends H2 {
private static final File TEMP_DIR = Files.createTempDir();
private static final String DEFAULT_URL = makeDefaultUrl();
private static Server h2Server;
private static Lock h2ServerLock = new ReentrantLock();
private static String makeDefaultUrl() {
StringBuilder url = new StringBuilder("jdbc:h2:tcp:");
url.append("//localhost/").append(TEMP_DIR).append("/ao-test");
//In this mode some compatibility features for applications written for H2 1.X are enabled. This mode doesn't provide full compatibility with H2 1.X.
//For eg, Empty IN, TOP clause, MINUS, IDENTITY, etc
if (h2VersionCompareTo(2, 1, 200) >= 0) {
url.append(";MODE=LEGACY");
}
appendDriverSettings(url);
return url.toString();
}
public H2Server() {
super(DEFAULT_URL);
}
public H2Server(String url, String username, String password, String schema) {
super(url, username, password, schema);
}
@Override
protected String getDefaultUrl() {
return DEFAULT_URL;
}
@Override
public void init() {
h2ServerLock.lock();
try {
if (h2Server == null) {
// launch an H2 server if there isn't one
try {
h2Server = Server.createTcpServer(getTcpServerParams()).start();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
} finally {
h2ServerLock.unlock();
}
}
private static String[] getTcpServerParams() {
List params = new ArrayList<>();
params.add("-baseDir");
params.add(TEMP_DIR.getPath());
if (h2VersionCompareTo(1, 4, 198) >= 0) {
// 1.4.198+ requires -ifNotExists to allow clients to auto-create a DB
params.add("-ifNotExists");
}
return params.toArray(new String[0]);
}
}