package eu.dnetlib.repos;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.unboundid.util.Base64;

import eu.dnetlib.domain.data.Repository;
import eu.dnetlib.domain.data.RepositoryInterface;
//import java.io.UnsupportedEncodingException;


public class RepoApiDirectImpl implements RepoApi {
	private static Logger logger = Logger.getLogger(RepoApiDirectImpl.class);
	private DataSource openAireDataSource = null;

	@Override
	public Repository getRepository(String id) throws Exception {
		return this.getRepository(null,id);
	}

	public Repository getRepository(String officialName, String id) throws SQLException {
		Connection conn = null;
		Repository repo = null;
		
		try {
			logger.info("getting repository " + officialName + " from openaire db");

			conn = openAireDataSource.getConnection();
			PreparedStatement stm = null, stm1 = null;
			stm = conn.prepareStatement("SELECT * FROM datasources d WHERE d.id = ?");
			stm.setString(1, id);				

			ResultSet rs = stm.executeQuery();

			if (rs.next()) {
				repo = new Repository();
				repo.setId(rs.getString("Id"));
				repo.setOfficialName(rs.getString("officialname"));
				repo.setEnglishName(rs.getString("englishname"));
				repo.setWebsiteUrl(rs.getString("websiteurl"));
				repo.setLogoUrl(rs.getString("logourl"));
				repo.setContactEmail(rs.getString("contactemail"));
				repo.setLatitude(rs.getDouble("latitude"));
				repo.setLongitude(rs.getDouble("longitude"));
				repo.setTimezone(rs.getDouble("timezone"));
				repo.setNamespacePrefix(rs.getString("namespaceprefix"));
				repo.setDescription(rs.getString("description"));
				repo.setCollectedFrom(rs.getString("collectedfrom"));
//				repo.setOptional1(rs.getString("optional1"));
//				repo.setOptional2(rs.getString("optional2"));
				repo.setActivationId("activationid");
				repo.setTypology(rs.getString("typology"));
				repo.setDatasourceClass(rs.getString("datasourceClass"));
				repo.setProvenanceActionClass(rs.getString("provenanceactionclass"));
				repo.setDateOfCollection(rs.getDate("dateofcollection"));
				repo.setIssn(rs.getString("issn"));
				repo.setEissn(rs.getString("eissn"));
				repo.setLissn(rs.getString("lissn"));
				
				rs.close();
				stm.close();
				
				stm = conn.prepareStatement("SELECT * FROM api a WHERE a.datasource = ? ORDER BY id");
				stm.setString(1, repo.getId());

				rs = stm.executeQuery();

				logger.debug("searching api");
				while (rs.next()) {
					RepositoryInterface iFace = new RepositoryInterface();
					if (rs.getBoolean("useedited")) {
						iFace.setBaseUrl(rs.getString("edited"));
						iFace.setAccessProtocol(rs.getString("editedprotocolclass"));
					}
					else {
						iFace.setBaseUrl(rs.getString("original"));
						iFace.setAccessProtocol(rs.getString("originalprotocolclass"));
					}
//					repo.setApiTypology(rs.getString("typology"));
					iFace.setId(rs.getString("id"));
					String apiId = rs.getString("id");
					logger.debug("apiId: "+ apiId);
					
					stm1 = conn.prepareStatement("SELECT * FROM apicollections ac WHERE ac.api = ?");
					stm1.setString(1, apiId);

					ResultSet rs1 = stm1.executeQuery();
					String setEdited = null;
					iFace.setAccessSet("none");
					logger.debug("searching apicollections");
					while (rs1.next()) {				
					
						if (rs1.getString("accessparam").equals("SET")) {
							iFace.setAccessSet(rs1.getString("accessvalue"));
						} else if (rs1.getString("accessparam").equals("SET_EDITED")) {
							setEdited = rs1.getString("accessvalue");
						} else if (rs1.getString("accessparam").equals("FORMAT")) {
							iFace.setAccessFormat(rs1.getString("accessvalue"));
						}
					}
					if (setEdited != null)
						iFace.setAccessSet(setEdited);
					
					if (iFace.getAccessSet().equalsIgnoreCase("driver")) {
						iFace.setCompliance("Driver");
					} else if (iFace.getAccessSet().equalsIgnoreCase("ec_fundedresources")) {
						iFace.setCompliance("OpenAIRE 2.0");
					} else if (iFace.getAccessSet().equalsIgnoreCase("openaire")) {
						iFace.setCompliance("OpenAIRE 3.0");
					} else if (iFace.getAccessSet().equalsIgnoreCase("openaire_data")) {
						iFace.setCompliance("OpenAIRE 3.0");
					} else if (iFace.getAccessSet().equalsIgnoreCase("none")) {
						iFace.setCompliance("notCompatible");
					} else {
						iFace.setCompliance("UNKNOWN");
					}
						
					rs1.close();
					stm1.close();
					repo.getInterfaces().add(iFace);
				}
				
				rs.close();
				stm.close();
				
//				stm = conn.prepareStatement("select legal_name from datasources, organizations, datasources_organizations where datasourceid=datasource and organizationid=organization and official_name = ?");
				stm = conn.prepareStatement("SELECT o.legalname, o.countryclass FROM datasources d, organizations o, datasource_organization dor WHERE dor.datasource=d.id AND o.id=dor.organization AND d.id = ?");
				stm.setString(1, id);
				rs = stm.executeQuery();

				if (rs.next()) {
					repo.setOrganization(rs.getString(1));
					repo.setCountryCode(rs.getString(2));
				}

				rs.close();
				stm.close();
			}
		} catch (SQLException e) {
			logger.error("Error getting repo " + officialName + " from openaire db", e);
			throw e;
		}  
		finally {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error("Error closing connection", e);
				}
		}

