Sindbad~EG File Manager

Current Path : /usr/home/beeson/public_html/dynamicgeometry/org/dynamicgeometry/diagrammer/
Upload File :
Current File : /usr/home/beeson/public_html/dynamicgeometry/org/dynamicgeometry/diagrammer/Tester.java

/*
 * Copyright (c) 2006, Ka Ki Cheung (and some parts, Zulaikha)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice,
 *     	 this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *     * Neither the name of San Jose State University nor the names of its
 *       contributors may be used to endorse or promote products derived from
 *       this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/* 12.21.06 Beeson modified calls to Execute1 since it now returns an array */
/* 12.22.06 Beeson added try-catch around Execute1  */

package org.dynamicgeometry.diagrammer;

// TODO: use generic instead of the plain old ArrayList
import java.util.*;
import java.sql.*;
import java.io.*;
import java.net.*;
import org.dynamicgeometry.diagrammer.*;
import org.dynamicgeometry.scripts.*;

public class Tester {
	public Tester(Diagrammer dia) throws Exception {
//		if(dia == null)
//			throw new Exception("Diagrammer for Tester cannot be null.");
		m_Diagrammer = dia;
	}

	private static final int FAR_ENUF = 40;

	private ArrayList startData2(String commandName) {
		ArrayList arguments = null;
		String[] argumentTypes = null;
		try {
			argumentTypes = Scripts.getParameterTypes(commandName);
		} catch(Throwable t) { }
		if(argumentTypes == null)
			return null;

		arguments = new ArrayList();
		// prepare the arguments for the construction
		for(int i = 0, c = 65; i < argumentTypes.length; ++i, ++c) {
			GeometricObject obj = null;
			try {
				Class cls = Class.forName("org.dynamicgeometry.diagrammer." + argumentTypes[i]);
				obj = (GeometricObject) cls.newInstance();
			} catch(Exception ex) {
				System.out.println("ERROR: startData2()");
				ex.printStackTrace();
			}
			if(obj == null)
				return null;

			obj.setVisible(true);
			obj.setIsInput(0);
			obj.setLabelFromString(new String(new byte[] {(byte) c}));
			obj.setSelected(true);
			boolean far_enuf;
			do {
				far_enuf = true;
				setLocation(obj, null);
				if(! (obj instanceof Point))
					break;
				for(int j = 0; j < arguments.size(); ++j) {
					if(! (arguments.get(j) instanceof Point)) {
						continue;
					}
					Point pj = (Point) arguments.get(j);
					Point p = (Point) obj;
					int d = dist(p.getX(), p.getY(), pj.getX(), pj.getY());
					if(d < FAR_ENUF) {
						System.out.println("! Dist " + d + " ain't far enuf.");
						far_enuf = false;
						break;
					}
				}
			} while(!far_enuf);	// Las Vegas
			arguments.add(obj);
//			printObject(obj, i);
		}
		// I shouldn't need to hack individual scripts!!!
		if(commandName.equals("ErectPerpendicular")) {
			// last point needs to align on the same line
			Point p0 = (Point) arguments.get(0);
			Point p1 = (Point) arguments.get(1);
			Point p2 = (Point) arguments.get(2);
			if(p0.getX() != p1.getX()) {
				double slope = (p0.getY() - p1.getY()) / (p0.getX() - p1.getX());
				System.out.println("Slope: " + slope);
				p2.setY((p2.getX() - p0.getX()) * slope + p0.getY());
			} else {
				p2.setX(p0.getX());
			}
		} else {
		}
		for(int i = 0; i < arguments.size(); ++i) {
			printObject((GeometricObject) arguments.get(i), i);
		}
		System.out.println("startData2(): " + arguments.size() + " objs for " + commandName);

		return arguments;
	}

	public void startData(String commandName) {
		m_Diagrammer.setFigure(startData2(commandName));
	}

	private int dist(double x1, double y1, double x2, double y2) {
		return (int) Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
	}

