rapture.repo.integration.PgIndexCreationTest.java Source code

Java tutorial

Introduction

Here is the source code for rapture.repo.integration.PgIndexCreationTest.java

Source

/**
 * Copyright (C) 2011-2015 Incapture Technologies LLC
 *
 * This is an autogenerated license statement. When copyright notices appear below
 * this one that copyright supercedes this statement.
 *
 * Unless required by applicable law or agreed to in writing, software is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied.
 *
 * Unless explicit permission obtained in writing this software cannot be distributed.
 */
package rapture.repo.integration;

import static org.junit.Assert.assertEquals;

import rapture.common.ActivityIndexInfo;
import rapture.common.ActivityPathBuilder;
import rapture.kernel.Kernel;
import rapture.object.storage.ObjectStorage;
import rapture.postgres.PostgresFactory;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.postgresql.util.PGobject;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;

import rapture.config.MultiValueConfigLoader;

/**
 * @author bardhi
 * @since 4/22/15.
 */
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class PgIndexCreationTest {
    private static final Logger log = Logger.getLogger(PgUnversionedRepoTest.class);
    private NamedParameterJdbcTemplate jdbcTemplate;

    @BeforeClass
    public static void beforeClass() throws Exception {

        String cmd = "createdb " + getDbName();
        log.info(String.format("running [%s]", cmd));
        Runtime.getRuntime().exec(cmd.split(" "));
    }

    @AfterClass
    public static void afterClass() throws Exception {
        String cmd = "dropdb " + getDbName();
        log.info(String.format("running [%s]", cmd));
        Runtime.getRuntime().exec(cmd.split(" "));
    }

    @Before
    public void before() {
        jdbcTemplate = createTemplate();
        try {
            jdbcTemplate.update("DROP INDEX activity_default", new MapSqlParameterSource());
        } catch (Exception e) {
            log.debug(e);
        }
    }

    @After
    public void after() {
        jdbcTemplate.update("DELETE FROM activity", new MapSqlParameterSource());
    }

    public static String getDbName() {
        return "integration";
    }

    @Test
    public void test1() throws Exception {
        int insertCount = 25;
        List<String> result = setup(insertCount);
        assertEquals(
                String.format("result has size %s, content:\n[%s]", result.size(), StringUtils.join(result, "\n")),
                0, result.size());
    }

    @Test
    public void test2() throws Exception {
        int insertCount = 24;
        List<String> result = setup(insertCount);
        assertEquals(
                String.format("result has size %s, content:\n[%s]", result.size(), StringUtils.join(result, "\n")),
                1, result.size());
    }

    @Test
    public void test3() throws Exception {
        int insertCount = 25;
        List<String> result = setup(insertCount);
        assertEquals(
                String.format("result has size %s, content:\n[%s]", result.size(), StringUtils.join(result, "\n")),
                0, result.size());

        ObjectStorage.getRepo(ActivityPathBuilder.getRepoName(), new ActivityIndexInfo()).getIndexHandler().get()
                .ensureIndicesExist();
        result = getData();
        assertEquals(
                String.format("result has size %s, content:\n[%s]", result.size(), StringUtils.join(result, "\n")),
                1, result.size());
    }

    private List<String> setup(int insertCount) throws SQLException, NoSuchFieldException, IllegalAccessException {
        Kernel.initBootstrap();
        setPreInsertLimit();
        initIndexHandler();

        for (int i = 0; i < insertCount; i++) {
            insertValue(jdbcTemplate, i);
        }

        setPostInsertLimit();
        initIndexHandler();

        return getData();
    }

    private void setPostInsertLimit() throws NoSuchFieldException, IllegalAccessException {
        setInsertLimit("25");
    }

    private void setPreInsertLimit() throws NoSuchFieldException, IllegalAccessException {
        setInsertLimit("0");
    }

    private void setInsertLimit(String limit) throws NoSuchFieldException, IllegalAccessException {
        Field field = MultiValueConfigLoader.class.getDeclaredField("knownAssignments");
        field.setAccessible(true);
        Map<String, Map<String, String>> knownAssignments = new HashMap<String, Map<String, String>>();
        field.set(MultiValueConfigLoader.INSTANCE, knownAssignments);

        System.setProperty("POSTGRES-DEFAULT.INDEXCREATELIMIT", limit);
    }

    private List<String> getData() {
        RowMapper<String> rowMapper = new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                ResultSetMetaData md = rs.getMetaData();
                StringBuilder sb = new StringBuilder();
                for (int i = 1; i <= md.getColumnCount(); i++) {
                    Object value = rs.getObject(i);
                    if (value != null) {
                        sb.append(value.toString()).append("; ");
                    }
                }
                return sb.toString();
            }
        };

        String sql = "    SELECT *\n" + "    FROM   pg_class tc\n"
                + "    JOIN   pg_namespace n ON n.oid = tc.relnamespace\n"
                + "    JOIN   pg_index i ON tc.oid = i.indrelid\n"
                + "    JOIN   pg_class ic ON i.indexrelid = ic.oid\n" + "    WHERE  tc.relname = :rel_name\n"
                + "    AND    n.nspname = 'public'\n" + "    AND    ic.relname = :index_name\n";
        String indexName = "activity_" + new ActivityIndexInfo().getIndexDefinitions().get(0).getIndexName();
        return jdbcTemplate.query(sql,
                new MapSqlParameterSource("rel_name", "activity").addValue("index_name", indexName), rowMapper);
    }

    private void initIndexHandler() {
        ObjectStorage.getRepo(ActivityPathBuilder.getRepoName(), new ActivityIndexInfo()).getIndexHandler().get()
                .initialize();

    }

    private void insertValue(NamedParameterJdbcTemplate jdbcTemplate, int i) throws SQLException {
        String value = String.format(
                "{\"id\": "
                        + "\"%s\", \"max\": 2, \"message\": \"what upz\", \"lastSeen\": 12345, \"progress\": 1}",
                i);
        PGobject valueJson = new PGobject();
        valueJson.setType("jsonb");
        valueJson.setValue(value);
        SqlParameterSource params = new MapSqlParameterSource().addValue("keyIn", "key" + i).addValue("contentIn",
                valueJson);
        jdbcTemplate.update("INSERT INTO activity\n" + "VALUES(:keyIn, :contentIn, now());\n", params);
    }

    private NamedParameterJdbcTemplate createTemplate() {
        return new NamedParameterJdbcTemplate(PostgresFactory.getDataSource("default"));
    }

}