//--------------------------------------------------------[JUnit]
import junit.framework.TestCase;
import junit.framework.Test;
import junit.framework.TestSuite;

//--------------------------------------------------------[JXPath]
import org.apache.commons.jxpath.*;
import org.apache.commons.jxpath.util.*;

/**
 * Tests the functionality of the JXPath library included. This is to
 * ensure future compatibility.
 */
public class SimpleArrayTest extends TestCase {

  private java.util.Map persons;
  private JXPathContextFactory ctxFactory;
  
  public SimpleArrayTest(java.lang.String testName) {
    super(testName);
  }
  
  public static void main(java.lang.String[] args) {
    junit.textui.TestRunner.run(suite());
  }
  
  public static Test suite() {
    TestSuite suite = new TestSuite(SimpleArrayTest.class);
    return suite;
  }
  
  protected void setUp() {
    ctxFactory = JXPathContextFactory.newInstance();
    persons = new java.util.HashMap();
    Person person = new Person();
    persons.put("testPerson", person);
  }
  
  /**
   * Standard test for JXPath expressions.
   */
  public void testJXPath() {
    try {
      JXPathContext ctx = ctxFactory.newContext(null, persons);
      ctx.setLenient(true);
      ctx.setFactory(new ObjectFactory());
      
      ctx.createPath("testPerson/intMatrix[2]/.[2]");
      ctx.setValue("testPerson/intMatrix[2]/.[2]", "5");
      assertEquals(
        ctx.getValue("testPerson/intMatrix[2]/.[2]", String.class), "5");
    }
    catch (Throwable t) {
      t.printStackTrace();
      super.fail(t.toString());
    }
  }
  
  private static void log(String statement) {
    System.out.println(statement);
  }
  
  public class Person {
    private int[][] intMatrix;
    public int[][] getIntMatrix() {return intMatrix;}
    public void setIntMatrix(int[][] intMatrix) {this.intMatrix = intMatrix;}
  }

  /**
   * Factory class for instantiating objects are they are traversed.
   */
  public class ObjectFactory extends AbstractFactory {
    
    public boolean createObject
      (JXPathContext context, Pointer pointer, Object parent, String name, 
       int index) {
       System.out.println("Create: " + name);
       if (name.equals("intMatrix")) {
         System.out.println("intMatrix creation.");
         int[][] intMatrix = new int[3][3];
         ((Person)parent).setIntMatrix(intMatrix);
         return true;
       }
       return false;
    }
  }
}


