package it.inaf.ia2.gms.persistence; import it.inaf.ia2.gms.persistence.model.ClientEntity; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; @Component public class ClientsDAO { private final JdbcTemplate jdbcTemplate; @Autowired public ClientsDAO(DataSource dataSource) { jdbcTemplate = new JdbcTemplate(dataSource); } public Optional findClientById(String clientId) { String sql = "SELECT client_secret, allowed_actions, ip_filter FROM gms_client WHERE client_id = ?"; return jdbcTemplate.query(conn -> { PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1, clientId); return ps; }, resultSet -> { if (resultSet.next()) { ClientEntity client = new ClientEntity(); client.setId(clientId); client.setSecret(resultSet.getString("client_secret")); client.setAllowedActions(getAllowedActions(resultSet)); client.setIpFilter(resultSet.getString("ip_filter")); return Optional.of(client); } return Optional.empty(); }); } private List getAllowedActions(ResultSet resultSet) throws SQLException { List actions = new ArrayList<>(); ResultSet items = resultSet.getArray("allowed_actions").getResultSet(); while (items.next()) { String action = items.getString(1); actions.add(action); } return actions; } }