Code Search for Developers
 
 
  

FitNesse.java from MASE: Agile Software Engineering at Krugle


Show FitNesse.java syntax highlighted

package ca.ucalgary.cpsc.ebe.fitClipse.connector;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.internal.UIPlugin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import ca.ucalgary.cpsc.ebe.fitClipse.runner.FitTest;
import ca.ucalgary.cpsc.ebe.fitClipse.ui.testHierarchy.model.WikiPageModel;
import ca.ucalgary.cpsc.ebe.fitClipse.util.Constants;

public class FitNesse implements IServerConnector {

	private Socket socket = null;

	private ServerConfiguration config = ServerConfiguration.getInstance();

	private static final boolean POST = true;

	private static final boolean GET = false;

	private static final Pattern inputsPattern = Pattern
	.compile("<input type=\"hidden\" name=\"(.+?)\" value=\"(.+?)\"/>");
//	private static final String FITCLIPSE_ROOT = "FitClipse.ProjectS"; ===== webPath

	public FitNesse (ServerConfiguration config) {
		this.config = config;
	}

	public FitTest getFitTestFromDatabase(long id, String qName) {		
		try{
			String url = "/"+ Constants.FITNESSE_FIT_TEST;
		String content = "suiteID="+id+"&testQName="+qName;
		List http = socketPostConnector(url,content,null,null);
		String xml = http.get(1).toString();
		FitTest test = constructFitTestFromXml(xml);
//		System.out.println("inside FitNesse: test outPut is: "+test.getTestOutput());
//		System.out.println("inside FitNesse: testOutputis"+test.getTestOutput()+test.getTestHtml());
		return test;
		}catch (Exception e){
			MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error!", "Unable to get FIT test from the server!");		
			e.printStackTrace();
			return null;
		}
	}