	private void setLocation(GeometricObject obj, GeometricObject from) {
		if(from == null) {
			if(obj instanceof Point) {
				((Point) obj).setX(randomInputX());
				((Point) obj).setY(randomInputY());
			} else {
				System.out.println("WARNING: setLocation() with " + obj.getClass());
				/* for arc, i wonder why executeprimitive doesn't
				 * validate the last 2 points to be on the circle...
				 */
				/* hopefully we won't have closedpolygon
				 * as we have no way to init #points...
				 */
				for(int i = 0; i < obj.getArgs().size(); ++i) {
					((Point) obj.getArgs().get(i)).setX(randomInputX());
					((Point) obj.getArgs().get(i)).setY(randomInputY());
				}
			}
		} else {
			// 'from' WILL match the type of 'obj'
			if(obj instanceof Point) {
				((Point) obj).setX(((Point) from).getX());
				((Point) obj).setY(((Point) from).getY());
			} else {
				obj.setIsInput(from.getIsInput());
				obj.setLevel(from.getLevel());
				obj.setConstruction(from.getConstruction());
				obj.setArgs(new ArrayList(from.getArgs()));
				/*for(int i = 0; i < obj.getArgs().size(); ++i) {

						Point p = (Point) obj;
						p.setX(((Point) from.getArgs().get(i)).getX());
						p.setY(((Point) from.getArgs().get(i)).getY());

				}*/
			}
		}
	}

	private int randomInputX() {
		return (int) (Math.random() * 200) + 150;
	}

	private int randomInputY() {
		return (int) (Math.random() * 100 + 100);
	}

	public String check(String commandName) {
		if(commandName == null)
			return exit("commandName cannot be null.");

		ArrayList theFigure = m_Diagrammer.getFigure();
		ArrayList userResults = m_Diagrammer.getSelected(), correctResults = new ArrayList();
		if(userResults.size() == 0)
			return "No, you need to select something to check.";
		int selectedIndex = theFigure.indexOf(userResults.get(0));

		// backup figure
		ArrayList originals = new ArrayList();
		for(int i = 0; i < theFigure.size(); ++i) {
			GeometricObject go = (GeometricObject) theFigure.get(i);
			if(go instanceof Point) {
				try {
					originals.add(go.clone());
				} catch(Throwable t) { }
			} else {
				originals.add(go.deepClone());
			}
		}
		originals = m_Diagrammer.getCopyArray(theFigure);

		// randomized arguments for the new figure
		ArrayList arguments = startData2(commandName);
		SymbolTable st = new SymbolTable();
		GeometricObject[] objs = new GeometricObject[arguments.size()];
		for(int i = 0; i < arguments.size(); ++i) {
			objs[i] = (GeometricObject) arguments.get(i);
		}
		GeometricObject[] results;
		try{
  		    results = st.Execute1(null, commandName, objs);
  		   }
  		catch (Exception ex)
  		   { ex.printStackTrace();
  		     return null;
  		   }
		GeometricObject o = results[0];
		correctResults.add(o);

		// set the same randomized input to original figure
		for(int i = 0; i < arguments.size(); ++i) {
			GeometricObject user = (GeometricObject) originals.get(i);
			GeometricObject test = (GeometricObject) arguments.get(i);
			setLocation(user, test);
		}

		userResults = new ArrayList();
		userResults.add(originals.get(selectedIndex));
		m_Diagrammer.updateConstructions(originals);

		// check the results
		if(userResults.size() != correctResults.size()) {
			return "no, number of results do no match.";
		}

		for(int i = 0; i < correctResults.size(); ++i) {
			GeometricObject user = (GeometricObject) userResults.get(i);
			GeometricObject correct = (GeometricObject) correctResults.get(i);
System.out.print("USER[" + i + "]: "); printObject(user, i);
System.out.print("CORRECT[" + i + "]: "); printObject(correct, i);
		}
		for(int i = 0; i < correctResults.size(); ++i) {
			GeometricObject user = (GeometricObject) userResults.get(i);
			GeometricObject correct = (GeometricObject) correctResults.get(i);
			if(user instanceof Triangle) {
				// special case: check perm of all 3 points
				ArrayList ua = (ArrayList) user.getArgs().clone(), ca = correct.getArgs();
				if(ua.size() != ca.size())
					return "no, [" + i + "] Triangle does not match.";
				ArrayList bk = new ArrayList();
				for(int j = 0; j < ca.size(); ++j) {
					GeometricObject cao = (GeometricObject) ca.get(j);
					int nbk = bk.size();
					for(int k = 0; k < ua.size(); ++k) {
						GeometricObject uao = (GeometricObject) ua.get(k);
						if(cao.equals(uao)) {
							ua.remove(uao);
							bk.add(uao);
							break;
						}
					}
					if(nbk == bk.size()) {
						break;
					}
				}
				if(bk.size() != ca.size()) {
					return "no, [" + i + "] Triangle does not match.";
				}
			} else if(! user.equals(correct)) {
				return "no, [" + i + "] GeometricObject does not match.";
			}
		}

		return "yes";
	}