		return repo;
	}

	@Override
	public String storeRepository(Repository repo, String datatype,  List<RepositoryInterface> interfacesToRegister) throws Exception {
		String retMessage = null;
		Connection conn = null;
		try {
			conn = openAireDataSource.getConnection();
			PreparedStatement stm = null;
			ResultSet rs = null;
			
			logger.info("storing " + datatype + " repository..");
			if (datatype.equalsIgnoreCase("opendoar")) {
				
				
				logger.debug("updating datasources values..");
				
				stm = conn.prepareStatement("UPDATE datasources SET englishname = ?, logourl = ?, timezone = ?, optional1 = ?, activationid = ?, contactemail = ? WHERE id = ?");
				stm.setString(1, repo.getEnglishName());
				stm.setString(2, repo.getLogoUrl());
				stm.setDouble(3, repo.getTimezone());
				stm.setString(4, repo.getRegisteredBy());
				stm.setString(5, repo.getActivationId());
				stm.setString(6, repo.getContactEmail());
				stm.setString(7, repo.getId());
				
				if (stm.executeUpdate() > 0 ) {
					logger.debug("finished updating values in datasources..");
					stm.close();
					conn.commit();
				}
				
				logger.debug("checking current values in api..");
				
				stm = conn.prepareStatement("SELECT COUNT(*) FROM api WHERE datasource = ?");
				stm.setString(1, repo.getId());
				rs = stm.executeQuery();
				int noCurrentInApi = 0;
				if (rs.next()) {
					noCurrentInApi = rs.getInt(1);
				}
				stm.close();
				rs.close();
				
				
				for (RepositoryInterface iFace : repo.getInterfaces()) {
					logger.debug("checking if interface : " + iFace.getId() + " already exists in api..");
					stm = conn.prepareStatement("SELECT * FROM api WHERE datasource = ? AND id = ?");
					stm.setString(1, repo.getId());
					stm.setString(2, iFace.getId());
					rs = stm.executeQuery();
					
					if (!rs.next()) {
						logger.debug("not exist..");
						stm.close();
						rs.close();
						
						stm = conn.prepareStatement("INSERT INTO api (id, typology, originalprotocolclass, original, datasource, _dnet_resource_identifier_)  VALUES (?,?,?,?,?,?)");
						iFace.setId("api_________::" + repo.getId() + "::" + noCurrentInApi);
						logger.debug("creating new api_id: " + iFace.getId());
						noCurrentInApi++;
						
						String apiTypology = "UNKNOWN";
						if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire3.0") || iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire2.0_data") || iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire2.0")) {
							apiTypology = "openaire";
						} else if (iFace.getDesiredCompatibilityLevel().contains("driver")) {
							apiTypology = "driver";
						}
						stm.setString(1, iFace.getId());
						stm.setString(2, apiTypology);
						stm.setString(3, iFace.getAccessProtocol());
						stm.setString(4, iFace.getBaseUrl());
						stm.setString(5, repo.getId());
						stm.setString(6, iFace.getId());
						
						if (stm.executeUpdate() > 0) {
							logger.debug(iFace.getId() + " inserted in api..");
							logger.debug("now inserting in apicollections..");
							stm.close();
							rs.close();
							conn.commit();
		
							stm = conn.prepareStatement("INSERT INTO apicollections (accessparam, accessvalue, api, _dnet_resource_identifier_)  VALUES (?,?,?,?)");
							
							stm.setString(1,"FORMAT");
							stm.setString(2, iFace.getAccessFormat());
							stm.setString(3, iFace.getId());
							stm.setString(4,"FORMAT" + "@@" + iFace.getAccessFormat() + "@@" + iFace.getId());
							
							stm.addBatch();
	
							stm.setString(1,"SET");
							stm.setString(2, iFace.getAccessSet());
							stm.setString(3, iFace.getId());
							stm.setString(4,"SET" + "@@" + iFace.getAccessSet() + "@@" + iFace.getId());
									
							stm.addBatch();
						
							if (stm.executeBatch()[0] > 0) {
								logger.debug(iFace.getId() + " inserted in apicollections.");
							}
							logger.debug("finished updating set + format values in apicollections.");
							stm.close();
							conn.commit();
						}
							
					} else {
						
						logger.debug("exists..");
						boolean edited = false;
						if( rs.getString("original") == null || rs.getString("originalprotocolclass") == null || !rs.getString("original").equalsIgnoreCase(iFace.getBaseUrl()) || !rs.getString("originalprotocolclass").equalsIgnoreCase(iFace.getAccessProtocol()) ) {
							edited = true;
						}
							logger.debug("updating edited values in api..");
							stm.close();
							rs.close();
							
							String apiTypology = "UNKNOWN";
							if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire3.0") || iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire2.0")) {
								apiTypology = "openaire";
							} else if (iFace.getDesiredCompatibilityLevel().contains("driver")) {
								apiTypology = "driver";
							}
								
							stm = conn.prepareStatement("UPDATE api SET typology = ?, edited = ?, editedprotocolclass = ?, useedited = ?  WHERE datasource = ? AND id = ? ");
							stm.setString(1, apiTypology);
							if (edited) {
								stm.setString(2, iFace.getBaseUrl());
								stm.setString(3, iFace.getAccessProtocol());
								stm.setBoolean(4, true);
							} else {
								stm.setString(2, null);
								stm.setString(3, null);
								stm.setBoolean(4, false);
							}
							stm.setString(5, repo.getId());
							stm.setString(6, iFace.getId());
							
							if (stm.executeUpdate() > 0 ) {
								logger.debug("finished updating values in api..");
								stm.close();
								conn.commit();
							}
						logger.debug("updating apicollections..");
						
						logger.debug("deleting current values from apicollections..");
						stm = conn.prepareStatement("DELETE FROM apicollections WHERE api = ?");
						
						stm.setString(1, iFace.getId());
						
						if (stm.executeUpdate() > 0) {
							logger.debug("values for interface " + iFace.getId() + " deleted from api_collections..");
							stm.close();
							rs.close();
							conn.commit();
							
						}
							logger.debug("now inserting in apicollections..");
		
							stm = conn.prepareStatement("INSERT INTO apicollections (accessparam, accessvalue, api, _dnet_resource_identifier_)  VALUES (?,?,?,?)");
							
							stm.setString(1,"FORMAT");
							stm.setString(2, iFace.getAccessFormat());
							stm.setString(3, iFace.getId());
							stm.setString(4,"FORMAT" + "@@" + iFace.getAccessFormat() + "@@" + iFace.getId());
							
							stm.addBatch();
	
							stm.setString(1,"SET");
							stm.setString(2, iFace.getAccessSet());
							stm.setString(3, iFace.getId());
							stm.setString(4,"SET" + "@@" + iFace.getAccessSet() + "@@" + iFace.getId());
								
							stm.addBatch();
							
							if (stm.executeBatch()[0] > 0) {
								logger.debug(iFace.getId() + " inserted in apicollections.");
							}
							logger.debug("finished updating set + format values in apicollections.");
							stm.close();
							conn.commit();
					
					}	
					logger.debug("interface : " + iFace.getId() + " inserted successfully..");
				}			
						
			} else if (datatype.equalsIgnoreCase("journal")||datatype.equalsIgnoreCase("aggregator")){		
	
					logger.debug("looking if " + datatype + " " + repo.getOfficialName() + " is already in datasources");
					stm = conn.prepareStatement("SELECT * FROM datasources WHERE officialname = ? OR id = ?");
					stm.setString(1, repo.getOfficialName());
					stm.setString(2, repo.getId());
		
					rs = stm.executeQuery();
		
					if (rs.next()) {
						retMessage = datatype + " " + repo.getOfficialName() + " is already in datasources.";
						logger.debug(retMessage);
						
						stm.close();
						rs.close();
					} else {
						logger.debug(datatype + " " + repo.getOfficialName() + " is not in datasources. Inserting..");
										
						stm = conn.prepareStatement("INSERT INTO datasources(id, officialname, englishname, websiteurl, logourl, contactemail, latitude, longitude, timezone, namespaceprefix, collectedfrom, activationid, typology, datasourceclass, provenanceactionclass, _dnet_resource_identifier_, optional1, issn, eissn, lissn, description) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
						
						stm.setString(1, repo.getId()); //activation id
						stm.setString(2, repo.getOfficialName());
						stm.setString(3, repo.getEnglishName());
						stm.setString(4, repo.getWebsiteUrl());
						stm.setString(5, repo.getLogoUrl());
						stm.setString(6, repo.getContactEmail());
						stm.setDouble(7, repo.getLatitude());
						stm.setDouble(8, repo.getLongitude());
						stm.setString(9, repo.getTimezone() + "");
						stm.setString(10, repo.getNamespacePrefix());
						stm.setString(11, repo.getCollectedFrom()); 
						stm.setString(12, repo.getActivationId()); 
						stm.setString(13, repo.getTypology()); 
						stm.setString(14, repo.getDatasourceClass());
						stm.setString(15, repo.getProvenanceActionClass());
						stm.setString(16,repo.getId());
						stm.setString(17, repo.getRegisteredBy());
						stm.setString(18, repo.getIssn());
						stm.setString(19, repo.getEissn());
						stm.setString(20, repo.getLissn());
						stm.setString(21, repo.getDescription());
						
						if (stm.executeUpdate() > 0) {
							logger.debug(datatype + " " + repo.getOfficialName() + " inserted in datasources.");
							logger.debug("inserting in api..");
							
							stm.close();
							conn.commit();
	
							
							int noCurrentInApi = 0;						
							for (RepositoryInterface iFace : repo.getInterfaces()) {
									
								stm = conn.prepareStatement("INSERT INTO api (id, typology, originalprotocolclass, original, datasource, _dnet_resource_identifier_)  VALUES (?,?,?,?,?,?)");
								iFace.setId("api_________::" + repo.getId() + "::" + noCurrentInApi);
								logger.debug("creating new api_id: " + iFace.getId());
								noCurrentInApi++;
								String apiTypology = "UNKNOWN";
								if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire3.0") || iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire2.0")) {
									apiTypology = "openaire";
								} else if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("driver")) {
									apiTypology = "driver";
								}
								stm.setString(1, iFace.getId());
								stm.setString(2, apiTypology);
								stm.setString(3, iFace.getAccessProtocol());
								stm.setString(4, iFace.getBaseUrl());
								stm.setString(5, repo.getId());
								stm.setString(6, iFace.getId());
								
								if (stm.executeUpdate() > 0) {
									logger.debug(iFace.getId() + " inserted in api..");
									logger.debug("now inserting in apicollections..");
									stm.close();
									rs.close();
									conn.commit();
				
									stm = conn.prepareStatement("INSERT INTO apicollections (accessparam, accessvalue, api, _dnet_resource_identifier_)  VALUES (?,?,?,?)");
									
									stm.setString(1,"FORMAT");
									stm.setString(2, iFace.getAccessFormat());
									stm.setString(3, iFace.getId());
									stm.setString(4,"FORMAT" + "@@" + iFace.getAccessFormat() + "@@" + iFace.getId());
									
									stm.addBatch();
	
									stm.setString(1,"SET");
									stm.setString(2, iFace.getAccessSet());
									stm.setString(3, iFace.getId());
									stm.setString(4,"SET" + "@@" + iFace.getAccessSet() + "@@" + iFace.getId());
										
									stm.addBatch();
									
									if (stm.executeBatch()[0] > 0) {
										logger.debug(iFace.getId() + " inserted in apicollections.");
									}
									logger.debug("finished updating set + format values in apicollections.");
									stm.close();
									conn.commit();
								}
									
								
								logger.debug("interface : " + iFace.getId() + " inserted successfully..");
							}			
							
							logger.debug("inserting in organizations..");
									
							stm = conn.prepareStatement("SELECT * FROM organizations WHERE id = ?");
							stm.setString(1, "openaire____::" + Base64.encode(repo.getOrganization()));
							
							ResultSet rs1 = stm.executeQuery();
							
							boolean exists = rs1.next();
							
							rs1.close();
							
							if(!exists) {
								
//								String countryCode = "UNKNOWN";
//								stm = conn.prepareStatement("SELECT code FROM class WHERE name = ?");
//								stm.setString(1,repo.getCountryName());
//								
//								rs1 = stm.executeQuery();
//								
//								if ( rs1.next()) {
//									countryCode = rs1.getString(1);
//								stm.close();
//								}
								if (repo.getCountryCode() == null) {
									repo.setCountryCode("UNKNOWN");
								}
								stm = conn.prepareStatement("INSERT INTO organizations (legalname, countryclass, id, legalshortname, collectedfrom, provenanceactionclass, _dnet_resource_identifier_) VALUES (?,?,?,?,?,?,?)");
								stm.setString(1, repo.getOrganization());
								stm.setString(2, repo.getCountryCode());
								stm.setString(3, "openaire____::" + Base64.encode(repo.getOrganization()));
								stm.setString(4, repo.getOrganization());
								stm.setString(5, repo.getCollectedFrom());
								stm.setString(6, repo.getProvenanceActionClass());
								stm.setString(7, "openaire____::" + Base64.encode(repo.getOrganization()));
								stm.executeUpdate();
								logger.debug("organization" + " openaire____::" + Base64.encode(repo.getOrganization()) + " inserted in organizations.");
								
								stm.close();
								conn.commit();
							} else {
								logger.debug("Organization "+repo.getOrganization()+" already exists");
							}
							logger.debug("inserting in datasource-organizations..");
							stm = conn.prepareStatement("INSERT INTO datasource_organization (organization, datasource, _dnet_resource_identifier_) VALUES (?,?,?)");
							stm.setString(1, "openaire____::" + Base64.encode(repo.getOrganization()));
							stm.setString(2, repo.getId());
							stm.setString(3, repo.getId() + "@@" + "openaire____::" + Base64.encode(repo.getOrganization()) );
	
							if( stm.executeUpdate()>0) {
								logger.debug("organization" + "openaire____::" + Base64.encode(repo.getOrganization()) + " inserted in datasource-organizations.");
								stm.close();
								conn.commit();
							}		
						}
						logger.debug("Finished storing " + datatype + " repository..");
					}
	
			}
		
		} catch (SQLException e) {
			logger.error("Error storing repo " + repo.getOfficialName() + " in openaire db", e);
			throw e;
		} finally {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error("Error closing connection", e);
				}
		}
		return retMessage;
	}

	public TreeMap<String, List<Map<String, String>>> getRepositoriesByCountry(String collectedFrom) throws SQLException {
		Connection conn = null;
		TreeMap<String, List<Map<String, String>>> res = new TreeMap<String, List<Map<String, String>>>();

		try {
			logger.info("getting repos by country from openaire db");
			String collFrom = null;
			if (collectedFrom.equalsIgnoreCase("opendoar")) {
				logger.debug("populating doar list");
				collFrom = "openaire____::opendoar";
			} else if (collectedFrom.equalsIgnoreCase("re3data")) {
				logger.debug("populating re3data list");
				collFrom = "openaire____::re3data";
			}
			conn = openAireDataSource.getConnection();
			PreparedStatement ps = conn.prepareStatement("SELECT DISTINCT d.id, d.officialname, c.name, d.websitEurl FROM datasources d, organizations o, datasource_organization dor, class c WHERE dor.datasource=d.id AND o.id=dor.organization AND o.countryclass=c.code AND d.collectedfrom=? ORDER BY c.name, d.officialname");
//			.prepareStatement("SELECT d.official_name, c.name, d.web_site_url FROM countries c, organizations o, datasources d, datasources_organizations dor WHERE dor.datasource=d.datasourceid AND o.organizationid=dor.organization AND o.country_of_origin = c.countryid order by c.name, d.official_name");
			ps.setString(1, collFrom);
			ResultSet rs = ps.executeQuery();

			while (rs.next()) {
				String country = rs.getString(3);
				List<Map<String, String>> repos = res.get(country);

				if (repos == null) {
					repos = new ArrayList<Map<String, String>>();
					res.put(country, repos);
				}

				Map<String, String> repo = new HashMap<String, String>();
				repo.put("name", rs.getString(2));
				repo.put("url", rs.getString(4));
				repo.put("id", rs.getString(1));
				repos.add(repo);
			}
		} catch (SQLException e) {
			logger.error("Error getting repositories from openaire db", e);
			throw e;
		} finally {
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error("Error closing connection", e);
				}
			}
		}

		return res;

	}

	@Override
	public Map<String, List<Repository>> getRepositoriesPerCountry(String collectedFrom) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public List<Repository> getRepositoriesOfCountry(String collectedFrom, String country) throws Exception {
		throw new UnsupportedOperationException();
	}

	public DataSource getOpenAireDataSource() {
		return openAireDataSource;
	}

	public void setOpenAireDataSource(DataSource openAireDataSource) {
		this.openAireDataSource = openAireDataSource;
	}

	@Override
	public List<Repository> getRepositoriesOfUser(String user_mail, Boolean repoAdmin) throws SQLException {
			Connection conn = null;
			Repository repo = null;
			List<Repository> retRepos = new ArrayList<Repository>();
			try {
				logger.info("getting repositories registered by user: " + user_mail + " from openaire db");

				conn = openAireDataSource.getConnection();
				PreparedStatement stm = conn.prepareStatement("SELECT * FROM datasources d WHERE contactemail = ? OR optional1 = ?");
				stm.setString(1, user_mail);
				stm.setString(2, user_mail);
				ResultSet rs = stm.executeQuery();

				while (rs.next()) {
					repo = new Repository();
					repo.setId(rs.getString("id"));
					repo.setOfficialName(rs.getString("officialname"));
					retRepos.add(repo);
				}
				rs.close();
				stm.close();
			} catch (Exception e) {
				logger.error("error getting repositories registered by user: " + user_mail + " from openaire db", e);
			} finally {
				try {
					if (conn != null)
						conn.close();
				} catch (Exception e) {
					logger.warn("could not close openaire db connection", e);
				}
			}
			return retRepos;
		
	}

	@Override
	public List<String> getUrlsOfRepos(String user_mail, Boolean repoAdmin) throws SQLException {				
			Connection conn = null;
			List<String> urls = new ArrayList<String>();
			try {
				logger.info("getting url from repositories registered by user: " + user_mail + " from openaire db");

				conn = openAireDataSource.getConnection();
				PreparedStatement stm = conn.prepareStatement("SELECT a.original, a.edited FROM datasources d, api a WHERE a.datasource=d.id AND ( d.optional1=? OR d.contactemail=?)");
				stm.setString(1, user_mail);
				stm.setString(2, user_mail);
				ResultSet rs = stm.executeQuery();

				while (rs.next()) {
					if (rs.getString(1) != null && !rs.getString(1).isEmpty() && !urls.contains(rs.getString(1)))
						urls.add(rs.getString(1));
					if (rs.getString(2) != null && !rs.getString(2).isEmpty() && !urls.contains(rs.getString(2)))
						urls.add(rs.getString(2));
				}
				rs.close();
				stm.close();
			} catch (Exception e) {
				logger.error("error getting url from repositories registered by user: " + user_mail + " from openaire db", e);
			} finally {
				try {
					if (conn != null)
						conn.close();
				} catch (Exception e) {
					logger.warn("could not close openaire db connection", e);
				}
			}
			return urls;
		
	}

	@Override
	public boolean insertPubFileInterface(String dsId, RepositoryInterface iFace) throws Exception {
		return false;
	}

	@Override
	public boolean updatePubFileInterface(String dsId, RepositoryInterface iFace) throws Exception {
		return false;
	}

	@Override
	public Map<String, Repository> getRepositoriesAsMap(String collectedFrom) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public List<Repository> getRepositories(String collectedFrom) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public String getNextScheduledExecution(String mode) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public String getListLatestUpdate(String mode) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public List<Repository> getReposByIds(List<String> datasourceIds) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public void getRepositoryStats(Repository repo) throws Exception {

	}

	@Override
	public String updateRepositoryInformation(Repository repo) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public String deleteRepositoryInterfaces(String dsId, List<RepositoryInterface> interfaces) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public void deleteRepositoryInterfacesWithoutChecks(String dsId, List<RepositoryInterface> interfaces, String datatype) throws Exception {

	}

	@Override
	public String updateRepositoryInterfaces(String dsId, List<RepositoryInterface> interfaces, List<RepositoryInterface> interfacesOld, String datatype, List<RepositoryInterface> interfacesToRegister) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public RepositoryInterface updateRepositoryInterfaceWithoutChecks(String dsId, RepositoryInterface iFace, String datatype) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public String insertRepositoryInterfaces(String dsId, List<RepositoryInterface> interfaces, List<RepositoryInterface> interfacesOld, String datatype, List<RepositoryInterface> interfacesToRegister) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public RepositoryInterface insertRepositoryInterfaceWithoutChecks(String dsId, RepositoryInterface iFace, String datatype) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean unregisterRepository(Repository repo) throws Exception {
		return false;
	}

	@Override
	public List<Map<String, String>> getRegisteredReposByOthers(String string) {
		throw new UnsupportedOperationException();
	}

	@Override
	public List<Map<String, String>> getRepositoriesOfUser(String user_mail) throws Exception {
		throw new UnsupportedOperationException();
	}

	@Override
	public boolean repoIsCompliant(String officialName) throws SQLException {
		boolean retCompliant = false;
		Connection conn = null;
		try {
			logger.info("checking if " + officialName + " is openaire compliant");
			conn = openAireDataSource.getConnection();
			PreparedStatement stm = conn.prepareStatement("SELECT openairecompatibilityclass FROM datasources WHERE officialname = ?");

			stm.setString(1, officialName);
			ResultSet rs = stm.executeQuery();
			if(rs.next()) {
				if (rs.getString(1).equals("UNKNOWN") || rs.getString(1).equals("notCompatible")) {
					retCompliant = false;
				} else {
					retCompliant = true;
				}
			}
			

			stm.close();

			rs.close();
			logger.debug(officialName + " is openaire compliant");
		} catch (Exception e) {
			logger.error("error connecting to openaire db to get openairecompliant for " + officialName, e);
			
		} finally {
			try {
				if (conn != null)
					conn.close();
			} catch (Exception e) {
				logger.warn("could not close openaire db connection", e);
			}
		}
		return retCompliant;

	}

	@Override
	public Map<String, String> getRepoCompatibility(String officialName, String datasourceId) throws Exception {
		Map<String, String> compMap = null;
		Connection conn = null;
		
		try {
			logger.info("getting repository " + officialName + " compatibility from openaire db");

			conn = openAireDataSource.getConnection();
			PreparedStatement stm = null;
		
			stm = conn.prepareStatement("SELECT openairecompatibilityclass FROM datasources d WHERE d.id = ?");
			stm.setString(1, datasourceId);				
			ResultSet rs = stm.executeQuery();

			compMap = new HashMap<String, String>();
			if (rs.next()) {
				String[] comp = rs.getString("openairecompatibilityclass").split("-");
				for ( String c : comp) {
					if (c.equalsIgnoreCase("driver"))
						compMap.put("driver", "driver");
                    else if (c.equalsIgnoreCase("openaire2.0")) {
						compMap.put("openaire2.0", "ec_fundedresources");
                        compMap.put("openaire2.0_data", "openaire_data");
                    }
					else if (c.equalsIgnoreCase("openaire3.0"))
						compMap.put("openaire3.0", "openaire");
					else if (c.equalsIgnoreCase("notCompatible"))
						compMap.put("notCompatible", "notCompatible");
					else if (c.equalsIgnoreCase("UNKNOWN"))
						compMap.put("UNKNOWN", "UNKNOWN");
				}
			}

			rs.close();
			stm.close();
			
		} catch (SQLException e) {
			logger.error("Error getting repo " + officialName + " compatibility from openaire db", e);
			throw e;
		}  
		finally {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error("Error closing connection", e);
				}
		}
		return compMap;
	}


	@Override
	public String editRepository(Repository repo, String officialNameOld, String idOld, String datatype) throws Exception {
	String retMessage = null;
	Connection conn = openAireDataSource.getConnection();
	PreparedStatement stm = null;
	ResultSet rs = null;
	
	logger.info("editing " + datatype + " repository..");
	if (datatype.equalsIgnoreCase("opendoar")) {
		
		logger.debug("updating datasources values for id:"+repo.getId()+" + name:" + repo.getOfficialName() );

			
		stm = conn.prepareStatement("UPDATE datasources SET englishname = ?, logourl = ?, timezone = ? WHERE officialname = ? AND id = ?");
		stm.setString(1, repo.getEnglishName());
		stm.setString(2, repo.getLogoUrl());
		stm.setDouble(3, repo.getTimezone());
		stm.setString(4, repo.getOfficialName());
		stm.setString(5, repo.getId());
		
		if (stm.executeUpdate() > 0 ) {
			logger.debug("finished updating values in datasources..");
			stm.close();
			conn.commit();
		}
		
		logger.debug("checking current values in api..");
		
		stm = conn.prepareStatement("SELECT COUNT(*) FROM api WHERE datasource = ?");
		stm.setString(1, repo.getId());
		rs = stm.executeQuery();
		int noCurrentInApi = 0;
		if (rs.next()) {
			noCurrentInApi = rs.getInt(1);
		}
		stm.close();
		rs.close();
		
		
		for (RepositoryInterface iFace : repo.getInterfaces()) {
			logger.debug("checking if interface : " + iFace.getId() + " already exists in api..");
			stm = conn.prepareStatement("SELECT * FROM api WHERE datasource = ? AND id = ?");
			stm.setString(1, repo.getId());
			stm.setString(2, iFace.getId());
			rs = stm.executeQuery();
			
			if (!rs.next()) {
				logger.debug("not exist..");
				stm.close();
				rs.close();
				
				stm = conn.prepareStatement("INSERT INTO api (id, typology, originalprotocolclass, original, datasource, _dnet_resource_identifier_)  VALUES (?,?,?,?,?,?)");
				iFace.setId("api_________::" + repo.getId() + "::" + noCurrentInApi);
				logger.debug("creating new api_id: " + iFace.getId());
				noCurrentInApi++;
				
				String apiTypology = "UNKNOWN";
				if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire3.0") || iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire2.0")) {
					apiTypology = "openaire";
				} else if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("driver")) {
					apiTypology = "driver";
				}
				
				stm.setString(1, iFace.getId());
				stm.setString(2, apiTypology);
				stm.setString(3, iFace.getAccessProtocol());
				stm.setString(4, iFace.getBaseUrl());
				stm.setString(5, repo.getId());
				stm.setString(6, iFace.getId());
				
				if (stm.executeUpdate() > 0) {
					logger.debug(iFace.getId() + " inserted in api..");
					logger.debug("now inserting in apicollections..");
					stm.close();
					rs.close();
					conn.commit();

					stm = conn.prepareStatement("INSERT INTO apicollections (accessparam, accessvalue, api, _dnet_resource_identifier_)  VALUES (?,?,?,?)");
					
					stm.setString(1,"FORMAT");
					stm.setString(2, iFace.getAccessFormat());
					stm.setString(3, iFace.getId());
					stm.setString(4,"FORMAT" + "@@" + iFace.getAccessFormat() + "@@" + iFace.getId());
					
					stm.addBatch();

					stm.setString(1,"SET");
					stm.setString(2, iFace.getAccessSet());
					stm.setString(3, iFace.getId());
					stm.setString(4,"SET" + "@@" + iFace.getAccessSet() + "@@" + iFace.getId());
						
					stm.addBatch();
					
					if (stm.executeBatch()[0] > 0) {
						logger.debug(iFace.getId() + " inserted in apicollections.");
					}
					logger.debug("finished updating set + format values in apicollections.");
					stm.close();
					conn.commit();
				}
					
			} else {
				
				logger.debug("exists..");
				boolean edited = false;
				if( rs.getString("original") == null || rs.getString("originalprotocolclass") == null || !rs.getString("original").equalsIgnoreCase(iFace.getBaseUrl()) || !rs.getString("originalprotocolclass").equalsIgnoreCase(iFace.getAccessProtocol()) ) {
					edited = true;
				}
					logger.debug("updating edited values in api..");
					stm.close();
					rs.close();
					
					String apiTypology = "UNKNOWN";
					if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire3.0") || iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire2.0")) {
						apiTypology = "openaire";
					} else if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("driver")) {
						apiTypology = "driver";
					}
					
						
					stm = conn.prepareStatement("UPDATE api SET typology = ?, edited = ?, editedprotocolclass = ?, useedited = ?  WHERE datasource = ? AND id = ? ");
					stm.setString(1, apiTypology);
					if (edited) {
						stm.setString(2, iFace.getBaseUrl());
						stm.setString(3, iFace.getAccessProtocol());
						stm.setBoolean(4, true);
					} else {
						stm.setString(2, null);
						stm.setString(3, null);
						stm.setBoolean(4, false);
					}
					stm.setString(5, repo.getId());
					stm.setString(6, iFace.getId());
					
					if (stm.executeUpdate() > 0 ) {
						logger.debug("finished updating values in api..");
						stm.close();
						conn.commit();
					}
				logger.debug("updating apicollections..");
				
				logger.debug("deleting current values from apicollections..");
				stm = conn.prepareStatement("DELETE FROM apicollections WHERE api = ?");
				
				stm.setString(1, iFace.getId());
				
				if (stm.executeUpdate() > 0) {
					logger.debug("values for interface " + iFace.getId() + " deleted from api_collections..");
					stm.close();
					rs.close();
					conn.commit();
					
				}
					logger.debug("now inserting in apicollections..");

					stm = conn.prepareStatement("INSERT INTO apicollections (accessparam, accessvalue, api, _dnet_resource_identifier_)  VALUES (?,?,?,?)");
					
					stm.setString(1,"FORMAT");
					stm.setString(2, iFace.getAccessFormat());
					stm.setString(3, iFace.getId());
					stm.setString(4,"FORMAT" + "@@" + iFace.getAccessFormat() + "@@" + iFace.getId());
					
					stm.addBatch();
					
					stm.setString(1,"SET");
					stm.setString(2, iFace.getAccessSet());
					stm.setString(3, iFace.getId());
					stm.setString(4,"SET" + "@@" + iFace.getAccessSet() + "@@" + iFace.getId());
						
					stm.addBatch();
					
					if (stm.executeBatch()[0] > 0) {
						logger.debug(iFace.getId() + " inserted in apicollections.");
					}
					logger.debug("finished updating set + format values in apicollections.");
					stm.close();
					conn.commit();
			
			}	
			logger.debug("interface : " + iFace.getId() + " inserted successfully..");
		}			
			
	} else if (datatype.equalsIgnoreCase("journal")||datatype.equalsIgnoreCase("aggregator")){		

		try {								
				stm = conn.prepareStatement("UPDATE datasources SET id = ?, officialname = ?, englishname = ?, websiteurl = ?, logourl = ?, contactemail = ?, latitude = ?, longitude = ?, timezone = ?, namespaceprefix = ?, collectedfrom = ?, typology = ?, datasourceclass = ?, provenanceactionclass = ?, _dnet_resource_identifier_ = ? WHERE officialname = ? AND id = ?");
				
				stm.setString(1, repo.getId()); //activation id
				stm.setString(2, repo.getOfficialName());
				stm.setString(3, repo.getEnglishName());
				stm.setString(4, repo.getWebsiteUrl());
				stm.setString(5, repo.getLogoUrl());
				stm.setString(6, repo.getContactEmail());
				stm.setDouble(7, repo.getLatitude());
				stm.setDouble(8, repo.getLongitude());
				stm.setString(9, repo.getTimezone() + "");
				stm.setString(10, repo.getNamespacePrefix());
				stm.setString(11, repo.getCollectedFrom()); 
				stm.setString(12, repo.getTypology()); 
				stm.setString(13, repo.getDatasourceClass());
				stm.setString(14, repo.getProvenanceActionClass());
				stm.setString(15,repo.getId());
				stm.setString(16,officialNameOld);
				stm.setString(17,idOld);
	
				
				stm.executeUpdate();
				logger.debug(datatype + " " + repo.getOfficialName() + " inserted in datasources.");
				stm.close();
				conn.commit();

				logger.debug("checking current values in api..");
				
				stm = conn.prepareStatement("SELECT COUNT(*) FROM api WHERE datasource = ?");
				stm.setString(1, repo.getId());
				rs = stm.executeQuery();
				int noCurrentInApi = 0;
				if (rs.next()) {
					noCurrentInApi = rs.getInt(1);
				}
				stm.close();
				rs.close();
				
				
				for (RepositoryInterface iFace : repo.getInterfaces()) {
					logger.debug("checking if interface : " + iFace.getId() + " already exists in api..");
					stm = conn.prepareStatement("SELECT * FROM api WHERE datasource = ? AND id = ?");
					stm.setString(1, repo.getId());
					stm.setString(2, iFace.getId());
					rs = stm.executeQuery();
					
					if (!rs.next()) {
						logger.debug("not exist..");
						stm.close();
						rs.close();
						
						stm = conn.prepareStatement("INSERT INTO api (id, typology, originalprotocolclass, original, datasource, _dnet_resource_identifier_)  VALUES (?,?,?,?,?,?)");
						iFace.setId("api_________::" + repo.getId() + "::" + noCurrentInApi);
						logger.debug("creating new api_id: " + iFace.getId());
						noCurrentInApi++;
						
						String apiTypology = "UNKNOWN";
						if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire3.0") || iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire2.0")) {
							apiTypology = "openaire";
						} else if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("driver")) {
							apiTypology = "driver";
						}
						stm.setString(1, iFace.getId());
						stm.setString(2, apiTypology);
						stm.setString(3, iFace.getAccessProtocol());
						stm.setString(4, iFace.getBaseUrl());
						stm.setString(5, repo.getId());
						stm.setString(6, iFace.getId());
						
						if (stm.executeUpdate() > 0) {
							logger.debug(iFace.getId() + " inserted in api..");
							logger.debug("now inserting in apicollections..");
							stm.close();
							rs.close();
							conn.commit();
		
							stm = conn.prepareStatement("INSERT INTO apicollections (accessparam, accessvalue, api, _dnet_resource_identifier_)  VALUES (?,?,?,?)");
							
							stm.setString(1,"FORMAT");
							stm.setString(2, iFace.getAccessFormat());
							stm.setString(3, iFace.getId());
							stm.setString(4,"FORMAT" + "@@" + iFace.getAccessFormat() + "@@" + iFace.getId());
							
							stm.addBatch();
	
							stm.setString(1,"SET");
							stm.setString(2, iFace.getAccessSet());
							stm.setString(3, iFace.getId());
							stm.setString(4,"SET" + "@@" + iFace.getAccessSet() + "@@" + iFace.getId());
								
							stm.addBatch();
							
							if (stm.executeBatch()[0] > 0) {
								logger.debug(iFace.getId() + " inserted in apicollections.");
							}
							logger.debug("finished updating set + format values in apicollections.");
							stm.close();
							conn.commit();
						}
							
					} else {
						
						logger.debug("exists..");
						boolean edited = false;
						if( rs.getString("original") == null || rs.getString("originalprotocolclass") == null || !rs.getString("original").equalsIgnoreCase(iFace.getBaseUrl()) || !rs.getString("originalprotocolclass").equalsIgnoreCase(iFace.getAccessProtocol()) ) {
							edited = true;
						}
							logger.debug("updating edited values in api..");
							stm.close();
							rs.close();
							
							String apiTypology = "UNKNOWN";
							if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire3.0") || iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("openaire2.0")) {
								apiTypology = "openaire";
							} else if (iFace.getDesiredCompatibilityLevel().equalsIgnoreCase("driver")) {
								apiTypology = "driver";
							}
							
							
							stm = conn.prepareStatement("UPDATE api SET typology = ?, edited = ?, editedprotocolclass = ?, useedited = ?  WHERE datasource = ? AND id = ? ");
							stm.setString(1, apiTypology);
							if (edited) {
								stm.setString(2, iFace.getBaseUrl());
								stm.setString(3, iFace.getAccessProtocol());
								stm.setBoolean(4, true);
							} else {
								stm.setString(2, null);
								stm.setString(3, null);
								stm.setBoolean(4, false);
							}
							stm.setString(5, repo.getId());
							stm.setString(6, iFace.getId());
							
							if (stm.executeUpdate() > 0 ) {
								logger.debug("finished updating values in api..");
								stm.close();
								conn.commit();
							}
						logger.debug("updating apicollections..");
						
						logger.debug("deleting current values from apicollections..");
						stm = conn.prepareStatement("DELETE FROM apicollections WHERE api = ?");
						
						stm.setString(1, iFace.getId());
						
						if (stm.executeUpdate() > 0) {
							logger.debug("values for interface " + iFace.getId() + " deleted from api_collections..");
							stm.close();
							rs.close();
							conn.commit();
							
						}
							logger.debug("now inserting in apicollections..");
		
							stm = conn.prepareStatement("INSERT INTO apicollections (accessparam, accessvalue, api, _dnet_resource_identifier_)  VALUES (?,?,?,?)");
							
							stm.setString(1,"FORMAT");
							stm.setString(2, iFace.getAccessFormat());
							stm.setString(3, iFace.getId());
							stm.setString(4,"FORMAT" + "@@" + iFace.getAccessFormat() + "@@" + iFace.getId());
							
							stm.addBatch();
	
							stm.setString(1,"SET");
							stm.setString(2, iFace.getAccessSet());
							stm.setString(3, iFace.getId());
							stm.setString(4,"SET" + "@@" + iFace.getAccessSet() + "@@" + iFace.getId());
								
							stm.addBatch();
							
							if (stm.executeBatch()[0] > 0) {
								logger.debug(iFace.getId() + " inserted in apicollections.");
							}
							logger.debug("finished updating set + format values in apicollections.");
							stm.close();
							conn.commit();
					
					}	
					logger.debug("interface : " + iFace.getId() + " inserted successfully..");
				}

					logger.debug("inserting in organizations..");
					stm.close();
					conn.commit();
					
					stm = conn.prepareStatement("SELECT * FROM organizations WHERE id = ?");
					stm.setString(1, "openaire____::" + Base64.encode(repo.getOrganization()));

					ResultSet rs1 = stm.executeQuery();
					boolean exists = rs1.next();
					
					rs1.close();
					
					if(!exists) {
						
						stm = conn.prepareStatement("SELECT code FROM class WHERE name = ?");
						stm.setString(1,repo.getCountryName());
						
						rs1 = stm.executeQuery();
						
						String countryCode = "UNKNOWN";
						if ( rs1.next()) {
							countryCode = rs1.getString(1);
						stm.close();
						}
						stm = conn.prepareStatement("INSERT INTO organizations (legalname, countryclass, id, legalshortname, _dnet_resource_identifier_) VALUES (?,?,?,?,?)");
						stm.setString(1, repo.getOrganization());
						stm.setString(2, countryCode);
						stm.setString(3, "openaire____::" + Base64.encode(repo.getOrganization()));
						stm.setString(4, repo.getOrganization());
						stm.setString(5, "openaire____::" + Base64.encode(repo.getOrganization()));
						stm.executeUpdate();
						logger.debug("organization" + "openaire____::" + Base64.encode(repo.getOrganization()) + " inserted in organizations.");
		
						stm.close();
						conn.commit();
					} else {
						logger.debug("Organization "+repo.getOrganization()+" already exists");
					}
					
						logger.debug("inserting in datasource-organizations..");
						stm = conn.prepareStatement("UPDATE datasource_organization SET organization = ? , datasource = ? , _dnet_resource_identifier_ = ? WHERE datasource = ? ");
						stm.setString(1, "openaire____::" + Base64.encode(repo.getOrganization()));
						stm.setString(2, repo.getId());
						stm.setString(3, repo.getId() + "@@" + "openaire____::" + Base64.encode(repo.getOrganization()) );
						stm.setString(4, idOld);
	
						if( stm.executeUpdate()>0) {
							logger.debug("organization" + "openaire____::" + Base64.encode(repo.getOrganization()) + " inserted in datasource-organizations.");
							stm.close();
							
							conn.commit();
						}		

		logger.debug("Finished updating " + datatype + " repository..");
		
		} catch (SQLException e) {
			logger.error("Error updating repo " + repo.getOfficialName() + " from openaire db", e);
			throw e;
		} finally {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					logger.error("Error closing connection", e);
				}
		}
	}
	return retMessage;

	}

	@Override
	public boolean updateRepositoryInterfaceCompliance(String officialName, String datasourceId,
			String interfaceId, String compliance, String set, String baseUrl, String oldId) throws Exception {
		boolean ret = true;
		Connection conn = null;
		try {
			
			logger.info("updating repository " + officialName + " compliance to : " + compliance);
			conn = openAireDataSource.getConnection();
			PreparedStatement stm = conn.prepareStatement("UPDATE datasources SET openairecompatibilityclass=?, dateofvalidation=?, activationid = ? , openairecompatibilityscheme = ? WHERE id = ?");

			java.util.Date utilDate = new java.util.Date();
			java.sql.Timestamp date = new java.sql.Timestamp(utilDate.getTime());			
			Map<String, String> compMap = this.getRepoCompatibility(officialName, datasourceId);
			
			String newCompliance = ""; 
			if (compliance.equalsIgnoreCase("openaire2.0")) {
				if ( compMap.containsValue("driver") && compMap.containsValue("openaire") )
					newCompliance = "driver-openaire2.0-openaire3.0";
				else if ( compMap.containsValue("driver") )
					newCompliance = "driver-openaire2.0";
				else if ( compMap.containsValue("openaire") )
					newCompliance = "openaire2.0-openaire3.0";
				else 
					newCompliance = "openaire2.0";			
			} else if (compliance.equalsIgnoreCase("driver")) {
				if ( compMap.containsValue("ec_fundedresources") && compMap.containsValue("openaire") )
					newCompliance = "driver-openaire2.0-openaire3.0";
				else if ( compMap.containsValue("ec_fundedresources") )
					newCompliance = "driver-openaire2.0";
				else if ( compMap.containsValue("openaire") )
					newCompliance = "driver-openaire3.0";
				else 
					newCompliance = "driver";	
			} else if (compliance.equalsIgnoreCase("openaire3.0")) {
				if ( compMap.containsValue("ec_fundedresources") && compMap.containsValue("driver") )
					newCompliance = "driver-openaire2.0-openaire3.0";
				else if ( compMap.containsValue("ec_fundedresources") )
					newCompliance = "openaire2.0-openaire3.0";
				else if ( compMap.containsValue("driver") )
					newCompliance = "driver-openaire3.0";
				else 
					newCompliance = "openaire3.0";
			} else if (compliance.equalsIgnoreCase("openaire2.0_data")) {
				newCompliance = "openaire2.0";
			} else if (compliance.equalsIgnoreCase("notCompatible")) {
				if ( compMap.containsValue("ec_fundedresources") && compMap.containsValue("driver") && compMap.containsValue("openaire"))
					newCompliance = "driver-openaire2.0-openaire3.0";
				else if ( compMap.containsValue("ec_fundedresources") && compMap.containsValue("driver") )
					newCompliance = "driver-openaire2.0";
				else if ( compMap.containsValue("openaire") )
					newCompliance = "openaire3.0";
				else if ( compMap.containsValue("ec_fundedresources") )
					newCompliance = "openaire2.0";
				else if ( compMap.containsValue("driver") )
					newCompliance = "driver";
				else 
					newCompliance = "notCompatible";		
			}
			
			stm.setString(1, newCompliance);
			stm.setTimestamp(2,date);
			stm.setString(3, null);
			stm.setString(4, "dnet:compatibilityLevel");
			stm.setString(5, datasourceId);
			
			stm.executeUpdate();
			stm.close();
			conn.commit();
			logger.debug(officialName + " set as openaire compliant: " + compliance);
		} catch (SQLException e) {
			 logger.error("error connecting to openaire db to set a repo as openaire compliant " + officialName, e);
			 	ret = false;
				throw e;
			}  
			finally {
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						ret = false;
						logger.error("Error closing connection", e);
					}
			}
		return ret;
	}

}