<repo_name>localidata/SPARQL-Interceptor<file_sep>/SPARQLInterceptor/src/tests/GenericTest.java
package tests;

import java.util.Collection;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

import com.localidata.interceptor.Utils;
import com.localidata.queries.ListOfQueries;
import com.localidata.queries.QueryBean;



@RunWith(Parameterized.class)
public class GenericTest {

	private QueryBean bean;

	@Before
	public void method() {
		// set up method	
	}

	@Parameters(name = "{0}")
	public static Collection<Object[]> data() {
		// load the files as you want from the directory
		// System.out.println("Parameters");
		Utils.logConfLoad("log4j.properties");

		ListOfQueries list = new ListOfQueries();
		 
		return Utils.generateData(list);
	}

	

	public GenericTest(QueryBean input) {
		// constructor
		this.bean = input;
	}

	@Test
	public void test() {
		// test
		Utils.realTest(bean);
	}	

	@After
	public void tearDown() {

	}
}<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/TaskConfig.java
package com.localidata.interceptor;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

import javax.servlet.ServletContextEvent;

import org.apache.log4j.Logger;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.ParseException;

public class TaskConfig {

	private static Logger log = Logger.getLogger(TaskConfig.class);

	private int time;
	private ArrayList<Query> queryList;

	private String usuario;
	private String password;
	private String destinos;

	private String endpoint;
	private String timelimit;
	private String timeout;

	
	private String petitionsBeforeReport;
	
	
	
	
	public String getPetitionsBeforeReport() {
		return petitionsBeforeReport;
	}

	public void setPetitionsBeforeReport(String petitionsBeforeReport) {
		this.petitionsBeforeReport = petitionsBeforeReport;
	}

	public String getTimelimit() {
		return timelimit;
	}

	public void setTimelimit(String timelimit) {
		this.timelimit = timelimit;
	}

	public String getTimeout() {
		return timeout;
	}

	public void setTimeout(String timeout) {
		this.timeout = timeout;
	}

	public String getEndpoint() {
		return endpoint;
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public int getTime() {
		return time;
	}

	public void setTime(int time) {
		this.time = time;
	}

	public ArrayList<Query> getQueryList() {
		return queryList;
	}

	public void setQueryList(ArrayList<Query> queryList) {
		this.queryList = queryList;
	}



	public String getUsuario() {
		return usuario;
	}

	public void setUsuario(String usuario) {
		this.usuario = usuario;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = <PASSWORD>;
	}

	public String getDestinos() {
		return destinos;
	}

	public void setDestinos(String destinos) {
		this.destinos = destinos;
	}

	public TaskConfig(ServletContextEvent evt) {

		try {
				Properties p = null;
				JSONObject o = null;
			if (evt==null){
				p = Utils.leerProperties("conf.properties");
				o = Utils.leerJSONFile("queries.json");
			}else{			
				 p = Utils.leerProperties(evt.getServletContext().getRealPath("/") + "/WEB-INF/conf.properties");
				 o = Utils.leerJSONFile(evt.getServletContext().getRealPath("/") + "/WEB-INF/queries.json");
			}

			time = Integer.parseInt(p.getProperty("time"));

			usuario = p.getProperty("user");
			password = <PASSWORD>("<PASSWORD>");
			destinos = p.getProperty("emails");
			endpoint = p.getProperty("endpoint");			
			timelimit=p.getProperty("timelimit");
			timeout=p.getProperty("timeout");
			
			petitionsBeforeReport=p.getProperty("petitionsBeforeReport");
			

			JSONArray queries = (JSONArray) o.get("queries");

			queryList = new ArrayList<Query>();

			for (int i = 0; i < queries.size(); i++) {
				JSONObject queryTemp = (JSONObject) queries.get(i);
				Query q = new Query();
				if (queryTemp != null) {

					if (queryTemp.get("query") != null) {
						q.setQuery((String) queryTemp.get("query"));
					}

					if (queryTemp.get("name") != null) {
						q.setName((String) queryTemp.get("name"));
					}
					
					if (queryTemp.get("type") != null) {
						q.setType(((Long) queryTemp.get("type")).longValue());
					}
					
					if (queryTemp.get("active") != null) {
						q.setActive(((Long) queryTemp.get("active")).longValue());
					}


					queryList.add(q);
				}
			}

			log.info("Config Loaded");

		} catch (Exception e) {
			log.error("Error loading configuration", e);
		}
	}

}
<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/TaskMethod.java
package com.localidata.interceptor;

import java.util.ArrayList;

import org.apache.log4j.Logger;

public class TaskMethod {

