<commit_before>/**
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 * 
 * Copyright (C) 2010, 2011, 2012, 2013 Pyravlos Team
 * 
 * http://www.strabon.di.uoa.gr/
 */
package eu.earthobservatory.org.StrabonEndpoint;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openrdf.query.BindingSet;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.TupleQueryResultHandlerException;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.earthobservatory.runtime.generaldb.InvalidDatasetFormatFault;
import eu.earthobservatory.runtime.generaldb.Strabon;
import eu.earthobservatory.utils.Format;


public class StrabonBeanWrapper implements org.springframework.beans.factory.DisposableBean {
	
	private static Logger logger = LoggerFactory.getLogger(eu.earthobservatory.org.StrabonEndpoint.StrabonBeanWrapper.class);
	
	private static final String FILE_PROTOCOL = "file";
	
	private String serverName;
	private int port;
	private String databaseName;
	private String user;
	private String password;
	private String dbBackend;
	private int maxLimit;
	private boolean loadFromFile;
	private String prefixes;
	
	private Strabon strabon = null;
		
	private String gChartString =" ";
	
	private boolean checkForLockTable;
	private List<StrabonBeanWrapperConfiguration> entries;

	public StrabonBeanWrapper(String databaseName, String user, String password, 
			int port, String serverName, boolean checkForLockTable, String dbBackend, 
			int maxLimit, boolean loadFromFile,String prefixes, 	List<List<String>> args) {
		this.serverName = serverName;
		this.port = port;
		this.databaseName = databaseName;
		this.user = user;
		this.password = password;
		this.checkForLockTable = checkForLockTable;
		this.dbBackend = dbBackend;
		this.maxLimit = maxLimit;	
		this.loadFromFile = loadFromFile;
		this.prefixes = prefixes;
		this.entries = new ArrayList<StrabonBeanWrapperConfiguration>(args.size());
		
		Iterator<List<String>> entryit = args.iterator();
		
		while (entryit.hasNext()) {
			List<String> list = entryit.next();
			Iterator<String> it = list.iterator();
			
			while (it.hasNext()) {
				int items = 0;
				//Header:label        
				//Bean  :label      bean         
				//Entry :label      bean         statement    format       title      handle
				String param1 = "", param2 = "", param3 = "", param4 = "", param5="", param6=""; 
	
				if (it.hasNext()) {
					param1 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param2 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param3 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param4 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param5 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param6 = it.next();
					items++;
				}
				
				if (items == 1) {
					//the first element corresponds to the label
					StrabonBeanWrapperConfiguration entry = new StrabonBeanWrapperConfiguration(param1);
					this.entries.add(entry);
				} else if (items == 2) {
					//the first element corresponds to the label
					StrabonBeanWrapperConfiguration entry = new StrabonBeanWrapperConfiguration(param1, param2);
					this.entries.add(entry);
				} else if (items == 6) {
					StrabonBeanWrapperConfiguration entry = new StrabonBeanWrapperConfiguration(param3, param1, param4, param2, param5, param6);
					this.entries.add(entry);
				}
			
				
			}
		}

		init();
	}

	public boolean init() {
		if (this.strabon == null) {
			try {
				logger.warn("[StrabonEndpoint] Strabon not initialized yet.");
				logger.warn("[StrabonEndpoint] Initializing Strabon.");
				//logger.info("[StrabonEndpoint] Connection details:\n" + this.getDetails());
				
				// initialize Strabon according to user preference
				if (Common.DBBACKEND_MONETDB.equalsIgnoreCase(dbBackend)) {
					this.strabon = new eu.earthobservatory.runtime.monetdb.Strabon(databaseName, user, password, port, serverName, checkForLockTable);
					
				} else {
					// check whether the user typed wrong database backend and report
					if (!Common.DBBACKEND_POSTGIS.equalsIgnoreCase(dbBackend)) {
						logger.warn("[StrabonEndpoint] Unknown database backend \""+dbBackend+"\". Assuming PostGIS.");
					}
					
					// use PostGIS as the default database backend
					this.strabon = new eu.earthobservatory.runtime.postgis.Strabon(databaseName, user, password, port, serverName, checkForLockTable);	
				}
				
				
			} catch (Exception e) {
				logger.error("[StrabonEndpoint] Exception occured while creating Strabon. {}\n{}", e.getMessage(), this.getDetails());
				return false;
			}
		}

		return true;
	}

	public Strabon getStrabon() {
		return strabon;
	}

	public void setStrabon(Strabon strabon) {
		this.strabon = strabon;
	}

	public void closeConnection() {
		if (strabon != null) {
			strabon.close();
			strabon = null;
		}
	}
	
	public void destroy() throws Exception {
		if (strabon != null) {
			strabon.close();
			
			// deregister jdbc driver
			strabon.deregisterDriver();
		}
	}<commit_msg>Fixes Bug #40: StrabonBeanWrapper now registers a handler for SIGTERM signal, so as if Strabon Endpoint is run from the command-line (endpoint-exec), then the closing of the connection will be ultimately called.<commit_after>/**
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 * 
 * Copyright (C) 2010, 2011, 2012, 2013 Pyravlos Team
 * 
 * http://www.strabon.di.uoa.gr/
 */
package eu.earthobservatory.org.StrabonEndpoint;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.openrdf.query.BindingSet;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.TupleQuery;
import org.openrdf.query.TupleQueryResult;
import org.openrdf.query.TupleQueryResultHandlerException;
import org.openrdf.repository.RepositoryException;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import eu.earthobservatory.runtime.generaldb.InvalidDatasetFormatFault;
import eu.earthobservatory.runtime.generaldb.Strabon;
import eu.earthobservatory.utils.Format;


public class StrabonBeanWrapper implements org.springframework.beans.factory.DisposableBean {
	