	private FitTest constructFitTestFromXml(String xml) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		FitTest test = new FitTest(null,null,null);
		try {
			Document doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
			Element docEle = doc.getDocumentElement();
			NodeList outPutList = docEle.getElementsByTagName("outPut");
			String outPut = outPutList.item(0).getTextContent();
			NodeList resultHtmlList = docEle.getElementsByTagName("testHtmlResult");
			String resultHtml = resultHtmlList.item(0).getTextContent();
			test.setTestHtml(resultHtml);
			test.setTestOutput(outPut);		
//			System.out.println("inside FitNesse: "+test.getAttribute("name"));
			return test;
		} catch (SAXException e) {
			e.printStackTrace();
			MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error!", "Unable to recontruct test list!");		
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			return null;
		}
		
	}

	public String getConnectorName() {
		return "FitNesse";
	}

	public String getFitPageText(String name) {
		name = name.replace(".root","");
		name = config.getWebPath()+name;
//		System.out.println("name is:"+name);
		String url = "/" + name + Constants.FITNESSE_PAGE_RAW_CONTENT;
		List http = socketGetConnector(url,name,"");
		String content = http.get(1).toString();
		return content;
	}

	public boolean saveGenericWikiPage(WikiPageModel model, String content) {
		String message = null;
		String pageQName = model.getQName();//do not have to get rid of ".root" this is done in does page exist
//		System.out.println("pageQName is: "+pageQName);
		boolean pageExist = doesPageExist(pageQName);
//		System.out.println("page exist: "+pageExist);
		if (pageExist){			
			String name = config.getWebPath() + pageQName;
			name = name.replace(".root", "");
//			System.out.println("name is; "+name);
			String url = "/" + name + Constants.FITNESSE_PAGE_SAVE;
//			System.out.println("url is: "+url);
			String pageContent = constructPageContentForSavePageContent(name, url, content);
//			String message = socketPostConnector(url, pageContent, name, EditorConstants.FITNESSE_PAGE_EDIT);
			List http = socketPostConnector(url, pageContent, name, Constants.FITNESSE_PAGE_EDIT);
			message = http.get(0).toString();
//			System.out.println("message is: " + message);
		}else{
			WikiPageModel parent = model.getParent();
			String parentContent = getFitPageText(parent.getQName());
			parentContent = parentContent + "\n^" + model.getName();
			saveGenericWikiPage(parent, parentContent);
//			saveGenericWikiPage(model,"");			
			String name = config.getWebPath() + pageQName;
			name = name.replace(".root", "");
//			System.out.println("name is; "+name);
			String url = "/" + name + Constants.FITNESSE_PAGE_SAVE;
//			System.out.println("url is: "+url);
			String pageContent = constructPageContentForSavePageContent(name, url, "");
//			String message = socketPostConnector(url, pageContent, name, EditorConstants.FITNESSE_PAGE_EDIT);
			List http = socketPostConnector(url, pageContent, name, Constants.FITNESSE_PAGE_EDIT);
			message = http.get(0).toString();
//			System.out.println("message is: \n" + message);			
		}
		if (message.contains("HTTP/1.1 303 See Other")) {
			return true;
		} else
			MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Unable to save to the server: "
					+ config.getHost() + ":" + config.getWebPort());
			return false;

	}

	public void deleteWikiPage(String qName) {
		qName = qName.replace(".root","");
//		System.out.println("Page to be deleted: "+qName);
		String originQName = qName;
		qName = config.getWebPath() +qName;
		int index = qName.lastIndexOf(".")+1;
		String pageName = qName;	
		pageName = qName.substring(index, qName.length());

		String fatherNameSpace = null;
		String url = "/" + qName + Constants.FITNESSE_PAGE_DELETE;
		socketGetConnector(url,qName,"?responder=deletePage");

		String fatherPage = originQName.substring(0,originQName.lastIndexOf("."));
		fatherPage = config.getWebPath() + fatherPage;
		String fatherUrl = "/" + fatherPage + Constants.FITNESSE_PAGE_RAW_CONTENT;

		String fatherPageName = null;
		fatherNameSpace = originQName.substring(0,originQName.lastIndexOf("."));
		int index2 = fatherNameSpace.lastIndexOf(".");
		if(index2==0){
			fatherPageName = fatherNameSpace.replace(".","");
			fatherNameSpace = ".root";
		}else{
			fatherPageName = fatherNameSpace.substring((index2+1),fatherNameSpace.length());
			fatherNameSpace = fatherNameSpace.substring(0,index2);			
		}

		WikiPageModel fatherModel = new WikiPageModel(fatherPageName,fatherNameSpace);

		String message = socketGetConnector(fatherUrl,fatherPage,"").get(1).toString();
//		System.out.println("*****message is: *****\n"+message);
		String newFatherContent = message;
		newFatherContent = message.replace("^"+pageName,"");
		saveGenericWikiPage(fatherModel,newFatherContent);

	}

	public boolean tagPageAsFitTest(String name, boolean value) {
		//name is qName = .FitClipseProject.JanIteration.BigRefactoring
		
		String qName = config.getWebPath()+name;
		String url = "/"+qName+Constants.FITNESSE_FIT_TEST_TAG_AS;
		String content = "fitTest="+value;
		List http = socketPostConnector(url,content,"","");
		if (http.get(1).toString().contains("OK")){
			return true;
		}else {
			MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Unable to tag the page as FIT test!");
			return false;
		}
	}

	public boolean doesPageExist(String pName) {
//		System.out.print("inside FitNese:doesPageExist pName is: "+pName);
//		System.out.println("inside FitNese:doesPageExist: web path is: "+config.getWebPath());
		pName = config.getWebPath()+pName;
		pName = pName.replace(".root","");
		String fatherPage = pName;
		int index1 = fatherPage.lastIndexOf(".");
		if(index1!=-1){
			fatherPage = fatherPage.substring(0,index1);
		}else{
			fatherPage = "";
		}
		int index = pName.lastIndexOf(".")+1;
		String newPageName = pName.substring(index, pName.length());
		String pageContent = "newPageName="+newPageName;
		String url = "/" + fatherPage + Constants.FITNESSE_PAGE_EXIST;
		List http = socketPostConnector(url, pageContent, fatherPage, "");
		String message = http.get(1).toString();
		if(message.contains("true")){
			return true;
		}else return false;
	}

	public List<FitTest> getFitTestHistory(String qName) {
		try{
			String xml;		
			String content = "testName="+qName;
			String url = "/" + Constants.FITNESSE_FIT_TEST_HISTORY;
			List http = socketPostConnector(url,content,"","");
			xml = http.get(1).toString();
//			System.out.println("FitNesse: test result xml is: "+xml);
			List <FitTest> tests= constructFitTestListFromXml(xml);
			return tests;
		}catch (Exception e){
			e.printStackTrace();
			MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Unable to get test history from the server!");
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	private List<FitTest> constructFitTestListFromXml(String xml) {
		List <FitTest> tests = new LinkedList();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();		
		Document doc;
		try {
			doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml)));
			Element docEle = doc.getDocumentElement();
			NodeList testResultNodeList = docEle.getElementsByTagName("fit_test_result");
			for(int i=0; i<testResultNodeList.getLength();i++){
				Element testResultEle = (Element)testResultNodeList.item(i);
				FitTest ft = new FitTest(null,null,null);
				int right = Integer.parseInt(testResultEle.getAttribute("right"));
				int wrong = Integer.parseInt(testResultEle.getAttribute("wrong"));
				int exceptions = Integer.parseInt(testResultEle.getAttribute("exceptions"));
				int ignored = Integer.parseInt(testResultEle.getAttribute("ignored"));
				ft.setNumRight(right);
				ft.setNumWrong(wrong);
				ft.setNumExceptions(exceptions);
				ft.setNumIgnored(ignored);	
				tests.add(ft);
			}
		} catch (SAXException e) {
//			MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "FIT test history is not in the right format!");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (Exception e){
			e.printStackTrace();
		}
		return tests;
	}

	public long persistTestSuite(String testRoot, boolean isSuite,
			Timestamp executionDate, long executionTime, List<FitTest> tests) {
		StringBuffer xml = new StringBuffer();
		xml = createXML(testRoot, isSuite, executionDate, executionTime, tests);
		System.out.println("the test result xml is: \n"+xml.toString());
		String url = "/" + Constants.FITNESSE_SAVE_TEST_RESULT;
		List http = socketPostConnector(url,xml.toString(),"","");
		long sid;
		//the string got from the server has a "\n" at the end
		try{
			sid = Long.parseLong(http.get(1).toString().replaceAll("\n",""));		
		}catch (Exception e){
			e.printStackTrace();
			Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
			MessageDialog.openError(shell, "Error!", "Save test result failed!");		
//			System.out.println("error in saving result!");
			return -1;
		}
		return sid;
	}

	private StringBuffer createXML(String testRoot, boolean isSuite, Timestamp executionDate, long executionTime, List<FitTest> testResults) {
		StringBuffer xml = new StringBuffer();
		xml.append("<fit_test_result_tree>\n");
		xml.append("<fit_test_suite name = \"").append(testRoot).append("\" eDate = \"").append(executionDate).append("\" eTime = \"").append(executionTime).append("\" suite = \"").append(isSuite).append("\">\n");
		for (FitTest ft: testResults){
			xml.append("<fit_test name = \"").append(ft.getTestName()).append("\" right = \"").append(ft.getNumRight()).append("\" wrong = \"").append(ft.getNumWrong()).append("\" exceptions = \"").
			append(ft.getNumExceptions()).append("\" ignored = \"").append(ft.getNumIgnored()).append("\" startTime = \"").append(ft.getStartTime()).append("\" endTime = \"").append(ft.getEndTime()).append("\" wikiPageID = \"")
			.append("-1").append("\" executionTime = \"").append(ft.getExecutionTime()).append("\" >\n");
			xml.append("<testOutput>\n<![CDATA[").append(ft.getTestOutput()).append("]]>\n</testOutput>");
			xml.append("<testHtml>\n<![CDATA[").append(ft.getTestHtml()).append("]]>\n</testHtml>");
			xml.append("</fit_test>\n");
		}
		xml.append("</fit_test_suite>\n");
		xml.append("</fit_test_result_tree>\n");
		return xml;
	}

	//adding HTML getter for running test
	public String getHTMLForPage(String qName){
		qName = config.getWebPath() +qName;
		String fatherName = getFatherName(qName);
		String url = "/" +qName;
		String html = socketGetConnector(url,fatherName,"").get(1).toString();
//		System.out.println("html is: \n"+html+"\n THE END....");
		return html;
	}

	private String getFatherName(String qName) {
		return qName.substring(0,qName.lastIndexOf("."));
	}

	private List socketGetConnector(String url, String pageName, String refererType) {

		InputStream in = null;
		OutputStream out = null;
		StringBuffer messageBody = new StringBuffer();
		StringBuffer messageHeader = new StringBuffer();
		// socket progress
		try {
			socket = new Socket(config.getHost(), Integer.parseInt(config.getWebPort()));
			in = socket.getInputStream();
			out = socket.getOutputStream();

			PrintWriter writer = new PrintWriter(out);
			String refererUrl = pageName + refererType;
			String header = constructHttpHeader(url, 0, refererUrl, GET);

			writer.println(header);
//			System.out.println("HEADER: \n"+header);
			writer.flush();

			// read the response
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));

			String line = null;

			while ((line = reader.readLine()) != null && !"".equals(line)) {
				messageHeader.append(line).append("\n");
//				System.out.println("header: " + line);
			} 

			while ((line = reader.readLine()) != null) {
				messageBody.append(line).append("\n");
			}

		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		List <String> Http = new LinkedList<String>();
