<commit_before>package utils;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.internal.jpa.deployment.JPAInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.eclipse.persistence.jpa.PersistenceProvider;
import com.heroku.sdk.jdbc.DatabaseUrl;

/**
 * Initialize EntityManager Factory
 * For Heroku, try to find the environment property DATABASE_URL, and transform
 * it into a valid jdbc URL to initialize properly the DB.
 *
 * @author mlecoutre
 */

/**
  private static final Logger logger = LoggerFactory.getLogger(AppointmentService.class);

    @GET
    public List<AppointmentVO> get() {
        logger.debug("Appointment service");
        EntityManager em = EntityManagerLoaderListener.createEntityManager();
        TypedQuery<Appointment> query = em.createQuery("FROM Appointment", Appointment.class);
        List<AppointmentVO> apps = new ArrayList<AppointmentVO>();
        try {
            query.setMaxResults(Constants.MAX_RESULT);
            List<Appointment> appointments = query.getResultList();
            for (Appointment a : appointments) {
                AppointmentVO appVo = populateAppointmentVO(a);
                apps.add(appVo);
            }
        } catch (NoResultException nre) {
            logger.error("No appointment at this time");
        } finally {
            em.close();
        }
        return apps;
    }

 */
@WebListener
public class EntityManagerLoaderListener implements ServletContextListener {
	private static final Logger logger = LoggerFactory.getLogger(EntityManagerLoaderListener.class);

	//private String DEFAULT_DB_URL = "postgres://postgres:postgres@localhost:5432/ursulaGIS";//"jdbc:h2:~/test.db";
	                              //"postgres://ursulaUser:ursulaPass@localhost:5432/UrsulaGIS";
	private String DEFAULT_DB_URL = "postgres://ursulaUser:ursulaPass@localhost:5432/UrsulaGIS";
	private static EntityManagerFactory emf;
	private boolean pushAdditionalProperties = true;

	public EntityManagerLoaderListener() {
	}

	public EntityManagerLoaderListener(boolean pushAdditionalProperties) {
		this.pushAdditionalProperties = pushAdditionalProperties;
	}
	
	/**
	 * metodo que crea emf al inicializarse el context
	 */
	//@Override
	public void contextInitializedNew(ServletContextEvent event) {	
		logger.info("EntityManagerLoaderListener.contextInitialized()");
		
		String databaseUrl = System.getenv("DATABASE_URL");
		StringTokenizer st = new StringTokenizer(databaseUrl, ":@/");
		String dbVendor = st.nextToken(); //if DATABASE_URL is set
		String userName = st.nextToken();
		String password = st.nextToken();
		String host = st.nextToken();
		String port = st.nextToken();
		String databaseName = st.nextToken();
		String jdbcUrl = String.format("jdbc:postgresql://%s:%s/%s?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory", host, port, databaseName);
		Map<String, String> properties = new HashMap<String, String>();
		properties.put("javax.persistence.jdbc.url", jdbcUrl );// cambiar databaseUrl por jdbcUrl? ;databaseUrl
		properties.put("javax.persistence.jdbc.user", userName );
		properties.put("javax.persistence.jdbc.password", password );
		properties.put("javax.persistence.jdbc.driver", "org.postgresql.Driver");
	//	properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
		//PersistenceProvider prov = new PersistenceProvider();
		//JPAInitializer initializer = prov.getInitializer("ursulaGIS", properties);
		
		emf = Persistence.createEntityManagerFactory("ursulaGIS", properties);
		
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		//contextInitializedOld(event);
		//contextInitializedNew(event);
		contextInitializedTest(event);
	}
	
	public void contextInitializedTest(ServletContextEvent event) {
		String databaseUrl = System.getenv("DATABASE_URL");
		HerokuURLAnalyser analyser = new HerokuURLAnalyser(databaseUrl);
		Map<String, String> properties = new HashMap<String, String>();
		logger.info("jdbcURL: "+ analyser.getJdbcURL());
		properties.put("javax.persistence.jdbc.url", analyser.getJdbcURL());//"jdbc:postgresql://localhost:5432/UrsulaGIS2" );// cambiar databaseUrl por jdbcUrl? ;databaseUrl
		properties.put("javax.persistence.jdbc.user", analyser.getUserName() );
		properties.put("javax.persistence.jdbc.password", analyser.getPassword() );
		emf = Persistence.createEntityManagerFactory("ursulaGIS",properties);
		
	}
	