	private static Logger log = Logger.getLogger(TaskMethod.class);
	private TaskConfig config;
	private ArrayList<ResponseQuery> responseList;
	private int petitionsOK;
	private int timelimit;
	private int petitionsBeforeReport;
	private SendMailSSL emailSender;

	public TaskConfig getConfig() {
		return config;
	}

	public void setConfig(TaskConfig config) {
		this.config = config;
	}

	public ArrayList<ResponseQuery> getResponseList() {
		return responseList;
	}

	public void setResponseList(ArrayList<ResponseQuery> responseList) {
		this.responseList = responseList;
	}

	public int getPetitionsOK() {
		return petitionsOK;
	}

	public void setPetitionsOK(int petitionsOK) {
		this.petitionsOK = petitionsOK;
	}

	public int getTimelimit() {
		return timelimit;
	}

	public void setTimelimit(int timelimit) {
		this.timelimit = timelimit;
	}

	public int getPetitionsBeforeReport() {
		return petitionsBeforeReport;
	}

	public void setPetitionsBeforeReport(int petitionsBeforeReport) {
		this.petitionsBeforeReport = petitionsBeforeReport;
	}

	public SendMailSSL getEmailSender() {
		return emailSender;
	}

	public void setEmailSender(SendMailSSL emailSender) {
		this.emailSender = emailSender;
	}