	public void updateDatabase(String CommandName ) {

	/* Done by Zulaikha.
	*/
	 final String SERVER_URL = "../includes/recordgrade.php";

                String LessonName = CommandName;
		String result = null;
			           try
                        {
                          result = doPost(SERVER_URL, LessonName);
                        }
                        catch (IOException e)
                        {
                           result = "Error =" + e;
                        }
  }
  public static String doPost(String urlString, String LessonName)
      throws IOException
   {
      URL url = new URL(urlString);
      URLConnection connection = url.openConnection();
      connection.setDoOutput(true);

      PrintWriter out = new PrintWriter(connection.getOutputStream());

      boolean first = true;
         out.print("LessonName=");
         out.print(URLEncoder.encode(LessonName, "UTF-8"));


      out.close();
      Scanner in;
      StringBuilder response = new StringBuilder();
      try
      {
         in = new Scanner(connection.getInputStream());
      }
      catch (IOException e)
      {
         if (!(connection instanceof HttpURLConnection)) throw e;
         InputStream err
            = ((HttpURLConnection)connection).getErrorStream();
         if (err == null) throw e;
         in = new Scanner(err);
      }
      while (in.hasNextLine())
      {
         response.append(in.nextLine());
         response.append("\n");
      }

      in.close();
      return response.toString();
   }

	private String exit(String error) {
		return error;
	}

	private Diagrammer m_Diagrammer;

	public static void main(String[] cmdargs) {
		ArrayList args = null;
		try {
			String cmdfullname = "org.dynamicgeometry.scripts." + cmdargs[0];
			System.out.println("Command is " + cmdfullname);
			args = (new Tester(null)).startData2(cmdfullname);
		} catch(Exception ex) {
			ex.printStackTrace();
		}
		if(args == null) return;
		for(int i = 0; i < args.size(); ++i) {
			printObject((GeometricObject) args.get(i), i);
		}
	}

	public static void printObject(GeometricObject go, int i) {
		if(go == null) {
			System.out.println("printObject(): null");
			return;
		}
		System.out.print("Argument " + i + " is " + go.getClass().getName());
		System.out.println(", " + go.getLabel().toString());
		System.out.println("- Construction: "  + go.getConstruction());
		System.out.print("- Loc(s):");
		if(go instanceof Point) {
			System.out.print("\tX: " + ((Point) go).getX());
			System.out.println("\tY: " + ((Point) go).getY());
		} else {
			for(int j = 0; j < go.getArgs().size(); ++j) {
				if(go.getArgs().get(j) instanceof Point) {
					Point p = (Point) go.getArgs().get(j);
					System.out.print("\tX: " + p.getX());
					System.out.println("\tY: " + p.getY());
				} else {
					System.out.println("\t(" + j + ")");
				}
			}
		}
		System.out.println("- Visible: " + go.isVisible() + ", isInput: " + go.getIsInput());
	}
}

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists