All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.lontime.extpac4j.sql.profile.DbProfileService Maven / Gradle / Ivy

There is a newer version: 1.4.0
Show newest version
package com.github.lontime.extpac4j.sql.profile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.github.lontime.extjdbi.JdbiInstance;
import com.github.lontime.extpac4j.impl.DefaultPasswordEncoder;
import com.github.lontime.extpac4j.sql.DbProfile;
import com.github.lontime.extpac4j.sql.DbProfileServiceSerializer;
import org.jdbi.v3.core.Jdbi;
import org.pac4j.core.credentials.password.PasswordEncoder;
import org.pac4j.core.profile.definition.CommonProfileDefinition;
import org.pac4j.core.profile.service.AbstractProfileService;
import org.pac4j.core.util.CommonHelper;

/**
 * The DB profile service (which supersedes the DB authenticator).
 *
 * @author Jerome Leleu
 * @since 2.0.0
 */
public class DbProfileService extends AbstractProfileService {

    protected Jdbi jdbi;

    private String usersTable = "users";

    private String dsName;

    public DbProfileService() {
        this(null);
    }

    public DbProfileService(final String dsName) {
        this(dsName, null, null);
    }

    public DbProfileService(final String dsName, final String attributes) {
        this(dsName, attributes, null);
    }

    public DbProfileService(final String dsName, final String attributes, final PasswordEncoder passwordEncoder) {
        this.dsName = dsName;
        if (attributes != null) {
            setAttributes(attributes);
        }
        if (passwordEncoder == null) {
            setPasswordEncoder(new DefaultPasswordEncoder());
        } else {
            setPasswordEncoder(passwordEncoder);
        }
    }

    public DbProfileService(final String dsName, final PasswordEncoder passwordEncoder) {
        this.dsName = dsName;
        setPasswordEncoder(passwordEncoder);
    }

    @Override
    protected void internalInit() {
        CommonHelper.assertNotNull("passwordEncoder", getPasswordEncoder());
        defaultProfileDefinition(new CommonProfileDefinition<>(x -> new DbProfile()));
        this.jdbi = JdbiInstance.get().getJdbi(dsName);
        setSerializer(new DbProfileServiceSerializer());

        super.internalInit();
    }

    @Override
    protected void insert(final Map attributes) {
        final List names = new ArrayList<>();
        final List values = new ArrayList<>();
        for (final Map.Entry entry : attributes.entrySet()) {
            names.add(entry.getKey());
            values.add(entry.getValue());
        }

        jdbi.withHandle(handle -> handle.createUpdate("INSERT INTO  () VALUES ()")
                .define("table", usersTable)
                .define("columns", buildAttributesList(names))
                .bindList("values", values)
                .execute());
//        final String query = "insert into " + usersTable + " (" + buildAttributesList(names) + ") values ("
//            + buildAttributesList(questionMarks) + ")";
//        execute(query, values.toArray());
    }

    @Override
    protected void update(final Map attributes) {
        final StringBuilder attributesList = new StringBuilder();
        String id = null;
        int i = 0;
        final Map mapValues = new HashMap<>();
        for (final Map.Entry entry : attributes.entrySet()) {
            final String name = entry.getKey();
            final Object value = entry.getValue();
            if (ID.equals(name)) {
                id = (String) value;
            } else {
                if (i > 0) {
                    attributesList.append(",");
                }
                attributesList.append(name);
                attributesList.append("= :");
                attributesList.append(name);
                mapValues.put(name, value);
                i++;
            }
        }

        CommonHelper.assertNotNull(ID, id);
        mapValues.put(ID, id);

        jdbi.withHandle(handle -> handle.createUpdate("update 
set where = :" + ID) .define("table", usersTable) .define("idColumn", getIdAttribute()) .define("columns", attributesList.toString()) .bindMap(mapValues) .execute()); // final String query = "update " + usersTable + " set " + attributesList.toString() + " where " + getIdAttribute() + " = :id"; // execute(query, values.toArray()); } @Override protected void deleteById(final String id) { jdbi.withHandle(handle -> handle.createUpdate("delete from
where = :id") .define("table", usersTable) .define("idColumn", getIdAttribute()) .bind("id", id) .execute()); // final String query = "delete from " + usersTable + " where " + getIdAttribute() + " = :id"; // execute(query, id); } // protected void execute(final String query, final Object... args) { // Handle h = null; // try { // h = jdbi.open(); // logger.debug("Execute query: {} and values: {}", query, args); // h.execute(query, args); // } finally { // if (h != null) { // h.close(); // } // } // } @Override protected List> read(final List names, final String key, final String value) { final String attributesList = buildAttributesList(names); return jdbi.withHandle(handle -> handle.createQuery("select from
where = :value") .define("table", usersTable) .define("columns", attributesList) .define("keyColumn", key) .bind("value", value) .mapToMap().list()); // final String query = "select " + attributesList + " from " + usersTable + " where " + key + " = :" + key; // return query(query, key, value); } // protected List> query(final String query, final String key, final String value) { // Handle h = null; // try { // h = jdbi.open(); // logger.debug("Query: {} for key/value: {} / {}", query, key, value); // return h.createQuery(query).bind(key, value).list(2); // } finally { // if (h != null) { // h.close(); // } // } // } protected String buildAttributesList(final List names) { final StringBuilder sb = new StringBuilder(); boolean firstOne = true; for (final String name : names) { if (!firstOne) { sb.append(","); } sb.append(name); firstOne = false; } return sb.toString(); } public String getUsersTable() { return usersTable; } public void setUsersTable(final String usersTable) { CommonHelper.assertNotBlank("usersTable", usersTable); this.usersTable = usersTable; } public Jdbi getJdbi() { return jdbi; } @Override public String toString() { return CommonHelper.toNiceString(this.getClass(), "dataSource", "passwordEncoder", getPasswordEncoder(), "attributes", getAttributes(), "profileDefinition", getProfileDefinition(), "usersTable", usersTable, "idAttribute", getIdAttribute(), "usernameAttribute", getUsernameAttribute(), "passwordAttribute", getPasswordAttribute()); } }