package uk.ac.ebi.biosamples.service;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApiKeyService {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	@Qualifier("accessionJdbcTemplate")
    protected JdbcTemplate jdbcTemplate;
	
	public Optional<String> getDomainForApiKey(String apiKey) throws DataAccessException {
		log.info("getting domain for apikey "+apiKey);
		return Optional.ofNullable(jdbcTemplate.queryForObject("SELECT AAPDOMAIN FROM USERS WHERE LIKE APIKEY ?", String.class, apiKey));
	}
}

@@ -32,16 +32,96 @@
 rvice;%0A%0A
+import java.sql.ResultSet;%0Aimport java.sql.SQLException;%0Aimport java.util.List;%0A
 import j
@@ -139,16 +139,16 @@
 tional;%0A
-
 %0Aimport 
@@ -426,16 +426,64 @@
 mplate;%0A
+import org.springframework.jdbc.core.RowMapper;%0A
 import o
@@ -854,65 +854,24 @@
 y);%0A
+%0A
 %09%09
-return Optional.ofNullable(jdbcTemplate.queryForObject(
+String stm = 
 %22SEL
@@ -905,49 +905,419 @@
 ERE 
-LIKE AP
+APIKEY L
 IKE
-Y
  ?%22
-, String.class, apiKey));%0A%09%7D
+;%0A    %09List%3CString%3E results = jdbcTemplate.query(stm, new SingleStringRowMapper(), apiKey);%0A    %09if (results.size() == 0) %7B%0A    %09%09return Optional.empty();%0A    %09%7D else %7B%0A    %09%09return Optional.of(results.get(0));%0A    %09%7D%0A%09%7D%0A%0A%09protected class SingleStringRowMapper implements RowMapper%3CString%3E%0A%09%7B%0A%09%09public String mapRow(ResultSet rs, int rowNum) throws SQLException %7B%0A%09%09%09return rs.getString(1);%0A%09%09%7D%0A%09%7D%0A
 %0A%7D%0A

fix sql