	public void testQueries() {

		for (Query q : config.getQueryList()) {
			if (q.getActive() == 1) {
				long startTime = System.currentTimeMillis();
				log.info("Throw " + q.getName());
				int size = 0;
				if (q.getType() == 1)
					size = SPARQLQuery.Query(q.getQuery(), config.getEndpoint());
				else
					size = SPARQLQuery.URIQuery(config.getEndpoint() + "?" + q.getQuery());
				long endTime = System.currentTimeMillis();
				double duration = (endTime - startTime);
				duration = duration / 1000.0;
				responseList.add(new ResponseQuery(duration, size, q.getName()));
			}
		}

		ArrayList<ResponseQuery> errors = new ArrayList<ResponseQuery>();
		for (ResponseQuery rq : responseList) {
			if ((rq.getSize() <= 0) || rq.getTime() > timelimit) {
				errors.add(rq);
			}
		}

		if (errors.size() > 0) {
			petitionsOK = 0;
			String bodyMail = "There are errors in the next Query/ies" + System.getProperty("line.separator");
			bodyMail += System.getProperty("line.separator");
			bodyMail += Utils.responseArrayToString(errors);
			// log.info(bodyMail);
			emailSender.send(config.getUsuario(), config.getPassword(), config.getDestinos(), "Some of the queries do not work", bodyMail);
		} else {
			petitionsOK++;
			if (petitionsOK == petitionsBeforeReport + 1) {
				petitionsOK = 0;
				String bodyMail = "There aren't errors after " + petitionsBeforeReport + " times" + System.getProperty("line.separator");
				bodyMail += System.getProperty("line.separator");
				bodyMail += "The last test are theses: " + System.getProperty("line.separator");
				bodyMail += System.getProperty("line.separator");
				bodyMail += Utils.responseArrayToString(responseList);
				// log.info(bodyMail);
				emailSender.send(config.getUsuario(), config.getPassword(), config.getDestinos(), "The queries work fine", bodyMail);
			}

			log.info(Utils.responseArrayToString(responseList));

			log.info(petitionsOK + " tests passed");
		}

		errors.clear();
		responseList.clear();

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
<file_sep>/README.md
SPARQL Interceptor
=================

This is a simple Web-based tool where you can test and monitor SPARQL queries over a set of SPARQL endpoints. The tool executes a set of queries periodically over a SPARQL endpoint. All these parameters (queries, SPARQL endpoint, periodicity of evaluations) can be configured, as explained below.

If any query fails (that is, it provides a timeout or zero results), it will send an e-mail, using a Google account to the e-mail account that is also specified in the configuration file. This may be improved in the feature to look for specific results.

When the whole process of testing queries is OK for all queries, a counter increases. When the counter is equal to a value (that can be also configured) the tool sends an e-mail with a report of the last execution time.

The tool is developed in Java, as a Java Application and as a Web Application (without a graphic enviroment).

The queries.json file is a deprecated version of the unit test file, as it was initially used when Jenkins was not used for this purpose. It is maintained in the repository for provenance reasons.


#JUnit Test of SPARQL queries

We added a new funcionality, with junit tests (mvn test) you can execute queries and test the number of rows that the query return match with a specific number.

If you want to add a query, you must create a file inside the "queries" directory with this format:


\# Description: A description of the query  
\# Result: number of results  
Query line 1  
Query line 2  
....  
Query line n  


## Example

```
# Description: Venues with no cell associated to them. It should be zero.
# Result: 0
SELECT ?venue (COUNT(DISTINCT ?cell) AS ?numberCells)
WHERE
{
  ?venue a dul:Place .
  ?venue locationOnt:cell ?cell

} GROUP BY ?venue HAVING (COUNT(DISTINCT ?cell) = 0)
```

## Be carefull with Jena
Jena execute these queries, you must test your queries in Jena first, maybe you put a 0 but Jena return -1, or the query is ok in Virtuoso but fails here.


# Deploy on Jenkins

Here I describe the steps to desploy this project without use any source control.

Usually the Jenkins home is:  /var/lib/jenkins 

When you are on Jenkins, you must add a new Item:

	- Add the name of the project
	- Select Maven project and click the "ok" button
	
Then you must do this steps:

    - Build the Project at least once, (it will fail), but Jenkins will create the structure jenkins/workspace/PROJECTNAME/
    - Copy the project files to jenkins/workspace/PROJECTNAME/
    - Build again and configure appropriately
    
Back to the Jenkins project configuration:

	In Build Triggers:
	
		- Check Build periodically and write in the Schedule a cron expression to configure it. For example: "H/30 * * * *"
	
	In Build:
	
		- Root POM: must be "pom.xml"
		- Goals and options: I write "clean package test"

	And that´s enought.
	
	With this configuration, Jenkins will run the test every 30 minutes.


#Configuration

This tool has three configuration files:

##log4j.properties

The log configuration, you can see this [tutorial](http://www.tutorialspoint.com/log4j/log4j_configuration.htm) to learn how to configure it.

##conf.properties

This file has the following attributes to configure:

####time

The periodicity of every query execution cycle.

Example: 3600000

####emails

List of email address of the people that you want to send an e-mail for errors or reports.

Example: <EMAIL>, <EMAIL>, <EMAIL>

####user

The Google account used to send e-mails.

Example: <EMAIL>

####password

The Google account password.

Example: <PASSWORD>

####endpoint

The SPARQL Endpoint where the queries will be executed.

Example: http://dev.3cixty.com/sparql

####timeout

The max-time for a  timeout error, expressed in milliseconds.

Example: 60000

####timelimit

The max-time for an alert via e-mail, in seconds.

Example: 30

####petitionsBeforeReport

The number of OK petitions before sending a report with the last execution time.

Example: 24

##queries.json

Here you configure all the queries that you want to test. The file is an array that contains all the queries.

Each query has four attributes:

####type

The type can be 1 or 2.

The type 1 uses "the JENA parser" and only works when the query is standard. If you use fucntions like "bif:intersect” from Virtuoso you cannot use this type.

The type 2 uses the URL to send the query. You must begin with que "query" parameter, and the output format must be "json".

####active

Active can be 0 or 1. The query is only executed if active is set to 1.

####name

The name of the query

####query

That is the query.

If the type is 1 you must write the query as follows:

    select distinct ?Concept where {[] a ?Concept} LIMIT 100

If the type is 2 you must write it as follows:

    query=select+distinct+%3FConcept+where+{[]+a+%3FConcept}+LIMIT+100&format=json&timeout=0&debug=on

Be carefull with the double quote, here it must be a single quote.

#Running


##JAR

You can run the jar with this command:

    java -jar SPARQLInterceptor.jar

You can stop pressing CONTROL + C.

If you are on LINUX you can add the " &" at the end of the command to run it in background:

    java -jar SPARQLInterceptor.jar &

You can stop it with a kill command:

    kill -9 pid

But you need to know the PID of the process. With this command you can obtain the pids of all Java processes

    jps

##WAR

You can run SPARQL Interceptor deploying the war on servlet container.

Where the webapp is deployed you can edit the configuration files inside the WEB-INF folder.
<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/TaskProcess.java
package com.localidata.interceptor;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class TaskProcess {
	
	private static Logger log = Logger.getLogger(TaskProcess.class);
	
	private static Timer timer;
	private static TimerTask timerTask;	
	private static int timelimit=30;	
	private TaskConfig config;	
	private ArrayList<ResponseQuery> responseList;	
	private SendMailSSL emailSender = new SendMailSSL();
	private int petitionsOK=0;
	private int petitionsBeforeReport=100;
	
	private TaskMethod method;

	public TaskProcess()
	{
			responseList=new ArrayList <ResponseQuery>();
			config=new TaskConfig(null);
			SPARQLQuery.timeOut=Integer.parseInt(config.getTimeout());
			timelimit=Integer.parseInt(config.getTimelimit().trim());
			petitionsBeforeReport=Integer.parseInt(config.getPetitionsBeforeReport().trim());
			
			method=new TaskMethod();
			method.setConfig(config);
			method.setEmailSender(emailSender);
			method.setPetitionsBeforeReport(petitionsBeforeReport);
			method.setPetitionsOK(petitionsOK);
			method.setResponseList(responseList);
			method.setTimelimit(timelimit);
			
	}
	
	public void init()
	{			
			timerTask = new TimerTask() {
				public void run() {
					log.info("Init process");
					method.testQueries();
					log.info("End proccess");
				}
			};
			
			timer = new Timer();
			// timer.schedule(this, 0, 10*60*1000); //  10 minutes
			timer.schedule(timerTask, 0, config.getTime());

		
	}
	


	
	
	public static void main(String[] args) {
		PropertyConfigurator.configure("log4j.properties");		
		TaskProcess t=new TaskProcess();
		t.init();
	}

}
<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/Utils.java
package com.localidata.interceptor;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;

import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.client.HttpClient;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.localidata.queries.ListOfQueries;
import com.localidata.queries.QueryBean;



public class Utils {
	
	private static Logger log = Logger.getLogger(Utils.class);

	public static Properties leerProperties(String ruta) throws FileNotFoundException, IOException {
		Properties propiedades = new Properties();
		propiedades.load(new FileInputStream(ruta));
		return propiedades;
	}

	private static String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}

	public static JSONObject leerJSONFile(String file) throws IOException, ParseException {
		FileInputStream fis = new FileInputStream(file);

		BufferedReader rd = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
		String jsonText = readAll(rd);

		JSONParser parser = new JSONParser();
		JSONObject obj = null;

		obj = (JSONObject) parser.parse(jsonText);

		return obj;

	}
	
	public static String procesaURL(String urlCadena, int timeout) throws IOException,MalformedURLException  {		
		
		URL url = new URL(urlCadena);	      

    HttpURLConnection huc = (HttpURLConnection) url.openConnection();
    HttpURLConnection.setFollowRedirects(false);
    huc.setConnectTimeout(timeout);
    huc.setRequestMethod("GET");
    huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
    huc.connect();
    InputStream input = huc.getInputStream();
    
    
		
		StringBuffer contenidoURL=new StringBuffer("");		
			      
	      
	      BufferedReader in = null;
	      //Volcamos lo recibido al buffer
	      in = new BufferedReader(new InputStreamReader(huc.getInputStream())); 
	      // Transformamos el contenido del buffer a texto
	      String inputLine;		      	      
	      if (in!=null){	    	  
	    	  
	    		  while ((inputLine = in.readLine()) != null)
			      {	  
	    			  contenidoURL.append(inputLine+"\n");
			      }	
	    	  		    
		      in.close();	
	      }
		return contenidoURL.toString();
	}
	
	public static String responseArrayToString(ArrayList<ResponseQuery> errors) {
		String body="";
		for (ResponseQuery rq:errors)
		{
			body+= rq.getName()+":"+System.getProperty("line.separator");
			body+= "\tNumber of results: "+rq.getSize()+System.getProperty("line.separator");
			body+= "\tExecution time: "+rq.getTime()+ " seconds"+System.getProperty("line.separator");
			body+= System.getProperty("line.separator");
		}
		return body;
	}
	
	
	public static String getQueryFromGitHub(String url) {

		StringBuffer sb = new StringBuffer();
		HttpURLConnection httpConnection =null;
		try {
			URL targetUrl = new URL(url);
			
			httpConnection = (HttpURLConnection) targetUrl.openConnection();
			httpConnection.setDoOutput(true);
			httpConnection.setRequestMethod("GET");

			
			BufferedReader responseBuffer = new BufferedReader(new InputStreamReader((httpConnection.getInputStream())));

			String output;

			while ((output = responseBuffer.readLine()) != null) {
				sb.append(output + System.getProperty("line.separator"));				
			}

			
			

		} catch (MalformedURLException e) {
			log.error("Error with the URI: " + url );
			log.error(e);

		} catch (IOException e) {
			log.error("IOError: " + url);
			log.error(e);
		}finally{
			httpConnection.disconnect();
		}

		return sb.toString();

	}

	
	public static boolean logConfLoad(String path) {
		File logProperties = new File(path);
		if (!logProperties.exists()) {
			System.out.println("log4j.properties not found. Please generate a log4j.properties.");
			return false;
		} else {
			PropertyConfigurator.configure(path);
			return true;
		}
	}
	
	public static String readFile(String file) throws IOException {
		FileInputStream fis = new FileInputStream(file);

		BufferedReader rd = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8")));
		String jsonText = readAll(rd);

		return jsonText;

	}
	
	public static void realTest(QueryBean bean) {
		if (bean.getCompareType().equals(QueryBean.EQUAL)) {
			if (bean.getExpectedResult() != bean.getResultSize()) {
				writeData(bean);
			}
			assertEquals(bean.getExpectedResult(), bean.getResultSize());
		}else if (bean.getCompareType().equals(QueryBean.GREATER)) {
			if (bean.getResultSize() <= bean.getExpectedResult()) {
				writeData(bean);
			}
			assertTrue( bean.getResultSize() > bean.getExpectedResult());
		}else if (bean.getCompareType().equals(QueryBean.LESS)) {
			if (bean.getResultSize() >= bean.getExpectedResult()) {
				writeData(bean);
			}
			assertTrue( bean.getResultSize() < bean.getExpectedResult());
		}
	}
	
	public static void writeData(QueryBean bean) {
		System.out.println(bean.getDescription());
		System.out.println("");
		System.out.println("Http Query:");
		System.out.println("");
		System.out.println(bean.getHttpQuery());
		System.out.println("");
		System.out.println("Query:");
		System.out.println("");
		System.out.println(bean.getQuery());
	}
	
	public static Collection<Object[]> generateData(ListOfQueries list) {
		Collection<Object[]> data = new ArrayList<Object[]>();
		for (QueryBean bean : list.getQueryList()) {
			Object[] arg1 = new Object[] { bean };
			data.add(arg1);
		}
		return data;
	}
	
	public static boolean checkURL(String url) {
		HttpURLConnection connection;
		try {
			connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setRequestMethod("HEAD");
			int responseCode = connection.getResponseCode();
			if (responseCode != 200) {
				return false;
			}			
		} catch (Exception e) {
			//log.error("Error testing URL",e);
			return false;
		}
		return true;		
}
	
	public static String watch(String url) {	
	
	StopWatch watch = new StopWatch();
	
	SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
	String r=dateFormat.format(new Date());
	
	boolean ok=false;

	try {
		watch.start();
		ok=checkURL(url);
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		watch.stop();
	}

	if (ok)
		r+=","+watch.getTime();
	else
		r+=",0";		
	
	return r;
	}
	
	
	public static void main(String[] args) {
		String json="http://jsonpdataproxy.appspot.com/?url=http://sandbox-ckan.localidata.com/dataset/e5b37d9a-f551-4375-872e-a9fad5be6c8b/resource/dcae2eab-7ea5-4966-850b-7695979e7c69/download/recurso.csv";		
		System.out.println(watch(json));
	}

}
<file_sep>/SPARQLInterceptor/src/com/localidata/interceptor/Task.java
package com.localidata.interceptor;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import java.io.File;
import java.util.ArrayList;
import java.util.TimerTask;
import java.util.Timer;

public class Task implements ServletContextListener {

	private static Logger log = Logger.getLogger(Task.class);
	
	private static Timer timer;
	private static TimerTask timerTask;	
	private static int timelimit=30;
	
	private TaskConfig config;
	
	private ArrayList<ResponseQuery> responseList;
	
	private SendMailSSL emailSender = new SendMailSSL();

	private int petitionsOK=0;
	private int petitionsBeforeReport=100;
	
	private TaskMethod method;


	private void initLogs(ServletContextEvent evt) {

		String log4jLocation = evt.getServletContext().getRealPath("/") + "WEB-INF" + File.separator + "log4j.properties";

		ServletContext sc = evt.getServletContext();

		File ficheroLogProperties = new File(log4jLocation);
		if (ficheroLogProperties.exists()) {
			System.out.println("Initializing log4j with: " + log4jLocation);
			PropertyConfigurator.configure(log4jLocation);
			
			responseList=new ArrayList <ResponseQuery>(); 
			
		} else {
			System.err.println("*** " + log4jLocation + " file not found, so initializing log4j with BasicConfigurator");
			BasicConfigurator.configure();
		}

	}

	

	public void contextInitialized(final ServletContextEvent evt) {

		initLogs(evt);
		config=new TaskConfig(evt);
		SPARQLQuery.timeOut=Integer.parseInt(config.getTimeout());
		timelimit=Integer.parseInt(config.getTimelimit().trim());
		petitionsBeforeReport=Integer.parseInt(config.getPetitionsBeforeReport().trim());
		
		method=new TaskMethod();
		method.setConfig(config);
		method.setEmailSender(emailSender);
		method.setPetitionsBeforeReport(petitionsBeforeReport);
		method.setPetitionsOK(petitionsOK);
		method.setResponseList(responseList);
		method.setTimelimit(timelimit);
		
		timerTask = new TimerTask() {
			public void run() {
				log.info("Init process");
					method.testQueries();
				log.info("End proccess");
			}
		};

		
		
		timer = new Timer();
		// timer.schedule(this, 0, 10*60*1000); //  10 minutes
		timer.schedule(timerTask, 0, config.getTime());

	}

	

	public void contextDestroyed(ServletContextEvent evt) {
		timer.cancel();
	}

	

	
	public static void main(String[] args) {
		PropertyConfigurator.configure("log4j.properties");
		log.info("Ready to rock");
		
	
		
		
	}
	



}