package whelk.export.servlet;

import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.SQLException;

public class DataBase {

    private static HikariDataSource dataSource;
    private static final Logger logger = LoggerFactory.getLogger(DataBase.class);

    /**
     * Initialize the db connection pool.
     */
    public static void init()
    {
        /*
        Extracts the components of a JDBC url, and reconstructs it without username and password,
        username and password being passed as parameters instead.
        */

        dataSource = new HikariDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");

        final String jdbcUrlPrefix = "jdbc:postgresql://";
        final String rawJdbcUrl = OaiPmh.configuration.getProperty("sqlUrl");

        if (!rawJdbcUrl.startsWith(jdbcUrlPrefix))
        {
            logger.error("Incorrect JDBC connection string. Check secret.properties.");
            return;
        }

        final int userAndPassPartBeginsAt = jdbcUrlPrefix.length();
        final int urlPartBeginsAt = rawJdbcUrl.indexOf("@") + 1;

        final String userAndPass = rawJdbcUrl.substring(userAndPassPartBeginsAt, urlPartBeginsAt - 1);
        final String urlPart = rawJdbcUrl.substring(urlPartBeginsAt);

        final String[] userAndPassArray = userAndPass.split(":");
        if (userAndPassArray.length != 2)
        {
            logger.error("Expected username and password as part of the JDBC string. Check secret.properties.");
            return;
        }
        final String user = userAndPassArray[0];
        final String password = userAndPassArray[1];

        dataSource.setJdbcUrl( jdbcUrlPrefix + urlPart );
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setAutoCommit(false);
    }

    public static void destroy()
    {
        dataSource.close();
    }

    public static Connection getConnection() throws SQLException
    {
        return dataSource.getConnection();
    }
}

@@ -125,16 +125,61 @@
 ctory;%0A%0A
+import java.io.UnsupportedEncodingException;%0A
 import j
@@ -1663,24 +1663,25 @@
       %7D%0A
+%0A
         
 final St
@@ -1676,101 +1676,380 @@
     
-final String user = userAndPassArray%5B0%5D;%0A        final String password = userAndPassArray%5B1%5D;
+String user;%0A        String password;%0A        try %7B%0A            user = java.net.URLDecoder.decode(userAndPassArray%5B0%5D, %22UTF-8%22);%0A            password = java.net.URLDecoder.decode(userAndPassArray%5B1%5D, %22UTF-8%22);%0A        %7D catch (UnsupportedEncodingException e)%0A        %7B%0A            logger.error(%22Could not URL decode username/password: %22 + e);%0A            return;%0A        %7D
 %0A%0A  

Add URL decoding of username and password from properties.