h2backup.H2BackupTestBase.java Source code

Java tutorial

Introduction

Here is the source code for h2backup.H2BackupTestBase.java

Source

/*
 * Copyright 2017 Evgeniy Khyst.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package h2backup;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.h2.jdbcx.JdbcDataSource;
import org.junit.After;
import org.junit.Before;

/**
 *
 * @author evgeniy
 */
public abstract class H2BackupTestBase {

    protected static final String BUILD_DIRECTORY = System.getProperty("buildDirectory");

    protected JdbcDataSource dataSource;
    protected Path workDirectory;

    @Before
    public void baseSetUp() throws IOException, SQLException {
        workDirectory = Paths.get(BUILD_DIRECTORY, "h2-backup", UUID.randomUUID().toString());

        if (!Files.exists(workDirectory)) {
            Files.createDirectories(workDirectory);
        }

        dataSource = new JdbcDataSource();
        dataSource.setURL("jdbc:h2:" + workDirectory + "/testdb");
        dataSource.setUser("sa");
        dataSource.setPassword("sa");

        createTestTable();
    }

    @After
    public void baseTearDown() throws IOException {
        if (Files.exists(workDirectory)) {
            FileUtils.deleteDirectory(workDirectory.toFile());
        }
    }

    protected Connection getConnection() throws SQLException {
        return dataSource.getConnection("sa", "sa");
    }

    protected void createTestTable() throws SQLException {
        try (Connection conn = getConnection()) {
            PreparedStatement ps = conn.prepareStatement(
                    "CREATE TABLE test_tbl ( id IDENTITY PRIMARY KEY, description VARCHAR(255) )");
            ps.execute();
        }
    }

    protected void insertRecordIntoTestTable(String description) throws SQLException {
        try (Connection conn = getConnection()) {
            PreparedStatement ps = conn.prepareStatement("INSERT INTO test_tbl (description) VALUES (?)");
            ps.setString(1, description);
            ps.execute();
        }
    }
}