//		System.out.println("body is: "+body);
		Http.add(messageHeader.toString());
		Http.add(messageBody.toString());
		return Http;
	}

	@SuppressWarnings("unchecked")
	private List socketPostConnector(String url, String pageContent,
			String pageName, String refererType) {
		InputStream in = null;
		OutputStream out = null;
		StringBuffer messageBody = new StringBuffer();
		StringBuffer messageHeader = new StringBuffer();

		// socket progress
		try {
			socket = new Socket(config.getHost(), Integer.parseInt(config
					.getWebPort()));
			in = socket.getInputStream();
			out = socket.getOutputStream();
			PrintWriter writer = new PrintWriter(out);
			int length = pageContent.getBytes().length;
			String refererUrl = pageName + refererType;
			String header = constructHttpHeader(url, length, refererUrl, POST);
			writer.println(header);
			System.out.println(header);
			writer.println(pageContent);
			System.out.println(pageContent);
			writer.flush();
			// read the response
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(in));
			String line = null;
			// get rid of extra lines
			while ((line = reader.readLine())!=null && !"".equals(line)){
				messageHeader.append(line).append("\n");            
			}
			while ((line = reader.readLine()) != null) {
				messageBody.append(line).append("\n");
			}
		} catch (NumberFormatException e) {
//			MessageDialog.openError(UIPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(), "Error1", "Can not download FIT tests from the server! \nServer may be not running or unresearchable.");
			e.printStackTrace();
		} catch (UnknownHostException e) {
//			MessageDialog.openError(UIPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(), "Error2", "Can not download FIT tests from the server! \nServer may be not running or unresearchable.");
			e.printStackTrace();
		} catch (IOException e) {
			MessageDialog.openError(UIPlugin.getDefault().getWorkbench().getActiveWorkbenchWindow().getShell(), "Error3", "Server may be not running or unresearchable.");
			e.printStackTrace();
		}
		List <String> http = new LinkedList();
		http.add(messageHeader.toString());
		http.add(messageBody.toString());
		return http;
	}

	private String constructPageContentForSavePageContent(String pageName, String url,
			String content) {
		String editUrl = "/" + pageName + Constants.FITNESSE_PAGE_EDIT;
		String message = socketGetConnector(editUrl,pageName,"").get(1).toString();
		HashMap inputs = getInputHashMap(message);
		String responder = inputs.get("responder").toString();
		String saveId = inputs.get("saveId").toString();
		String ticketId = inputs.get("ticketId").toString();
		StringBuffer pageContent = new StringBuffer();
		try {
			content = URLEncoder.encode(content, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		pageContent.append("responder=" + responder + "&saveId=" + saveId
				+ "&ticketId=" + ticketId + "&pageContent=" + content
				+ "&save=Save&fixtureTable=default\n");
		return pageContent.toString();
	}

	private HashMap getInputHashMap(String message) {
		HashMap<String, String> parameter = new HashMap<String, String>();
		Matcher matcher = inputsPattern.matcher(message);
		while (matcher.find()) {
			if (!parameter.containsKey(matcher.group(1))) {
				parameter.put(matcher.group(1), matcher.group(2));
			}
		}
		return parameter;
	}

	private String constructHttpHeader(String url, int length, String referer,
			boolean type) {
		StringBuffer header = new StringBuffer();
		String refererUrl = ("http://" + config.getHost() + "/" + referer);
		if (type) {
			header.append("POST " + url + " HTTP/1.1\n");
			header.append("Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\n");
			header.append("Referer: " + refererUrl + "\n");
			header.append("Accept-Language: en-us\n");
			header.append("Content-Type: application/x-www-form-urlencoded\n");
			header.append("Accept-Encoding: gzip, deflate\n");
			header.append("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\n");
			header.append("Host: " + config.getHost() + "\n");
			header.append("Content-Length: " + length + "\n");
			header.append("Connection: Keep-Alive\n");
			header.append("Cache-Control: no-cache\n");
		} else {
			header.append("GET " + url + " HTTP/1.1\n");
			header.append("Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\n");
			header.append("Referer: " + refererUrl + "\n");
			header.append("Accept-Language: en-us\n");
			header.append("Accept-Encoding: gzip, deflate\n");
			header.append("User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)\n");
			header.append("Host: " + config.getHost() + "\n");
			header.append("Connection: Keep-Alive\n");
		}
		return header.toString();
	}

	public String getWikiPageTree() {
		try{
			String url = "/" + config.getWebPath() + Constants.FITNESSE_PAGE_CHILDREN_TREE;
			String content = "projectNameSpace="+config.getProjectNameSpace();
			String xml = socketPostConnector(url,content,"","").get(1).toString();
			if (xml.contains("No this project:")){
				MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error!", "The wiki name space is not configured properly!");
			}else if (xml.contains("<title>Default Responder</title>")){
				MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error!", "The version of the server is not right!");
			}
			return xml;
		}catch(Exception e){
			MessageDialog.openError(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error!", "Can not get FIT test list from the server!");
			return null;
		}
	}

	public String getResultDetailsUrl(String qName) {
		String Url = "http://"+config.getHost()+"/"+config.getWebPath()+qName+Constants.FITNESSE_TEST_HISTORY_CHART;
		return Url;
	}

	public String getSuiteDetailsUrl(String qName){
		String Url = "http://"+config.getHost()+"/"+config.getWebPath()+qName+Constants.FITNESSE_FIT_TEST_SUITE_HISTORY_CHART;
		return Url;
	}

	public String getWikiEditorUrl(String qName) {
		String Url = "http://"+config.getHost()+"/"+config.getWebPath()+qName;
		return Url;
	}

}




See more files for this project here

MASE: Agile Software Engineering

The MASE project investigates methods to support the coordination and executable acceptance testing of software projects. Keywords: Agile methods, distributed teams, Extreme Programming. See http://ebe.cpsc.ucalgary.ca/ebe for more information.

Project homepage: http://sourceforge.net/projects/mase
Programming language(s): Java,XML
License: other

  FitNesse.java
  IServerConnector.java
  ServerConfiguration.java
  ServerConnectorFactory.java