	public void contextInitializedOld(ServletContextEvent event) {
		logger.info("EntityManagerLoaderListener.contextInitialized()");
		
		String databaseUrl = System.getenv("DATABASE_URL");
		//logger.info("system database url ="+databaseUrl);
		//System.out.println("database url ="+databaseUrl);
		//postgres://{user}:{password}@{hostname}:{port}/{database-name}
		//set DATABASE_URL=postgres://postgres:admin@localhost:5432/ursulaGIS
		
		//DatabaseUrl.extract().getConnection();

		if (databaseUrl == null && pushAdditionalProperties) {
			logger.info("Use default config in persistence.xml with " + DEFAULT_DB_URL);
			databaseUrl = DEFAULT_DB_URL;
		}
		Map<String, String> properties = new HashMap<String, String>();
		if (pushAdditionalProperties) {
			HerokuURLAnalyser analyser = new HerokuURLAnalyser(databaseUrl);
			try{
//				DatabaseUrl ext = DatabaseUrl.extract();
//				properties.put(PersistenceUnitProperties.JDBC_URL,ext.jdbcUrl());// ext.jdbcUrl());//
//				properties.put(PersistenceUnitProperties.JDBC_USER, ext.username());//ext.username());//
//				properties.put(PersistenceUnitProperties.JDBC_PASSWORD,ext.password());// ext.password());<commit_msg>cambiand herokuUrlAnalyser por DatabaseUrl<commit_after>package utils;

import java.net.URISyntaxException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.eclipse.persistence.config.PersistenceUnitProperties;
import org.eclipse.persistence.internal.jpa.deployment.JPAInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.eclipse.persistence.jpa.PersistenceProvider;
import com.heroku.sdk.jdbc.DatabaseUrl;

/**
 * Initialize EntityManager Factory
 * For Heroku, try to find the environment property DATABASE_URL, and transform
 * it into a valid jdbc URL to initialize properly the DB.
 *
 * @author mlecoutre
 */

/**
  private static final Logger logger = LoggerFactory.getLogger(AppointmentService.class);

    @GET
    public List<AppointmentVO> get() {
        logger.debug("Appointment service");
        EntityManager em = EntityManagerLoaderListener.createEntityManager();
        TypedQuery<Appointment> query = em.createQuery("FROM Appointment", Appointment.class);
        List<AppointmentVO> apps = new ArrayList<AppointmentVO>();
        try {
            query.setMaxResults(Constants.MAX_RESULT);
            List<Appointment> appointments = query.getResultList();
            for (Appointment a : appointments) {
                AppointmentVO appVo = populateAppointmentVO(a);
                apps.add(appVo);
            }
        } catch (NoResultException nre) {
            logger.error("No appointment at this time");
        } finally {
            em.close();
        }
        return apps;
    }

 */
@WebListener
public class EntityManagerLoaderListener implements ServletContextListener {
	private static final Logger logger = LoggerFactory.getLogger(EntityManagerLoaderListener.class);

	//private String DEFAULT_DB_URL = "postgres://postgres:postgres@localhost:5432/ursulaGIS";//"jdbc:h2:~/test.db";
	                              //"postgres://ursulaUser:ursulaPass@localhost:5432/UrsulaGIS";
	private String DEFAULT_DB_URL = "postgres://ursulaUser:ursulaPass@localhost:5432/UrsulaGIS";
	private static EntityManagerFactory emf;
	private boolean pushAdditionalProperties = true;

	public EntityManagerLoaderListener() {
	}

	public EntityManagerLoaderListener(boolean pushAdditionalProperties) {
		this.pushAdditionalProperties = pushAdditionalProperties;
	}
	
	/**
	 * metodo que crea emf al inicializarse el context
	 */
	//@Override
	public void contextInitializedNew(ServletContextEvent event) {	
		logger.info("EntityManagerLoaderListener.contextInitialized()");
		
		String databaseUrl = System.getenv("DATABASE_URL");
		StringTokenizer st = new StringTokenizer(databaseUrl, ":@/");
		String dbVendor = st.nextToken(); //if DATABASE_URL is set
		String userName = st.nextToken();
		String password = <PASSWORD>();
		String host = st.nextToken();
		String port = st.nextToken();
		String databaseName = st.nextToken();
		String jdbcUrl = String.format("jdbc:postgresql://%s:%s/%s?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory", host, port, databaseName);
		Map<String, String> properties = new HashMap<String, String>();
		properties.put("javax.persistence.jdbc.url", jdbcUrl );// cambiar databaseUrl por jdbcUrl? ;databaseUrl
		properties.put("javax.persistence.jdbc.user", userName );
		properties.put("javax.persistence.jdbc.password", password );
		properties.put("javax.persistence.jdbc.driver", "org.postgresql.Driver");
	//	properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
		//PersistenceProvider prov = new PersistenceProvider();
		//JPAInitializer initializer = prov.getInitializer("ursulaGIS", properties);
		
		emf = Persistence.createEntityManagerFactory("ursulaGIS", properties);
		
	}

	@Override
	public void contextInitialized(ServletContextEvent event) {
		//contextInitializedOld(event);
		//contextInitializedNew(event);
		contextInitializedRemote(event);
	}
	
	//esto funciona bien en local pero no en remoto porque da error de string decription
	public void contextInitializedTest(ServletContextEvent event) {
		String databaseUrl = System.getenv("DATABASE_URL");
		HerokuURLAnalyser analyser = new HerokuURLAnalyser(databaseUrl);
		Map<String, String> properties = new HashMap<String, String>();
		logger.info("jdbcURL: "+ analyser.getJdbcURL());
		properties.put("javax.persistence.jdbc.url", analyser.getJdbcURL());//"jdbc:postgresql://localhost:5432/UrsulaGIS2" );// cambiar databaseUrl por jdbcUrl? ;databaseUrl
		properties.put("javax.persistence.jdbc.user", analyser.getUserName() );
		properties.put("javax.persistence.jdbc.password", <PASSWORD>ser.<PASSWORD>() );
		emf = Persistence.createEntityManagerFactory("ursulaGIS",properties);
		
	}
	
	public void contextInitializedRemote(ServletContextEvent event) {
		
		try {
			DatabaseUrl databaseUrl = DatabaseUrl.extract();
			//databaseUrl.
			
		//	String databaseUrl = System.getenv("DATABASE_URL");
			//HerokuURLAnalyser analyser = new HerokuURLAnalyser(databaseUrl);
			Map<String, String> properties = new HashMap<String, String>();
			logger.info("jdbcURL: "+ databaseUrl.jdbcUrl());
			properties.put("javax.persistence.jdbc.url", databaseUrl.jdbcUrl());//"jdbc:postgresql://localhost:5432/UrsulaGIS2" );// cambiar databaseUrl por jdbcUrl? ;databaseUrl
			properties.put("javax.persistence.jdbc.user", databaseUrl.username() );
			properties.put("javax.persistence.jdbc.password", <PASSWORD>Url.password() );
			emf = Persistence.createEntityManagerFactory("ursulaGIS",properties);
			
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	
	public void contextInitializedOld(ServletContextEvent event) {
		logger.info("EntityManagerLoaderListener.contextInitialized()");
		
		String databaseUrl = System.getenv("DATABASE_URL");
		//logger.info("system database url ="+databaseUrl);
		//System.out.println("database url ="+databaseUrl);
		//postgres://{user}:{password}@{hostname}:{port}/{database-name}
		//set DATABASE_URL=postgres://postgres:admin@localhost:5432/ursulaGIS
		
		//DatabaseUrl.extract().getConnection();

		if (databaseUrl == null && pushAdditionalProperties) {
			logger.info("Use default config in persistence.xml with " + DEFAULT_DB_URL);
			databaseUrl = DEFAULT_DB_URL;
		}
		Map<String, String> properties = new HashMap<String, String>();
		if (pushAdditionalProperties) {
			HerokuURLAnalyser analyser = new HerokuURLAnalyser(databaseUrl);
			try{
//				DatabaseUrl ext = DatabaseUrl.extract();
//				properties.put(PersistenceUnitProperties.JDBC_URL,ext.jdbcUrl());// ext.jdbcUrl());//
//				properties.put(PersistenceUnitProperties.JDBC_USER, ext.username());//ext.username());//
//				properties.put(PersistenceUnitProperties.JDBC_PASSWORD,ext.password());// ext.password());
{'fraction_non_alphanumeric': 0.12141820126843432, 'fraction_numerical': 0.004049820432490257, 'mean_word_length': 4.83764495985727, 'pattern_counts': {'":': 2, '<': 31, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4934872', 'n_tokens_mistral': 4016, 'n_tokens_neox': 3751, 'n_words': 704}