<commit_before>package net.sf.taverna.t2.workbench.reference.config;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import net.sf.taverna.raven.appconfig.ApplicationRuntime;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.derby.drda.NetworkServerControl;
import org.apache.log4j.Logger;

/**
 * A set of utility methods related to basic data management.
 * 
 * @author <NAME>
 *
 */
public class DataManagementHelper {
	
	private final static Logger logger = Logger.getLogger(DataManagementHelper.class); 
			
	private static NetworkServerControl server;
	
	public static void setupDataSource() {
		
		DataManagementConfiguration config = DataManagementConfiguration.getInstance();
		
		if (config.getConnectorType()==DataManagementConfiguration.CONNECTOR_DERBY) {
			String homeDir=ApplicationRuntime.getInstance().getApplicationHomeDir().getAbsolutePath();
			System.setProperty("derby.system.home",homeDir);
		}
		
        try {
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                    "org.osjava.sj.memory.MemoryContextFactory");
            System.setProperty("org.osjava.sj.jndi.shared", "true");

            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName(config.getDriverClassName());
            
            System.setProperty("hibernate.dialect", config.getHibernateDialect());

            ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            ds.setMaxActive(config.getPoolMaxActive());
            ds.setMinIdle(config.getPoolMinIdle());
            ds.setMaxIdle(config.getPoolMaxIdle());
            ds.setDefaultAutoCommit(true);
            ds.setInitialSize(config.getPoolMinIdle());
            //Derby blows up if the username of password is empty (even an empty string thats not null).
            if (config.getUsername()!=null && config.getUsername().length()>=1) ds.setUsername(config.getUsername());
            if (config.getPassword()!=null && config.getPassword().length()>=1) ds.setPassword(config.getPassword());
            
            ds.setUrl(config.getJDBCUri());
            InitialContext context = new InitialContext();
            context.rebind(DataManagementConfiguration.JNDI_NAME, ds);
            
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }
	
	public static boolean isRunning() {
		if (server==null) {
			return false;			
		}
		else {
			try {
				server.ping();
				return true;
			} catch (Exception e) {
				return false;
			}	
		}
	}
	
	public static Connection openConnection() throws NamingException, SQLException {
		return ((DataSource)new InitialContext().lookup(DataManagementConfiguration.JNDI_NAME)).getConnection();
	}
	
	public synchronized static void startDerbyNetworkServer() {
        String homeDir=ApplicationRuntime.getInstance().getApplicationHomeDir().getAbsolutePath();
        String logDir=homeDir+File.separator+"logs";
        
        //make the logs directory if it doesn't already exist
        File logDirFile=new File(logDir);
        if (!logDirFile.exists()) logDirFile.mkdir();
        
        System.setProperty("derby.drda.host","localhost");
        System.setProperty("derby.drda.minThreads","5");
        System.setProperty("derby.drda.maxThreads",String.valueOf(DataManagementConfiguration.getInstance().getPoolMaxActive()));        
        
        System.setProperty("derby.stream.error.file",logDir+File.separator+"derby.log");
        int port=DataManagementConfiguration.getInstance().getPort();
        int maxPort = port+10;
        
        try {
        	System.setProperty("derby.drda.portNumber",String.valueOf(port));
            if (server==null) server = new NetworkServerControl();
            while(port<maxPort) { //loop to find another available port on which Derby isn't already running
            	if (!isRunning()) break; <commit_msg>now sets the derby home within a method, as it needs to be set before starting the server (if server mode) or before setting up the data source.<commit_after>package net.sf.taverna.t2.workbench.reference.config;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import net.sf.taverna.raven.appconfig.ApplicationRuntime;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.derby.drda.NetworkServerControl;
import org.apache.log4j.Logger;

/**
 * A set of utility methods related to basic data management.
 * 
 * @author <NAME>
 *
 */
public class DataManagementHelper {
	
	private final static Logger logger = Logger.getLogger(DataManagementHelper.class); 
			
	private static NetworkServerControl server;
	
	public static void setupDataSource() {
		
		DataManagementConfiguration config = DataManagementConfiguration.getInstance();
		setDerbyHome();
		
        try {
            System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
                    "org.osjava.sj.memory.MemoryContextFactory");
            System.setProperty("org.osjava.sj.jndi.shared", "true");

            BasicDataSource ds = new BasicDataSource();
            ds.setDriverClassName(config.getDriverClassName());
            
            System.setProperty("hibernate.dialect", config.getHibernateDialect());

            ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
            ds.setMaxActive(config.getPoolMaxActive());
            ds.setMinIdle(config.getPoolMinIdle());
            ds.setMaxIdle(config.getPoolMaxIdle());
            ds.setDefaultAutoCommit(true);
            ds.setInitialSize(config.getPoolMinIdle());
            //Derby blows up if the username of password is empty (even an empty string thats not null).
            if (config.getUsername()!=null && config.getUsername().length()>=1) ds.setUsername(config.getUsername());
            if (config.getPassword()!=null && config.getPassword().length()>=1) ds.setPassword(config.getPassword());
            
            ds.setUrl(config.getJDBCUri());
            InitialContext context = new InitialContext();
            context.rebind(DataManagementConfiguration.JNDI_NAME, ds);
            
        } catch (NamingException ex) {
            ex.printStackTrace();
        }
    }
	
	private static void setDerbyHome() {
		if (DataManagementConfiguration.getInstance().getConnectorType()==DataManagementConfiguration.CONNECTOR_DERBY) {
			String homeDir=ApplicationRuntime.getInstance().getApplicationHomeDir().getAbsolutePath();
			System.setProperty("derby.system.home",homeDir);
		}
		
	}

	public static boolean isRunning() {
		if (server==null) {
			return false;			
		}
		else {
			try {
				server.ping();
				return true;
			} catch (Exception e) {
				return false;
			}	
		}
	}
	
	public static Connection openConnection() throws NamingException, SQLException {
		return ((DataSource)new InitialContext().lookup(DataManagementConfiguration.JNDI_NAME)).getConnection();
	}
	
	public synchronized static void startDerbyNetworkServer() {
		setDerbyHome();
		
        String homeDir=ApplicationRuntime.getInstance().getApplicationHomeDir().getAbsolutePath();
        String logDir=homeDir+File.separator+"logs";        
        
        //make the logs directory if it doesn't already exist
        File logDirFile=new File(logDir);
        if (!logDirFile.exists()) logDirFile.mkdir();
        
        System.setProperty("derby.drda.host","localhost");
        System.setProperty("derby.drda.minThreads","5");
        System.setProperty("derby.drda.maxThreads",String.valueOf(DataManagementConfiguration.getInstance().getPoolMaxActive()));        
        
        System.setProperty("derby.stream.error.file",logDir+File.separator+"derby.log");
        int port=DataManagementConfiguration.getInstance().getPort();
        int maxPort = port+10;
        
        try {
        	System.setProperty("derby.drda.portNumber",String.valueOf(port));
            if (server==null) server = new NetworkServerControl();
            while(port<maxPort) { //loop to find another available port on which Derby isn't already running
            	if (!isRunning()) break; 
{'fraction_non_alphanumeric': 0.11113758189398451, 'fraction_numerical': 0.0016676593210244192, 'mean_word_length': 3.274949083503055, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, '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': '3234461', 'n_tokens_mistral': 2374, 'n_tokens_neox': 2235, 'n_words': 431}