	private static Logger logger = LoggerFactory.getLogger(eu.earthobservatory.org.StrabonEndpoint.StrabonBeanWrapper.class);
	
	private static final String FILE_PROTOCOL = "file";
	
	private String serverName;
	private int port;
	private String databaseName;
	private String user;
	private String password;
	private String dbBackend;
	private int maxLimit;
	private boolean loadFromFile;
	private String prefixes;
	
	private Strabon strabon = null;
		
	private String gChartString =" ";
	
	private boolean checkForLockTable;
	private List<StrabonBeanWrapperConfiguration> entries;

	public StrabonBeanWrapper(String databaseName, String user, String password, 
			int port, String serverName, boolean checkForLockTable, String dbBackend, 
			int maxLimit, boolean loadFromFile,String prefixes, 	List<List<String>> args) {
		this.serverName = serverName;
		this.port = port;
		this.databaseName = databaseName;
		this.user = user;
		this.password = password;
		this.checkForLockTable = checkForLockTable;
		this.dbBackend = dbBackend;
		this.maxLimit = maxLimit;	
		this.loadFromFile = loadFromFile;
		this.prefixes = prefixes;
		this.entries = new ArrayList<StrabonBeanWrapperConfiguration>(args.size());
		
		Iterator<List<String>> entryit = args.iterator();
		
		while (entryit.hasNext()) {
			List<String> list = entryit.next();
			Iterator<String> it = list.iterator();
			
			while (it.hasNext()) {
				int items = 0;
				//Header:label        
				//Bean  :label      bean         
				//Entry :label      bean         statement    format       title      handle
				String param1 = "", param2 = "", param3 = "", param4 = "", param5="", param6=""; 
	
				if (it.hasNext()) {
					param1 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param2 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param3 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param4 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param5 = it.next();
					items++;
				}
				if (it.hasNext()) {
					param6 = it.next();
					items++;
				}
				
				if (items == 1) {
					//the first element corresponds to the label
					StrabonBeanWrapperConfiguration entry = new StrabonBeanWrapperConfiguration(param1);
					this.entries.add(entry);
				} else if (items == 2) {
					//the first element corresponds to the label
					StrabonBeanWrapperConfiguration entry = new StrabonBeanWrapperConfiguration(param1, param2);
					this.entries.add(entry);
				} else if (items == 6) {
					StrabonBeanWrapperConfiguration entry = new StrabonBeanWrapperConfiguration(param3, param1, param4, param2, param5, param6);
					this.entries.add(entry);
				}
			
				
			}
		}

		init();
	}

	public boolean init() {
		if (this.strabon == null) {
			try {
				logger.warn("[StrabonEndpoint] Strabon not initialized yet.");
				logger.warn("[StrabonEndpoint] Initializing Strabon.");
				//logger.info("[StrabonEndpoint] Connection details:\n" + this.getDetails());
				
				// initialize Strabon according to user preference
				if (Common.DBBACKEND_MONETDB.equalsIgnoreCase(dbBackend)) {
					this.strabon = new eu.earthobservatory.runtime.monetdb.Strabon(databaseName, user, password, port, serverName, checkForLockTable);
					
				} else {
					// check whether the user typed wrong database backend and report
					if (!Common.DBBACKEND_POSTGIS.equalsIgnoreCase(dbBackend)) {
						logger.warn("[StrabonEndpoint] Unknown database backend \""+dbBackend+"\". Assuming PostGIS.");
					}
					
					// use PostGIS as the default database backend
					this.strabon = new eu.earthobservatory.runtime.postgis.Strabon(databaseName, user, password, port, serverName, checkForLockTable);	
				}

				installSIGTERMHandler(this.strabon);
				
			} catch (Exception e) {
				logger.error("[StrabonEndpoint] Exception occured while creating Strabon. {}\n{}", e.getMessage(), this.getDetails());
				return false;
			}
		}

		return true;
	}

	/**
	 * Registers a handler for SIGTERM signals, like Ctrl-C. One may send such a signal
	 * at the command prompt, when running Strabon Endpoint from the command line, i.e.,
	 * using the endpoint-exec module.   
	 * 
	 * @param strabon The strabon instance
	 */
	private static void installSIGTERMHandler(final Strabon strabon) {
		if (logger.isDebugEnabled()) {
			logger.info("[StrabonEndpoint] Installing handler for SIGTERM signals...");
		}
		
		// register the handler
		Runtime.getRuntime().addShutdownHook(new Thread() {
			
			@Override
			public void run() {
				// just call the Strabon.close() method
				strabon.close();
			}
		});
		
		if (logger.isDebugEnabled()) {
			logger.info("[StrabonEndpoint] Handler for SIGTERM signals installed successfully.");
		}
	}
	
	public Strabon getStrabon() {
		return strabon;
	}

	public void setStrabon(Strabon strabon) {
		this.strabon = strabon;
	}

	public void closeConnection() {
		if (strabon != null) {
			strabon.close();
			strabon = null;
		}
	}
	
	public void destroy() throws Exception {
		if (strabon != null) {
			strabon.close();
			
			// deregister jdbc driver
			strabon.deregisterDriver();
		}
	}
{'fraction_non_alphanumeric': 0.11186715269339814, 'fraction_numerical': 0.007776427703523694, 'mean_word_length': 3.5624538063562454, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, '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': '2019928', 'n_tokens_mistral': 4518, 'n_tokens_neox': 3778, 'n_words': 952}