text:
package com.pivotal.gemfirexd.jdbc;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import org.apache.derbyTesting.junit.JDBC;

import com.pivotal.gemfirexd.TestUtil;
import com.pivotal.gemfirexd.dataawareprocedure.MergeSortDUnit;
import com.pivotal.gemfirexd.dataawareprocedure.MergeSortDUnit.MergeSortProcessor;
import com.pivotal.gemfirexd.procedure.OutgoingResultSet;
import com.pivotal.gemfirexd.procedure.ProcedureExecutionContext;

import junit.framework.AssertionFailedError;
import junit.framework.TestSuite;
import junit.textui.TestRunner;

/**
 * This junit test is used to test procedure
 * @author yjing
 *
 */

public class Procedure2Test extends JdbcTestBase {

  private List<Statement> statements;

  public Procedure2Test(String name) {
    super(name);
  }

  public static void main(String[] args) {
    TestRunner.run(new TestSuite(Procedure2Test.class));
  }

  // TESTS

  public static void selectOnlyIn(int cid1, int cid2, int sid, int tid,
      ResultSet[] rs, ResultSet[] rs2, ResultSet[] rs3, ProcedureExecutionContext context)
      throws SQLException {
    getLogger().info("method executed");
  }

  public static void selectInAsWellASOut(int cid1, int cid2, int sid, int tid, int[] data,
      ResultSet[] rs, ResultSet[] rs2, ResultSet[] rs3, ProcedureExecutionContext context)
      throws SQLException {
    getLogger().info("method executed");
  }

  public void testProperExceptionInvalidProcClassName() throws SQLException {
    Connection conn = TestUtil.getConnection();
    Statement s = conn.createStatement();
    try {
      s.execute("CREATE PROCEDURE MergeSort () "
          + "LANGUAGE JAVA PARAMETER STYLE JAVA "
          + "READS SQL DATA DYNAMIC RESULT SETS 1 " + "EXTERNAL NAME '"
          + MergeSortDUnit.class.getName() + "garbage.mergeSort' ");

      s.execute("CREATE ALIAS MergeSortProcessor FOR '"
          + MergeSortProcessor.class.getName() + "garbage'");

      s.execute("CALL MergeSort() WITH RESULT PROCESSOR MergeSortProcessor");
      fail("should not proceed");
    } catch (SQLException e) {
      assertEquals("42X51", e.getSQLState());
    }
  }

  public void testProperExceptionInvalidProcessorClassName() throws SQLException {
    Connection conn = TestUtil.getConnection();
    Statement s = conn.createStatement();
    try {
      s.execute("CREATE PROCEDURE MergeSort () "
          + "LANGUAGE JAVA PARAMETER STYLE JAVA "
          + "READS SQL DATA DYNAMIC RESULT SETS 1 " + "EXTERNAL NAME '"
          + MergeSortDUnit.class.getName() + ".mergeSort' ");

      s.execute("CREATE ALIAS MergeSortProcessor FOR '"
          + MergeSortProcessor.class.getName() + "garbage'");

      s.execute("CALL MergeSort() WITH RESULT PROCESSOR MergeSortProcessor");
      fail("should not proceed");
    } catch (SQLException e) {
      assertEquals("42X51", e.getSQLState());
    }
  }

  public void testBug42875_OUT() throws SQLException {
    String showGfxdPortfolio = "create procedure trade.showGfxdPortfolio(IN DP1 Integer, " +
    "IN DP2 Integer, IN DP3 Integer, IN DP4 Integer, OUT DP5 Integer) " +
    "PARAMETER STYLE JAVA " +
    "LANGUAGE JAVA " +
    "READS SQL DATA " +
    "DYNAMIC RESULT SETS 3 " +
    "EXTERNAL NAME 'com.pivotal.gemfirexd.jdbc.Procedure2Test.selectInAsWellASOut'";

    Connection conn = TestUtil.getConnection();
    Statement s = conn.createStatement();

    s.execute("create table trade.portfolio " +
        "(cid int not null, tid int not null)");

    s.execute(showGfxdPortfolio);

    CallableStatement cs = conn.prepareCall(" call trade.showGfxdPortfolio(?, ?, ?, ?, ?) " +
                "ON Table trade.portfolio where cid > 258 and cid< 1113 and tid=2");
    cs.setInt(1, 1);
    cs.setInt(2, 2);
    cs.setInt(3, 3);
    cs.setInt(4, 4);
    cs.registerOutParameter(5, Types.INTEGER);

    cs.execute();
  }

  public void testBug42875_onlyIN() throws SQLException {
    String showGfxdPortfolio = "create procedure trade.showGfxdPortfolio(IN DP1 Integer, " +
    "IN DP2 Integer, IN DP3 Integer, IN DP4 Integer) " +
    "PARAMETER STYLE JAVA " +
    "LANGUAGE JAVA " +
    "READS SQL DATA " +
    "DYNAMIC RESULT SETS 3 " +
    "EXTERNAL NAME 'com.pivotal.gemfirexd.jdbc.Procedure2Test.selectOnlyIn'";

    Connection conn = TestUtil.getConnection();
    Statement s = conn.createStatement();

    s.execute("create table trade.portfolio " +
        "(cid int not null, tid int not null)");

    s.execute(showGfxdPortfolio);

    CallableStatement cs = conn.prepareCall(" call trade.showGfxdPortfolio(?, ?, ?, ?) " +
                "ON Table trade.portfolio where cid > 258 and cid< 1113 and tid=2");
    cs.setInt(1, 1);
    cs.setInt(2, 2);
    cs.setInt(3, 3);
    cs.setInt(4, 4);

    cs.execute();
  }

  static int tidGot = -1;
  static BigDecimal subtotalGot = new BigDecimal(-1);

  public static void updateGfxdPortfolioByCidRange(BigDecimal subTotal, int tid,
      ProcedureExecutionContext context) throws SQLException {
    tidGot = tid;
    subtotalGot = subTotal;
  }

  public void testBug42963_NPEInBCMethod() throws SQLException {
    String updateGfxdPortfolioByCidRange = "create procedure trade.updateGfxdPortfolioByCidRange(IN DP1 DECIMAL(30, 20), " +
    "IN DP2 Integer) " +
    "PARAMETER STYLE JAVA " +
    "LANGUAGE JAVA " +
    "Modifies SQL DATA " +
    "EXTERNAL NAME 'com.pivotal.gemfirexd.jdbc.Procedure2Test.updateGfxdPortfolioByCidRange'";

    Connection conn = TestUtil.getConnection();
    Statement s = conn.createStatement();

    s.execute("create table trade.portfolio " +
        "(cid int not null, tid int not null)");

    s.execute(updateGfxdPortfolioByCidRange);

    CallableStatement cs = conn.prepareCall("{call trade.updateGfxdPortfolioByCidRange(?, ?) " +
    		"ON Table trade.portfolio where cid > 474 and cid< 2055 and tid=17}");
    cs.setInt(1, 1);
    cs.setInt(2, 2);
    cs.execute();
    assertEquals(2, tidGot);
    //assertTrue(subtotalGot.equals(new BigDecimal(1)));
  }

  /**
   * Tests that PreparedStatement.executeQuery() fails
   * when no result sets are returned.
   * @exception SQLException if a database error occurs
   */
  public void testExecuteQueryWithNoDynamicResultSets_prepared()
  throws SQLException {
    setup();
    PreparedStatement ps = prepareStatement("CALL RETRIEVE_DYNAMIC_RESULTS(?)");
    ps.setInt(1, 0);
    try {
      ps.executeQuery();
      fail("executeQuery() didn't fail.");
    }
    catch (SQLException sqle) {
      assertNoResultSetFromExecuteQuery(sqle);
    }
  }

  /**
   * Tests that PreparedStatement.executeQuery()
   * succeeds when one result set is returned from a stored
   * procedure.
   * @exception SQLException if a database error occurs
   */
  public void testExecuteQueryWithOneDynamicResultSet_prepared()
  throws SQLException {
    setup();
    PreparedStatement ps = prepareStatement("CALL RETRIEVE_DYNAMIC_RESULTS(?)");
    ps.setInt(1, 1);
    ResultSet rs = ps.executeQuery();
    assertNotNull("executeQuery() returned null.", rs);
    assertSame(ps, rs.getStatement());
    JDBC.assertDrainResultsHasData(rs);

  }

  /**
   * Tests that PreparedStatement.executeQuery() fails
   * when multiple result sets are returned.
   * @exception SQLException if a database error occurs
   */
  public void testExecuteQueryWithMoreThanOneDynamicResultSet_prepared()
  throws SQLException {
    setup();
    PreparedStatement ps = prepareStatement("CALL RETRIEVE_DYNAMIC_RESULTS(?)");
    ps.setInt(1, 2);
    try {
      ps.executeQuery();
      fail("executeQuery() didn't fail.");
    }
    catch (SQLException sqle) {
      assertMultipleResultsFromExecuteQuery(sqle);
    }
  }

  /**
   * Tests that PreparedStatement.executeUpdate()
   * succeeds when no result sets are returned.
   *
   *
Currently, this test fails with JCC.
   *
   * @exception SQLException if a database error occurs
   */
  public void testExecuteUpdateWithNoDynamicResultSets_prepared()
  throws SQLException {
    setup();
    PreparedStatement ps = prepareStatement("CALL RETRIEVE_DYNAMIC_RESULTS(?)");
    ps.setInt(1, 0);
    //   assertUpdateCount(ps, 0);
    JDBC.assertNoMoreResults(ps);
  }

  /**
   * Tests that PreparedStatement.executeUpdate() fails
   * when a result set is returned from a stored procedure.
   *
   *
Currently, this test fails with
   * JCC. However, the corresponding tests for
   * Statement and CallableStatement
   * succeed. Strange...
   *
   * @exception SQLException if a database error occurs
   */
  public void testExecuteUpdateWithOneDynamicResultSet_prepared()
  throws SQLException {
    setup();
    PreparedStatement ps = prepareStatement("CALL RETRIEVE_DYNAMIC_RESULTS(?)");
    ps.setInt(1, 1);
    try {
      ps.executeUpdate();
      fail("executeUpdate() didn't fail.");
    }
    catch (SQLException sqle) {
      assertResultsFromExecuteUpdate(sqle);
    }
  }

  /**
   * Tests that CallableStatement.executeQuery() fails
   * when no result sets are returned.
   * @exception SQLException if a database error occurs
   */
  public void testExecuteQueryWithNoDynamicResultSets_callable()
  throws SQLException {
    setup();
    CallableStatement cs = prepareCall("CALL RETRIEVE_DYNAMIC_RESULTS(?)");
    cs.setInt(1, 0);
    try {
      cs.executeQuery();
      fail("executeQuery() didn't fail.");
    }
    catch (SQLException sqle) {
      assertNoResultSetFromExecuteQuery(sqle);
    }
  }

  /**
   * Tests that CallableStatement.executeQuery()
   * succeeds when one result set is returned from a stored
   * procedure.
   * @exception SQLException if a database error occurs
   */
  public void testExecuteQueryWithOneDynamicResultSet_callable()
  throws SQLException {
    setup();
    CallableStatement cs = prepareCall("CALL RETRIEVE_DYNAMIC_RESULTS(?)");
    cs.setInt(1, 1);
    ResultSet rs = cs.executeQuery();
    assertNotNull("executeQuery() returned null.", rs);
    assertSame(cs, rs.getStatement());
    JDBC.assertDrainResultsHasData(rs);
  }

  /**
   * Tests that CallableStatement.executeQuery() fails
   * when multiple result sets are returned.
   * @exception SQLException if a database error occurs
   */
  public void testExecuteQueryWithMoreThanOneDynamicResultSet_callable()
      throws SQLException {
    setup();
    CallableStatement cs = prepareCall("CALL RETRIEVE_DYNAMIC_RESULTS(?)");
    cs.setInt(1, 2);
    try {
      cs.executeQuery();
      fail("executeQuery() didn't fail.");
    }
    catch (SQLException sqle) {
      assertMultipleResultsFromExecuteQuery(sqle);
    }
  }

//******************************************************
  public void testCreateProcedureResultProcessorAlias() throws SQLException {
    setup();
    Statement s = getConnection().createStatement();
    s.execute("CREATE ALIAS MergeSortProcessor FOR '"
        + com.pivotal.gemfirexd.dataawareprocedure.MergeSortDUnit.class
            .getName() + ".MergeSortProcessor'");
   /*
   s.execute("Create alias aaa FOR ddd");
   s.execute("Create alias aaa FOR BBB");
   */
  }

  public void testAlias() throws Exception {
    Statement s = getConnection().createStatement();
    s.execute("CREATE PROCEDURE MergeSort () "
        + "LANGUAGE JAVA PARAMETER STYLE JAVA "
        + "READS SQL DATA DYNAMIC RESULT SETS 1 " + "EXTERNAL NAME '"
        + MergeSortDUnit.class.getName() + ".justanothermergeSort' ");

    // create custom processor
    s.execute("CREATE ALIAS MergeSortProcessor FOR '"
        + MergeSortProcessor.class.getName()+"'");
    /*
    "CALL GFXD.CreateResultProcessor('MergeSortProcessor', "
    + MergeSortDUnit.class.getName()
    + ".MergeSortProcessor)");
    */

    CallableStatement cs = prepareCall("CALL MergeSort() "
        + "WITH RESULT PROCESSOR MergeSortProcessor");
    cs.execute();
    cs.getResultSet();
  }
  // !!!:ezoerner:20090825
  // fails with:
  // Caused by: com.gemstone.gemfire.cache.execute.FunctionException: No target node found for KEY = 2
  //Neeraj::20100317
  // This test is invalid because optimizedForWrite has been made as true which
  // means procedure will be routed to a node irrespective of whether data is there
  // or not in the system.
  public void _testDataAwareProcedureWithOutgoingResultSetsWithoutNodesToExecute()
  throws SQLException {

    setup();
    CallableStatement cs = prepareCall("CALL RETRIEVE_OUTGOING_RESULTS(?) ON TABLE "
        + "EMP.PARTITIONEMPTYTESTTABLE WHERE ID in (?, ?, ?)");
    int number=2;
    cs.setInt(1, number);
    cs.setInt(2, 2);
    cs.setInt(3, 3);
    cs.setInt(4, 4);

    cs.execute();

    do {
      ResultSet rs = cs.getResultSet();
      ResultSetMetaData metaData = rs.getMetaData();
      int rowCount = metaData.getColumnCount();
      if(rowCount!=0 || rs.next()) {
         fail("The result set is supposed to be empty!");
      }
    } while (cs.getMoreResults());
  }

  /***
   * Note test for no out parameters
   */

  /***
   * Note test for one of parameters is null
   *
   */

  /***
   * normal test for out parameter
   */

  /**
   * Tests that CallableStatement.executeUpdate() fails
   * when a result set is returned from a stored procedure.
   * @exception SQLException if a database error occurs
   */
  public void testExecuteUpdateWithOneDynamicResultSet_callable()
  throws SQLException {
    setup();
    CallableStatement cs = prepareCall("CALL RETRIEVE_DYNAMIC_RESULTS(?)");
    cs.setInt(1, 1);
    try {
      cs.executeUpdate();
      fail("executeUpdate() didn't fail.");
    }
    catch (SQLException sqle) {
      assertResultsFromExecuteUpdate(sqle);
    }
  }

  /**
   * Tests that the effects of executing a stored procedure with
   * executeQuery() are correctly rolled back when
   * Connection.rollback() is called.
   * @exception SQLException if a database error occurs
   */
  // !!!:ezoerner:20090825
  // this test is not yet working
  public void _testRollbackStoredProcWithExecuteQuery() throws SQLException {
    setup();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("CALL PROC_WITH_SIDE_EFFECTS(1)");
    rs.close();
    // rollback();

    // Expect Side effects from stored procedure to be rolled back.
    JDBC.assertEmpty(stmt.executeQuery("SELECT * FROM SIMPLE_TABLE"));

  }

  /**
   * Tests that the effects of executing a stored procedure with
   * executeUpdate() are correctly rolled back when
   * Connection.rollback() is called.
   * @exception SQLException if a database error occurs
   */
  // !!!:ezoerner:20090825
  // this test is not yet working
  public void _testRollbackStoredProcWithExecuteUpdate() throws SQLException {
    setup();
    Statement stmt = createStatement();
    stmt.executeUpdate("CALL PROC_WITH_SIDE_EFFECTS(0)");
    //  rollback();

    // Expect Side effects from stored procedure to be rolled back.
    JDBC.assertEmpty(stmt.executeQuery("SELECT * FROM SIMPLE_TABLE"));

  }

  /**
   * Tests that the effects of executing a stored procedure with
   * executeQuery() are correctly rolled back when the
   * query fails because the number of returned result sets is zero.
   *
   *
 This test case fails with JCC.
   *
   * @exception SQLException if a database error occurs
   */
  // !!!:ezoerner:20090825
  // this test is not yet working
  public void _testRollbackStoredProcWhenExecuteQueryReturnsNothing()
      throws SQLException {
    Connection conn = getConnection();
    conn.setAutoCommit(true);
    Statement stmt = createStatement();
    try {
      stmt.executeQuery("CALL PROC_WITH_SIDE_EFFECTS(0)");
      fail("executeQuery() didn't fail.");
    }
    catch (SQLException sqle) {
      assertNoResultSetFromExecuteQuery(sqle);
    }

    // Expect Side effects from stored procedure to be rolled back.
    JDBC.assertEmpty(stmt.executeQuery("SELECT * FROM SIMPLE_TABLE"));
  }

  /**
   * Tests that the effects of executing a stored procedure with
   * executeQuery() are correctly rolled back when the
   * query fails because the number of returned result sets is more
   * than one.
   *
   *
 This test case fails with JCC.
   *
   * @exception SQLException if a database error occurs
   */
  // !!!:ezoerner:20090825
  // this test is not yet working
  public void _testRollbackStoredProcWhenExecuteQueryReturnsTooMuch()
      throws SQLException {
    Connection conn = getConnection();
    conn.setAutoCommit(true);
    Statement stmt = createStatement();
    try {
      stmt.executeQuery("CALL PROC_WITH_SIDE_EFFECTS(2)");
      fail("executeQuery() didn't fail.");
    }
    catch (SQLException sqle) {
      assertMultipleResultsFromExecuteQuery(sqle);
    }
    // Expect Side effects from stored procedure to be rolled back.
    JDBC.assertEmpty(stmt.executeQuery("SELECT * FROM SIMPLE_TABLE"));

  }

  /**
   * Tests that the effects of executing a stored procedure with
   * executeUpdate() are correctly rolled back when the
   * query fails because the stored procedure returned a result set.
   *
   *
 This test case fails with JCC.
   *
   * @exception SQLException if a database error occurs
   */
  // !!!:ezoerner:20090825
  // this test is not yet working
  public void _testRollbackStoredProcWhenExecuteUpdateReturnsResults()
      throws SQLException {
    Connection conn = getConnection();
    conn.setAutoCommit(true);
    Statement stmt = createStatement();
    try {
      stmt.executeUpdate("CALL PROC_WITH_SIDE_EFFECTS(1)");
      fail("executeUpdate() didn't fail.");
    }
    catch (SQLException sqle) {
      assertResultsFromExecuteUpdate(sqle);
    }
    // Expect Side effects from stored procedure to be rolled back.
    JDBC.assertEmpty(stmt.executeQuery("SELECT * FROM SIMPLE_TABLE"));

  }

  /**
   * Tests that the effects of executing a stored procedure with
   * executeQuery() are correctly rolled back when the
   * query fails because the number of returned result sets is zero.
   *
   *
 This test case fails with JCC.
   *
   * @exception SQLException if a database error occurs
   */
  // !!!:ezoerner:20090825
  // this test is not yet working
  public void _testRollbackStoredProcWhenExecuteQueryReturnsNothing_prepared()
      throws SQLException {
    Connection conn = getConnection();
    conn.setAutoCommit(true);
    PreparedStatement ps = prepareStatement("CALL PROC_WITH_SIDE_EFFECTS(?)");
    ps.setInt(1, 0);
    try {
      ps.executeQuery();
      fail("executeQuery() didn't fail.");
    }
    catch (SQLException sqle) {
      assertNoResultSetFromExecuteQuery(sqle);
    }
    Statement stmt = createStatement();
    // Expect Side effects from stored procedure to be rolled back.
    JDBC.assertEmpty(stmt.executeQuery("SELECT * FROM SIMPLE_TABLE"));

  }

  /**
   * Tests that the effects of executing a stored procedure with
   * executeQuery() are correctly rolled back when the
   * query fails because the number of returned result sets is more
   * than one.
   *
   *
 This test case fails with JCC.
   *
   * @exception SQLException if a database error occurs
   */
  // !!!:ezoerner:20090825
  // this test is not yet working
  public void _testRollbackStoredProcWhenExecuteQueryReturnsTooMuch_prepared()
      throws SQLException {
    Connection conn = getConnection();
    conn.setAutoCommit(true);
    PreparedStatement ps = prepareStatement("CALL PROC_WITH_SIDE_EFFECTS(?)");
    ps.setInt(1, 2);
    try {
      ps.executeQuery();
      fail("executeQuery() didn't fail.");
    }
    catch (SQLException sqle) {
      assertMultipleResultsFromExecuteQuery(sqle);
    }
    Statement stmt = createStatement();
    // Expect Side effects from stored procedure to be rolled back.
    JDBC.assertEmpty(stmt.executeQuery("SELECT * FROM SIMPLE_TABLE"));
  }

  /**
   * Tests that the effects of executing a stored procedure with
   * executeUpdate() are correctly rolled back when the
   * query fails because the stored procedure returned a result set.
   *
   *
 This test case fails with JCC.
   *
   * @exception SQLException if a database error occurs
   */
  // !!!:ezoerner:20090825
  // this test is not yet working
  public void _testRollbackStoredProcWhenExecuteUpdateReturnsResults_prepared()
      throws SQLException {
    Connection conn = getConnection();
    conn.setAutoCommit(true);
    PreparedStatement ps = prepareStatement("CALL PROC_WITH_SIDE_EFFECTS(?)");
    ps.setInt(1, 1);
    try {
      ps.executeUpdate();
      fail("executeUpdate() didn't fail.");
    }
    catch (SQLException sqle) {
      assertResultsFromExecuteUpdate(sqle);
    }
    Statement stmt = createStatement();
    // Expect Side effects from stored procedure to be rolled back.
    JDBC.assertEmpty(stmt.executeQuery("SELECT * FROM SIMPLE_TABLE"));

  }

  /**
   * Tests that closed result sets are not returned when calling
   * executeQuery().
   * @exception SQLException if a database error occurs
   */
  public void testClosedDynamicResultSetsFromExecuteQuery() throws SQLException {
    setup();
    Statement stmt = createStatement();
    try {
      stmt.executeQuery("CALL RETRIEVE_CLOSED_RESULT()");
      fail("executeQuery() didn't fail.");
    }
    catch (SQLException sqle) {
      assertNoResultSetFromExecuteQuery(sqle);
    }
  }

  private static int delInvokeCnt = 0;

  public static void procreadssql(ResultSet[] outResults,
      ProcedureExecutionContext context) throws SQLException {
    delInvokeCnt++;
  }

  public void testDeleteTriggerWhichHasProc() throws SQLException {
    Connection conn = TestUtil.getConnection();
    Statement s = conn.createStatement();
    s.execute("create table t2(col1 int not null, col2 int not null primary key)");
    s.execute("CREATE PROCEDURE proc_reads_sql () "
        + "LANGUAGE JAVA PARAMETER STYLE JAVA "
        + "READS SQL DATA DYNAMIC RESULT SETS 1 " + "EXTERNAL NAME '"
        + Procedure2Test.class.getName() + ".procreadssql' ");

    try {
      s.execute("create trigger before_row_trig_reads_sql "
          + "no cascade BEFORE delete on t2 for each ROW call proc_reads_sql()");
      s.execute("insert into t2 values(1, 11), (2, 22)");
      // --- delete 2 rows. check that trigger is fired - procedure should be
      // called twice
      s.execute("delete from t2");
      // checkAndResetSelectRowsCount(2);
      // --- check delete is successful
      ResultSet rs = s.executeQuery("select * from t2");
      while (rs.next()) {
        fail("table should have been empty");
      }
    } finally {
      s.execute("drop trigger before_row_trig_reads_sql");
    }
    s.execute("insert into t2 values(1, 11), (2, 22)");
    ResultSet rs = s.executeQuery("select * from t2");
    int cnt = 0;
    while (rs.next()) {
      cnt++;
    }
    assertEquals(2, cnt);
    assertEquals(2, delInvokeCnt);
  }

  /**
   * Tests that closed result sets are ignored when calling
   * executeUpdate().
   * @exception SQLException if a database error occurs
   */
  public void testClosedDynamicResultSetsFromExecuteUpdate()
  throws SQLException {
    setup();
    Statement stmt = createStatement();
    stmt.executeUpdate("CALL RETRIEVE_CLOSED_RESULT()");
    JDBC.assertNoMoreResults(stmt);
  }

  // UTILITY METHODS

  /**
   * Raises an exception if the exception is not caused by
   * executeQuery() returning no result set.
   *
   * @param sqle a SQLException value
   */
  private void assertNoResultSetFromExecuteQuery(SQLException sqle) {
    //  if (usingDB2Client()) {
    //     assertNull("Unexpected SQL state.", sqle.getSQLState());
    // } else {
    assertSQLState("Unexpected SQL state.", "X0Y78", sqle);
    // }
  }

  /**
   * Raises an exception if the exception is not caused by
   * executeQuery() returning multiple result sets.
   *
   * @param sqle a SQLException value
   */
  private void assertMultipleResultsFromExecuteQuery(SQLException sqle) {
    // if (usingDB2Client()) {
    //     assertNull("Unexpected SQL state.", sqle.getSQLState());
    // } else {
    assertSQLState("Unexpected SQL state.", "X0Y78", sqle);
    // }
  }

  /**
   * Raises an exception if the exception is not caused by
   * executeUpdate() returning result sets.
   *
   * @param sqle a SQLException value
   */
  private void assertResultsFromExecuteUpdate(SQLException sqle) {
    // if (usingDB2Client()) {
    //     assertNull("Unexpected SQL state.", sqle.getSQLState());
    // } else {
    assertSQLState("Unexpected SQL state.", "X0Y79", sqle);
    // }

  }

  // SETUP

  /**
   * Creates the test suite and wraps it in a TestSetup
   * instance which sets up and tears down the test environment.
   * @return test suite
   */
  private static void setup() throws SQLException {

    Connection conn = getConnection();
    //conn.setAutoCommit(false);
    Statement s = conn.createStatement();

    s.execute("create table EMP.PARTITIONTESTTABLE (ID int NOT NULL,"
        + " SECONDID int not null, THIRDID varchar(10) not null, PRIMARY KEY (SECONDID, THIRDID))");
     //   + " PARTITION BY COLUMN (ID)");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE VALUES (2, 2, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE VALUES (3, 3, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE VALUES (4, 4, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE VALUES (5, 5, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE VALUES (2, 2, '2') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE VALUES (2, 2, '4') ");

    s.execute("SELECT * FROM EMP.PARTITIONTESTTABLE " +
    		"WHERE (SECONDID=10 AND THIRDID='20') OR (SECONDID=10 AND THIRDID='20')");

    s.execute("create table EMP.PARTITIONTESTTABLE1 (ID int NOT NULL,"
        + " SECONDID int not null, THIRDID varchar(10) not null, " +
        		"PRIMARY KEY (SECONDID, THIRDID)) PARTITION BY COLUMN (ID)");
     //   + " PARTITION BY COLUMN (ID)");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE1 VALUES (2, 2, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE1 VALUES (3, 3, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE1 VALUES (4, 4, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE1 VALUES (5, 5, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE1 VALUES (2, 2, '2') ");
    s.execute("INSERT INTO EMP.PARTITIONTESTTABLE1 VALUES (2, 2, '4') ");

    s.execute("create table EMP.PARTITIONRANGETESTTABLE (ID int NOT NULL,"
        + " SECONDID int not null, THIRDID varchar(10) not null, PRIMARY KEY (ID)) PARTITION BY RANGE ( ID )"
            + " ( VALUES BETWEEN 1 and 10, VALUES BETWEEN 10 and 20, "
            + "VALUES BETWEEN 20 and 30, VALUES BETWEEN 30 and 40 )");
     //   + " PARTITION BY COLUMN (ID)");
    s.execute("INSERT INTO EMP.PARTITIONRANGETESTTABLE VALUES (1, 2, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONRANGETESTTABLE VALUES (10, 3, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONRANGETESTTABLE VALUES (15, 4, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONRANGETESTTABLE VALUES (21, 5, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONRANGETESTTABLE VALUES (30, 2, '2') ");
    s.execute("INSERT INTO EMP.PARTITIONRANGETESTTABLE VALUES (35, 2, '4') ");

    s.execute("create table EMP.PARTITIONLISTTESTTABLE (ID int NOT NULL,"
        + " SECONDID int not null, THIRDID varchar(10) not null, PRIMARY KEY (ID)) PARTITION BY LIST ( ID )"
        + " ( VALUES (0, 5) , VALUES (10, 15), "
        + "VALUES (20, 23), VALUES(25, 30), VALUES(31, 100))");
     //   + " PARTITION BY COLUMN (ID)");
    s.execute("INSERT INTO EMP.PARTITIONLISTTESTTABLE VALUES (0, 2, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONLISTTESTTABLE VALUES (5, 3, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONLISTTESTTABLE VALUES (15, 4, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONLISTTESTTABLE VALUES (30, 5, '3') ");
    s.execute("INSERT INTO EMP.PARTITIONLISTTESTTABLE VALUES (31, 2, '2') ");
    s.execute("INSERT INTO EMP.PARTITIONLISTTESTTABLE VALUES (25, 2, '4') ");

    s.execute("create table EMP.PARTITIONEMPTYTESTTABLE (ID int NOT NULL,"
        + " SECONDID int not null, THIRDID varchar(10) not null, PRIMARY KEY (ID)) PARTITION BY COLUMN ( ID )");
    /**
     * Creates the tables and the stored procedures used in the test cases.
     *
     * @exception SQLException
     *                    if a database error occurs
     */

    for (int i = 0; i < PROCEDURES.length; i++) {
      s.execute(PROCEDURES[i]);
    }
    for (int i = 0; i < TABLES.length; i++) {
      s.execute(TABLES[i][1]);
    }
    conn.close();

  }

  /**
   * Procedures that should be created before the tests are run and dropped when
   * the tests have finished. First element in each row is the name of the
   * procedure, second element is SQL which creates it.
   */
  private static final String[] PROCEDURES = {

      "CREATE PROCEDURE RETRIEVE_DYNAMIC_RESULTS(number INT) "
          + "LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME '"
          + Procedure2Test.class.getName() + ".retrieveDynamicResults' "
          + "DYNAMIC RESULT SETS 4",

      "CREATE PROCEDURE RETRIEVE_OUTGOING_RESULTS(number INT) "
          + "LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME '"
          + Procedure2Test.class.getName() + ".retrieveDynamicResultsWithOutgoingResultSet'"
          + "DYNAMIC RESULT SETS 4",

      "CREATE PROCEDURE PROCEDURE_INOUT_PARAMETERS(number INT, INOUT name VARCHAR(25), OUT total INT) "
          + "LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME '"
          + Procedure2Test.class.getName() + ".procedureWithInAndOutParameters'"
          + "DYNAMIC RESULT SETS 4",

      "CREATE PROCEDURE PROCEDURE_WITHOUT_RESULTSET(number INT, INOUT name VARCHAR(20) ) "
          + "LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME '"
          + Procedure2Test.class.getName() + ".procedureWithoutDynamicResultSets'",

      "CREATE PROCEDURE PROCEDURE_WITHOUT_RESULTSET_OUTPARAMETER(number INT, name VARCHAR(20) ) "
          + "LANGUAGE JAVA PARAMETER STYLE JAVA EXTERNAL NAME '"
          + Procedure2Test.class.getName() + ".procedureWithoutDynamicResultSetsAndOutParameters'",

      "CREATE PROCEDURE RETRIEVE_CLOSED_RESULT() LANGUAGE JAVA "
          + "PARAMETER STYLE JAVA EXTERNAL NAME '"
          + Procedure2Test.class.getName() + ".retrieveClosedResult' "
          + "DYNAMIC RESULT SETS 1",

      "CREATE PROCEDURE RETRIEVE_EXTERNAL_RESULT("
          + "DBNAME VARCHAR(128), DBUSER VARCHAR(128), DBPWD VARCHAR(128)) LANGUAGE JAVA "
          + "PARAMETER STYLE JAVA EXTERNAL NAME '"
          + Procedure2Test.class.getName() + ".retrieveExternalResult' "
          + "DYNAMIC RESULT SETS 1",

      "CREATE PROCEDURE PROC_WITH_SIDE_EFFECTS(ret INT) LANGUAGE JAVA "
          + "PARAMETER STYLE JAVA EXTERNAL NAME '"
          + Procedure2Test.class.getName() + ".procWithSideEffects' "
          + "DYNAMIC RESULT SETS 2",

      "CREATE PROCEDURE NESTED_RESULT_SETS(proctext VARCHAR(128)) LANGUAGE JAVA "
          + "PARAMETER STYLE JAVA EXTERNAL NAME '"
          + Procedure2Test.class.getName() + ".nestedDynamicResultSets' "
          + "DYNAMIC RESULT SETS 6"

  };

  /**
   * Tables that should be created before the tests are run and
   * dropped when the tests have finished. The tables will be
   * cleared before each test case is run. First element in each row
   * is the name of the table, second element is the SQL text which
   * creates it.
   */
  private static final String[][] TABLES = {
  // SIMPLE_TABLE is used by PROC_WITH_SIDE_EFFECTS
  { "SIMPLE_TABLE", "CREATE TABLE SIMPLE_TABLE (id INT)" }, };

  // PROCEDURES

  /**
   * Stored procedure which returns 0, 1, 2, 3 or 4 ResultSets.
   *
   * @param number the number of ResultSets to return
   * @param rs1 first ResultSet
   * @param rs2 second ResultSet
   * @param rs3 third ResultSet
   * @param rs4 fourth ResultSet
   * @exception SQLException if a database error occurs
   */
  public static void retrieveDynamicResults(int number, ResultSet[] rs1,
      ResultSet[] rs2, ResultSet[] rs3, ResultSet[] rs4) throws SQLException {
      Connection c = DriverManager.getConnection("jdbc:default:connection");

    if (number > 0) {
      rs1[0] = c.createStatement().executeQuery("VALUES(1)");
    }
    if (number > 1) {
      rs2[0] = c.createStatement().executeQuery("VALUES(1)");
    }
    if (number > 2) {
      rs3[0] = c.createStatement().executeQuery("VALUES(1)");
    }
    if (number > 3) {
      rs4[0] = c.createStatement().executeQuery("VALUES(1)");
    }
  }

  public static void procedureWithInAndOutParameters(int number,
      String[] name,
      int[]    total,
      ResultSet[] rs1,
      ResultSet[] rs2, ResultSet[] rs3, ResultSet[] rs4) throws SQLException {
      Connection c = DriverManager.getConnection("jdbc:default:connection");

    name[0]=name[0]+"Modified";
    total[0]=number;

    if (number > 0) {
      rs1[0] = c.createStatement().executeQuery("VALUES(1)");
    }
    if (number > 1) {
      rs2[0] = c.createStatement().executeQuery("VALUES(1)");
    }
    if (number > 2) {
      rs3[0] = c.createStatement().executeQuery("VALUES(1)");
    }
    if (number > 3) {
      rs4[0] = c.createStatement().executeQuery("VALUES(1)");
    }
  }

  public static void procedureWithoutDynamicResultSets(int number,
      String[] name) throws SQLException {
    name[0]=name[0]+number;

  }

  public static void procedureWithoutDynamicResultSetsAndOutParameters(int number,
      String name) throws SQLException {

  }
  /**
   * Stored procedure which returns 0, 1, 2, 3 or 4 ResultSets.
   *
   * @param number the number of ResultSets to return
   * @param rs1 first ResultSet
   * @param rs2 second ResultSet
   * @param rs3 third ResultSet
   * @param rs4 fourth ResultSet
   * @exception SQLException if a database error occurs
   */
  public static void retrieveDynamicResultsWithOutgoingResultSet(int number, ResultSet[] rs1,
      ResultSet[] rs2, ResultSet[] rs3, ResultSet[] rs4, ProcedureExecutionContext pec)
      throws SQLException {
      Connection c = DriverManager.getConnection("jdbc:default:connection");

    if (number > 0) {
      rs1[0] = c.createStatement().executeQuery("VALUES(1)");
    }
    if (number > 1) {
      OutgoingResultSet ors=pec.getOutgoingResultSet(2);
      for(int i=0; i<10; ++i) {
        List<Object> row=new ArrayList<Object>();
        row.add(new Integer(i));
        row.add("String"+ i);
        ors.addRow(row);
      }
      ors.endResults();
    }
    if (number > 2) {
      rs3[0] = c.createStatement().executeQuery("VALUES(1)");
    }
    if (number > 3) {
      rs4[0] = c.createStatement().executeQuery("VALUES(1)");
    }
  }

  /**
   * Stored procedure which produces a closed result set.
   *
   * @param closed holder for the closed result set
   * @exception SQLException if a database error occurs
   */
  public static void retrieveClosedResult(ResultSet[] closed)
      throws SQLException {
    Connection c = DriverManager.getConnection("jdbc:default:connection");
    closed[0] = c.createStatement().executeQuery("VALUES(1)");
    closed[0].close();
  }

  /**
   * Stored procedure which produces a result set in another
   * connection.
   *
   * @param external result set from another connection
   * @exception SQLException if a database error occurs
   */
  public static void retrieveExternalResult(String dbName, String user,
      String password, ResultSet[] external) throws SQLException {
    // Use a server-side connection to the same database.
    String url = "jdbc:derby:" + dbName;

    Connection conn = DriverManager.getConnection(url, user, password);

    external[0] = conn.createStatement().executeQuery("VALUES(1)");
  }

  /**
   * Stored procedure which inserts a row into SIMPLE_TABLE and
   * optionally returns result sets.
   *
   * @param returnResults if one, return one result set; if greater
   * than one, return two result sets; otherwise, return no result
   * set
   * @param rs1 first result set to return
   * @param rs2 second result set to return
   * @exception SQLException if a database error occurs
   */
  public static void procWithSideEffects(int returnResults, ResultSet[] rs1,
      ResultSet[] rs2) throws SQLException {
    Connection c = DriverManager.getConnection("jdbc:default:connection");
    Statement stmt = c.createStatement();
    stmt.executeUpdate("INSERT INTO SIMPLE_TABLE VALUES (42)");
    if (returnResults > 0) {
      rs1[0] = c.createStatement().executeQuery("VALUES(1)");
    }
    if (returnResults > 1) {
      rs2[0] = c.createStatement().executeQuery("VALUES(1)");
    }
  }

  /**
   * Method for a Java procedure that calls another procedure
   * and just passes on the dynamic results from that call.
   */
  public static void nestedDynamicResultSets(String procedureText,
      ResultSet[] rs1, ResultSet[] rs2, ResultSet[] rs3, ResultSet[] rs4,
      ResultSet[] rs5, ResultSet[] rs6) throws SQLException {
    Connection c = DriverManager.getConnection("jdbc:default:connection");

    CallableStatement cs = c.prepareCall("CALL " + procedureText);

    cs.execute();

    // Mix up the order of the result sets in the returned
    // parameters, ensures order is defined by creation
    // and not parameter order.
    rs6[0] = cs.getResultSet();
    if (!cs.getMoreResults(Statement.KEEP_CURRENT_RESULT))
      return;
    rs3[0] = cs.getResultSet();
    if (!cs.getMoreResults(Statement.KEEP_CURRENT_RESULT))
      return;
    rs4[0] = cs.getResultSet();
    if (!cs.getMoreResults(Statement.KEEP_CURRENT_RESULT))
      return;
    rs2[0] = cs.getResultSet();
    if (!cs.getMoreResults(Statement.KEEP_CURRENT_RESULT))
      return;
    rs1[0] = cs.getResultSet();
    if (!cs.getMoreResults(Statement.KEEP_CURRENT_RESULT))
      return;
    rs5[0] = cs.getResultSet();

  }

  /**
   * Test various combinations of getMoreResults
   *
   * @throws SQLException
   */
  // !!!:ezoerner:20090825
  // fails with Caused by: java.lang.ClassCastException: com.pivotal.gemfirexd.internal.engine.locks.GfxdLockSet
  public void _testGetMoreResults() throws SQLException {

    Statement s = createStatement();

    s.executeUpdate("create table MRS.FIVERS(i integer)");
    PreparedStatement ps = prepareStatement("insert into MRS.FIVERS values (?)");
    for (int i = 1; i <= 20; i++) {
      ps.setInt(1, i);
      ps.executeUpdate();
    }

    // create a procedure that returns 5 result sets.

    s.executeUpdate("create procedure MRS.FIVEJP() " +
    		"parameter style JAVA READS SQL DATA dynamic result sets 5 " +
    		"language java " +
    		"external name 'org.apache.derbyTesting.functionTests.util.Procedure2Test.fivejp'");

    CallableStatement cs = prepareCall("CALL MRS.FIVEJP()");
    ResultSet[] allRS = new ResultSet[5];

    defaultGetMoreResults(cs, allRS);
    java.util.Arrays.fill(allRS, null);
    closeCurrentGetMoreResults(cs, allRS);
    java.util.Arrays.fill(allRS, null);
    keepCurrentGetMoreResults(cs, allRS);
    java.util.Arrays.fill(allRS, null);
    mixedGetMoreResults(cs, allRS);
    java.util.Arrays.fill(allRS, null);
    checkExecuteClosesResults(cs, allRS);
    java.util.Arrays.fill(allRS, null);
    checkCSCloseClosesResults(cs, allRS);
    java.util.Arrays.fill(allRS, null);

    // a procedure that calls another procedure that returns
    // dynamic result sets, see if the result sets are handled
    // correctly through the nesting.
    CallableStatement nestedCs = prepareCall("CALL NESTED_RESULT_SETS('MRS.FIVEJP()')");
    defaultGetMoreResults(nestedCs, allRS);

  }

  /**
   * Check that CallableStatement.execute() closes results
   * @param cs
   * @param allRS
   * @throws SQLException
   */
  private void checkExecuteClosesResults(CallableStatement cs, ResultSet[] allRS)
      throws SQLException {
    //Fetching result sets with
    // getMoreResults(Statement.KEEP_CURRENT_RESULT) and checking that cs.execute() closes them");
    cs.execute();
    int pass = 0;
    do {

      allRS[pass++] = cs.getResultSet();
      assertSame(cs, allRS[pass - 1].getStatement());
      // expect everything to stay open.

    } while (cs.getMoreResults(Statement.KEEP_CURRENT_RESULT));
    //fetched all results
    // All should still be open.
    for (int i = 0; i < 5; i++)
      JDBC.assertDrainResults(allRS[i]);

    cs.execute();
    // all should be closed.
    for (int i = 0; i < 5; i++)
      JDBC.assertClosed(allRS[i]);
  }

  /**
   * Check that CallableStatement.close() closes results
   * @param cs
   * @param allRS
   * @throws SQLException
   */
  private void checkCSCloseClosesResults(CallableStatement cs, ResultSet[] allRS)
      throws SQLException {
    cs.execute();
    int pass = 0;
    do {

      allRS[pass++] = cs.getResultSet();
      assertSame(cs, allRS[pass - 1].getStatement());
      // expect everything to stay open.

    } while (cs.getMoreResults(Statement.KEEP_CURRENT_RESULT));
    //fetched all results
    // All should still be open.
    for (int i = 0; i < 5; i++)
      JDBC.assertDrainResults(allRS[i]);

    cs.close();
    // all should be closed.
    for (int i = 0; i < 5; i++)
      JDBC.assertClosed(allRS[i]);
  }

  private void mixedGetMoreResults(CallableStatement cs, ResultSet[] allRS)
      throws SQLException {
    //Fetching result sets with getMoreResults(<mixture>)"
    cs.execute();

    //first two with KEEP_CURRENT_RESULT"
    allRS[0] = cs.getResultSet();
    assertSame(cs, allRS[0].getStatement());
    boolean moreRS = cs.getMoreResults(Statement.KEEP_CURRENT_RESULT);
    if (!moreRS)
      fail("FAIL - no second result set");
    allRS[1] = cs.getResultSet();
    assertSame(cs, allRS[1].getStatement());
    // two open
    allRS[0].next();
    assertEquals(2, allRS[0].getInt(1));
    allRS[1].next();
    assertEquals(3, allRS[1].getInt(1));

    //third with CLOSE_CURRENT_RESULT"
    moreRS = cs.getMoreResults(Statement.CLOSE_CURRENT_RESULT);
    if (!moreRS)
      fail("FAIL - no third result set");
    // first and third open
    allRS[2] = cs.getResultSet();
    assertSame(cs, allRS[2].getStatement());
    assertEquals(2, allRS[0].getInt(1));
    JDBC.assertClosed(allRS[1]);
    allRS[2].next();
    assertEquals(4, allRS[2].getInt(1));

    //fourth with KEEP_CURRENT_RESULT"
    moreRS = cs.getMoreResults(Statement.KEEP_CURRENT_RESULT);
    if (!moreRS)
      fail("FAIL - no fourth result set");
    allRS[3] = cs.getResultSet();
    assertSame(cs, allRS[3].getStatement());
    allRS[3].next();
    // first, third and fourth open, second closed
    assertEquals(2, allRS[0].getInt(1));
    JDBC.assertClosed(allRS[1]);
    assertEquals(4, allRS[2].getInt(1));
    assertEquals(5, allRS[3].getInt(1));

    //fifth with CLOSE_ALL_RESULTS"
    moreRS = cs.getMoreResults(Statement.CLOSE_ALL_RESULTS);
    if (!moreRS)
      fail("FAIL - no fifth result set");
    allRS[4] = cs.getResultSet();
    assertSame(cs, allRS[4].getStatement());
    allRS[4].next();
    // only fifth open
    JDBC.assertClosed(allRS[0]);
    JDBC.assertClosed(allRS[1]);
    JDBC.assertClosed(allRS[2]);
    JDBC.assertClosed(allRS[3]);
    assertEquals(6, allRS[4].getInt(1));

    //no more results with with KEEP_CURRENT_RESULT"
    moreRS = cs.getMoreResults(Statement.KEEP_CURRENT_RESULT);
    if (moreRS)
      fail("FAIL - too many result sets");
    // only fifth open
    JDBC.assertClosed(allRS[0]);
    JDBC.assertClosed(allRS[1]);
    JDBC.assertClosed(allRS[2]);
    JDBC.assertClosed(allRS[3]);
    assertEquals(6, allRS[4].getInt(1));

    allRS[4].close();
  }

  /**
   * Check getMoreResults(Statement.KEEP_CURRENT_RESULT)
   *
   * @param cs
   * @param allRS
   * @throws SQLException
   */
  private void keepCurrentGetMoreResults(CallableStatement cs, ResultSet[] allRS)
      throws SQLException {
    cs.execute();

    for (int i = 0; i < 5; i++) {
      allRS[i] = cs.getResultSet();
      assertSame(cs, allRS[i].getStatement());
      allRS[i].next();
      assertEquals(2 + i, allRS[i].getInt(1));

      if (i < 4)
        assertTrue(cs.getMoreResults(Statement.KEEP_CURRENT_RESULT));
      else
        assertFalse(cs.getMoreResults(Statement.KEEP_CURRENT_RESULT));
    }

    // resultSets should still be open
    for (int i = 0; i < 5; i++)
      JDBC.assertDrainResults(allRS[i]);
  }

  private void closeCurrentGetMoreResults(CallableStatement cs,
      ResultSet[] allRS) throws SQLException {
    cs.execute();

    for (int i = 0; i < 5; i++) {
      allRS[i] = cs.getResultSet();
      assertSame(cs, allRS[i].getStatement());
      allRS[i].next();
      assertEquals(2 + i, allRS[i].getInt(1));

      if (i < 4)
        assertTrue(cs.getMoreResults(Statement.CLOSE_CURRENT_RESULT));
      else
        assertFalse(cs.getMoreResults(Statement.CLOSE_CURRENT_RESULT));
    }

    // verify resultSets are closed
    for (int i = 0; i < 5; i++)
      JDBC.assertClosed(allRS[i]);
  }

  /**
   * Test default getMoreResults() closes result set.
   * @param cs
   * @param allRS
   * @throws SQLException
   */
  private void defaultGetMoreResults(CallableStatement cs, ResultSet[] allRS)
      throws SQLException {
    // execute the procedure that returns 5 result sets and then use the various
    // options of getMoreResults().

    cs.execute();

    for (int i = 0; i < 5; i++) {
      allRS[i] = cs.getResultSet();
      assertSame(cs, allRS[i].getStatement());
      allRS[i].next();
      assertEquals(2 + i, allRS[i].getInt(1));

      if (i < 4)
        assertTrue(cs.getMoreResults());
      else
        assertFalse(cs.getMoreResults());
    }

    // verify resultSets are closed
    for (int i = 0; i < 5; i++)
      JDBC.assertClosed(allRS[i]);
  }

  public Statement createStatement() throws SQLException {
    Statement s = getConnection().createStatement();
    addStatement(s);
    return s;
  }

  /**
   * Add a statement into the list we will close
   * at tearDown.
   */
  private void addStatement(Statement s) {
    if (statements == null)
      statements = new ArrayList<Statement>();
    statements.add(s);
  }

  /**
   * Utility method to create a PreparedStatement using the connection
   * returned by getConnection.
   * The returned statement object will be closed automatically
   * at tearDown() but may be closed earlier by the test if required.
   * @return Statement object from
   * getConnection.prepareStatement(sql)
   * @throws SQLException
   */
  public PreparedStatement prepareStatement(String sql) throws SQLException {
    PreparedStatement ps = getConnection().prepareStatement(sql);
    addStatement(ps);
    return ps;
  }

  /**
   * Utility method to create a CallableStatement using the connection
   * returned by getConnection.
   * The returned statement object will be closed automatically
   * at tearDown() but may be closed earlier by the test if required.
   * @return Statement object from
   * getConnection().prepareCall(sql)
   * @throws SQLException
   */
  public CallableStatement prepareCall(String sql) throws SQLException {
    CallableStatement cs = getConnection().prepareCall(sql);
    addStatement(cs);
    return cs;

  }

  /**
   * Assert that SQLState is as expected.  If the SQLState for
   * the top-level exception doesn't match, look for nested
   * exceptions and, if there are any, see if they have the
   * desired SQLState.
   *
   * @param message message to print on failure.
   * @param expected the expected SQLState.
   * @param exception the exception to check the SQLState of.
   */
  public static void assertSQLState(String message, String expected,
      SQLException exception) {
    // Make sure exception is not null. We want to separate between a
    // null-exception object, and a null-SQLState.
    assertNotNull("Exception cannot be null when asserting on SQLState",
        exception);

    try {
      String state = exception.getSQLState();

      if (state != null)
        assertTrue("The exception's SQL state must be five characters long",
            state.length() == 5);

      if (expected != null)
        assertTrue("The expected SQL state must be five characters long",
            expected.length() == 5);

      assertEquals(message, expected, state);
    }
    catch (AssertionFailedError e) {

      // Save the SQLException
      try {
        Method m = Throwable.class.getMethod("initCause",
            new Class[] { Throwable.class });
        m.invoke(e, new Object[] { exception });
      }
      catch (Throwable t) {
        // Some VMs don't support initCause(). It is OK if they fail.
      }

      //     if (usingDB2Client())
      //     {
      /* For JCC the error message is a series of tokens representing
       * different things like SQLSTATE, SQLCODE, nested SQL error
       * message, and nested SQL state.  Based on observation it
       * appears that the last token in the message is the SQLSTATE
       * of the nested exception, and it's preceded by a colon.
       * So using that (hopefully consistent?) rule, try to find
       * the target SQLSTATE.
       */
      //        String msg = exception.getMessage();
      //        if (!msg.substring(msg.lastIndexOf(":")+1)
      //            .trim().equals(expected))
      //        {
      //            throw e;
      //        }
      //    }
      //    else
      //    {
      // Check nested exceptions to see if any of them is
      // the one we're looking for.
      exception = exception.getNextException();
      if (exception != null)
        assertSQLState(message, expected, exception);
      else
        throw e;
      // }
    }
  }

  public static void assertErrorCode(String message, int expected,
      SQLException exception) {
    while (exception != null) {
      try {
        assertEquals(message, expected, exception.getErrorCode());
      }
      catch (AssertionFailedError e) {
        // check and see if our error code is in a chained exception
        exception = exception.getNextException();
      }
    }
  }

}


text:
package com.vaadin.tests.components.table;

import com.vaadin.tests.components.TestBase;
import com.vaadin.ui.Label;
import com.vaadin.ui.Table;

public class TooManySetColumnCollapsedCalls extends TestBase {

    private int counter = 0;
    private Label label;
    private Table table;

    @Override
    protected void setup() {
        label = new Label(String.valueOf(counter));
        label.setId("label");
        table = createTable();
        table.setId("table");
        addComponent(table);
        addComponent(label);
        getLayout().setSpacing(true);
        table.setColumnCollapsed("p2", true);
    }

    @Override
    protected String getDescription() {
        return "Table.setColumnCollapsed is called too many times in Table.changeVariables."
                + " Collapsing column 'P3' should only increase the counter by one.";
    }

    @Override
    protected Integer getTicketNumber() {
        return 5681;
    }

    private Table createTable() {
        Table table = new Table() {
            @Override
            public void setColumnCollapsed(Object propertyId, boolean collapsed)
                    throws IllegalStateException {
                ++counter;
                label.setValue(String.valueOf(counter));
                super.setColumnCollapsed(propertyId, collapsed);
            }
        };
        table.setWidth("400px");
        table.setHeight("100px");
        table.setPageLength(100);
        table.setColumnCollapsingAllowed(true);
        table.setImmediate(true);
        table.addContainerProperty("p1", String.class, null);
        table.addContainerProperty("p2", String.class, null);
        table.addContainerProperty("p3", String.class, null);
        table.addContainerProperty("p4", String.class, null);

        for (int i = 0; i < 10; i++) {
            table.addItem(new Object[] { "a" + i, "b" + i, "c" + i, "X" + i },
                    "" + i);
        }
        return table;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ignite.yardstick.cache.jdbc;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.ignite.IgniteException;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.yardstick.IgniteAbstractBenchmark;
import org.apache.ignite.yardstick.IgniteBenchmarkArguments;
import org.yardstickframework.BenchmarkConfiguration;

import static org.yardstickframework.BenchmarkUtils.jcommander;

/** Base class for benchmarks that measure raw performance of JDBC databases */
public abstract class JdbcAbstractBenchmark extends IgniteAbstractBenchmark {
    /** Arguments. */
    protected final IgniteBenchmarkArguments args = new IgniteBenchmarkArguments();

    /** All {@link Connection}s associated with threads. */
    private final List<Connection> threadConnections = new ArrayList<>();

    /** List of queries. */
    private final List<String> dbqueries = new ArrayList<>();

    /** Each connection is also a transaction, so we better pin them to threads. */
    ThreadLocal<Connection> conn = new ThreadLocal<Connection>() {
        @Override protected Connection initialValue() {
            Connection conn;
            try {
                conn = connection();
                if (args.createTempDatabase() || args.dbn() != null) {
                    assert dbName != null;
                    conn.setCatalog(dbName);
                }
            }
            catch (SQLException e) {
                throw new IgniteException(e);
            }
            synchronized (threadConnections) {
                threadConnections.add(conn);
            }
            return conn;
        }
    };

    /** Dynamically generated DB name */
    private String dbName;

    /** {@inheritDoc} */
    @Override public void setUp(BenchmarkConfiguration cfg) throws Exception {
        super.setUp(cfg);
        jcommander(cfg.commandLineArguments(), args, "<ignite-driver>");

        Class.forName(args.jdbcDriver());
        if (args.createTempDatabase())
            createTestDatabase();
        else
            dbName = (args.dbn() == null) ? null : args.dbn();

        try (Connection conn = connection()) {
            if (args.createTempDatabase())
                conn.setCatalog(dbName);

            populateTestDatabase(conn);
        }

        if (args.loadTestQueriesFile() != null)
            setQueries();
    }

    /** {@inheritDoc} */
    @Override public void tearDown() throws Exception {
        synchronized (threadConnections) {
            for (Connection conn : threadConnections)
                U.closeQuiet(conn);

            threadConnections.clear();
        }

        if (args.createTempDatabase())
            dropTestDatabase();

        super.tearDown();
    }

    /** Create new, randomly named database to put dummy benchmark data in - no need in this for databases like H2 */
    private void createTestDatabase() throws SQLException {
        try (Connection conn = connection()) {
            String uuid = UUID.randomUUID().toString().replace("-", "");
            dbName = "benchmark" + getClass().getSimpleName() + uuid.substring(0, 16);
            try (Statement stmt = conn.createStatement()) {
                stmt.executeUpdate("create database " + dbName);
            }
        }
    }

    /** Drop previously created randomly named database - no need in this for databases like H2 */
    private void dropTestDatabase() throws SQLException {
        try (Connection conn = connection()) {
            try (Statement stmt = conn.createStatement()) {
                if (!conn.getMetaData().getDatabaseProductName().equals("Ignite Cache"))
                    stmt.executeUpdate("drop database " + dbName);
            }
        }
    }

    /** Create benchmark DB schema from supplied SQL file path */
    private void populateTestDatabase(Connection conn) throws IOException, SQLException {
        assert conn != null;
        List<String> queries = new ArrayList<>();
        if (args.schemaDefinition() != null) {
            try (FileReader fr = new FileReader(args.schemaDefinition())) {
                try (BufferedReader br = new BufferedReader(fr)) {
                    String line;
                    while ((line = br.readLine()) != null) {
                        if (line.trim().isEmpty())
                            continue;

                        queries.add(line.trim());
                    }
                }
            }
        }

        for (String query : queries) {
            try (PreparedStatement stmt = conn.prepareStatement(query)) {
                stmt.executeUpdate();
            }
        }
    }

    /** Set list of queries defined in file */
    private void setQueries() throws IOException, SQLException {
        if (args.loadTestQueriesFile() != null) {
            try (FileReader fr = new FileReader(args.loadTestQueriesFile())) {
                try (BufferedReader br = new BufferedReader(fr)) {
                    String line;

                    while ((line = br.readLine()) != null) {
                        if (line.trim().isEmpty())
                            continue;

                        dbqueries.add(line.trim());
                    }
                }
            }
        }
    }

    /** Create new {@link Connection} from {@link #args}. Intended for use by {@link #setUp} and {@link #tearDown}  */
    public Connection connection() throws SQLException {
        Connection conn = DriverManager.getConnection(args.jdbcUrl());
        conn.setAutoCommit(true);
        return conn;
    }

    /**
     * @return List of queries.
     */
    public List<String> getDbqueries(){
        return dbqueries;
    }

    /**
     * Delete all data from the table specified
     * @param tblName target table
     * @throws SQLException if failed
     */
    void clearTable(String tblName) throws SQLException {
        try (Connection conn = connection()) {
            try (PreparedStatement stmt = conn.prepareStatement("drop table " + tblName)) {
                if (!conn.getMetaData().getDatabaseProductName().equals("Ignite Cache"))
                    stmt.executeUpdate();
            }
        }
    }
}


text:
[![Build Status](https://travis-ci.org/sensu-plugins/sensu-plugins-lxc.svg?branch=master)](https://travis-ci.org/sensu-plugins/sensu-plugins-lxc)
[![Gem Version](https://badge.fury.io/rb/sensu-plugins-lxc.svg)](http://badge.fury.io/rb/sensu-plugins-lxc)
[![Code Climate](https://codeclimate.com/github/sensu-plugins/sensu-plugins-lxc/badges/gpa.svg)](https://codeclimate.com/github/sensu-plugins/sensu-plugins-lxc)
[![Test Coverage](https://codeclimate.com/github/sensu-plugins/sensu-plugins-lxc/badges/coverage.svg)](https://codeclimate.com/github/sensu-plugins/sensu-plugins-lxc)
[![Dependency Status](https://gemnasium.com/sensu-plugins/sensu-plugins-lxc.svg)](https://gemnasium.com/sensu-plugins/sensu-plugins-lxc)

## Functionality

## Files
 * bin/check-lxc-memstat.rb
 * bin/check-lxc-status.rb

## Usage

## Installation

[Installation and Setup](http://sensu-plugins.io/docs/installation_instructions.html)

## Notes


text:
import React, { Component } from 'react';
import { Grid, Button, Container, Image, Divider } from 'semantic-ui-react'

const LevelSelection = (props) => {
  return (
    <div>
      <Container fluid>
        <Button onClick={props.onBackToMainMenu} icon='reply' />
      </Container>
      <Divider hidden />
      <Grid columns={3}>
        <Grid.Row>
          <Grid.Column>
            <Button onClick={props.onStart.bind(null, 1)}>Level 1</Button>
          </Grid.Column>
          <Grid.Column>
            <Button>Level 2</Button>
          </Grid.Column>
          <Grid.Column>
            <Button>Level 3</Button>
          </Grid.Column>
        </Grid.Row>
        <Grid.Row>
          <Grid.Column>
            <Button>Level 4</Button>
          </Grid.Column>
          <Grid.Column>
            <Button>Level 5</Button>
          </Grid.Column>
          <Grid.Column>
            <Button>Level 6</Button>
          </Grid.Column>
        </Grid.Row>
      </Grid>
    </div>
  )
}
export default LevelSelection;


text:
/**
 *
 */
module.exports = require('./lib/base-config');


text:
import PIXI from 'pixi.js';
import tsort from 'tsort';

import {Entity, SystemManager} from 'koholint/engine/components';
import PhysicalSystem from 'koholint/engine/components/physical';
import TransformSystem from 'koholint/engine/components/transform';
import VisibleSystem from 'koholint/engine/components/visible';
import {Tileset} from 'koholint/engine/graphics';

export default class GameEngine {
    constructor() {
        this.running = false;
        this.systemManager = new SystemManager();

        this.systemManager.register(new TransformSystem());
        this.systemManager.register(new PhysicalSystem());
        this.systemManager.register(new VisibleSystem(400, 300));
    }

    start() {
        PIXI.loader.add('characters', 'img/characters.png').load((loader, resources) => {
            let tileset = new Tileset(resources.characters.texture, 16, 16);

            let person = new Entity();
            this.systemManager.systems['transform'].addToEntity(person, {x: 50, y: 50});
            this.systemManager.systems['physical'].addToEntity(person, {rotationalVelocity: 0.01});
            this.systemManager.systems['visible'].addToEntity(person, tileset.tile(1));
            this.systemManager.addEntity(person);

            this.running = true;
            requestAnimationFrame(::this.tick);
        });
    }

    stop() {
        this.running = false;
    }

    tick() {
        if (this.running) {
            requestAnimationFrame(::this.tick);
        }

        this.systemManager.update();
        this.systemManager.draw();
    }
}


text:
.. tags: extensions

Extension "Attachments"
=======================

This extensions allow to upload files to a page and include in the text as an embedded image or inline link.

Go to edit this page, click othe button ``Attachments`` and try upload something and insert in the page.

For example, these are me and my niece :)

.. image:: /attachments/_attachment/974471_167677233415256_1026236323_n.jpg

.. tip::

   The code is at https://github.com/mgaitan/waliki/blob/master/extensions/uploads.py
   and the template (with the fancy javascript) here https://github.com/mgaitan/waliki/blob/master/templates/upload.html

On old-fashion browsers without FormData_ support (i.e. Internet Explorer < 10) the ajaxified upload form (including the uploading progress bar) degrades to a popup window.

.. FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData


text:
FROM node:latest

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . /usr/src/app

EXPOSE 8080
RUN npm install
CMD ["npm", "start"]


text:
package matchers_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestMatchers(t *testing.T) {
	RegisterFailHandler(Fail)

	RunSpecs(t, "Matchers Suite")
}


text:
using System;

using Microsoft.SPOT;
using Microsoft.SPOT.Presentation.Media;

namespace Skewworks.NETMF.Controls
{
   /// <summary>
   /// Displays a simple button
   /// </summary>
   [Serializable]
   public class Button : AutoSizeControl
   {
      #region Variables

      private string _text;
      private Font _font;
      private PressState _state;
      private Color _textColor;
      private Color _pressedTextColor;
      private Color _backgroundGradientTopColor;
      private Color _backgroundGradientBottomColor;
      private Color _pressdBackgroundGradientTopColor;
      private Color _pressdBackgroundGradientBottomColor;
      private Color _borderColor;
      private Color _pressedBorderColor;
      private Bitmap _image;
      private ScaleMode _imageScaleMode;
      private Color _textShadowColor;
      private Color _pressedTextShadowColor;
      private ButtonRenderStyles _renderStyle = ButtonRenderStyles.Default;
      private HorizontalAlignment _horizontalTextAlignment = HorizontalAlignment.Center;
      private VerticalAlignment _verticalTextAlignment = VerticalAlignment.Center;

      #endregion

      #region Constructors

      /// <summary>
      /// Creates a new button
      /// </summary>
      /// <param name="name">Name of the button</param>
      /// <param name="text">Content text of the button</param>
      /// <param name="font">Font to render the content text</param>
      /// <param name="x">X position relative to it's parent</param>
      /// <param name="y">Y position relative to it's parent</param>
      /// <param name="showFocusRect">true if the focus rectangle should be visible; false if not</param>
      /// <remarks>
      /// The <see cref="Control.Width"/> and <see cref="Control.Height"/> are calculated automatically to fit the content text.
      /// </remarks>
      public Button(string name, string text, Font font, int x, int y, bool showFocusRect = true) :
         base(name, x, y)
      {
         DefaultColors();

         _text = text;
         _font = font;
         if (!showFocusRect)
         {
            _renderStyle &= ~ButtonRenderStyles.ShowFocusRectangle;
         }
         _state = PressState.Normal;
         SetPadding(new Thickness(11, 6, 11, 7));

         if (!MeasureControl())
         {
            Invalidate();
         }
         /*// Size button
         size sz = FontManager.ComputeExtentEx(_font, _text);
         // ReSharper disable DoNotCallOverridableMethodsInConstructor
         Width = sz.Width + 22;
         Height = sz.Height + 13;
         // ReSharper restore DoNotCallOverridableMethodsInConstructor*/
      }

      /// <summary>
      /// Creates a new button
      /// </summary>
      /// <param name="name">Name of the button</param>
      /// <param name="text">Content text of the button</param>
      /// <param name="font">Font to render the content text</param>
      /// <param name="x">X position relative to it's parent</param>
      /// <param name="y">Y position relative to it's parent</param>
      /// <param name="width">Width of the button in pixel</param>
      /// <param name="height">Height of the button in pixel</param>
      /// <param name="showFocusRect">true if the focus rectangle should be visible; false if not</param>
      public Button(string name, string text, Font font, int x, int y, int width, int height, bool showFocusRect = true) :
         base(name, x, y, width, height)
      {
         DefaultColors();

         _text = text;
         _font = font;

         if (!showFocusRect)
         {
            _renderStyle &= ~ButtonRenderStyles.ShowFocusRectangle;
         }
         _state = PressState.Normal;

         SetPadding(new Thickness(11, 6, 11, 7));
      }

      /// <summary>
      /// Creates a new button
      /// </summary>
      /// <param name="name">Name of the button</param>
      /// <param name="text">Content text of the button</param>
      /// <param name="font">Font to render the content text</param>
      /// <param name="x">X position relative to it's parent</param>
      /// <param name="y">Y position relative to it's parent</param>
      /// <param name="normalTextColor">Normal text color (unpressed)</param>
      /// <param name="pressedTextColor">Text color for pressed state</param>
      /// <param name="borderColorColor">Normal border color (unpressed)</param>
      /// <param name="pressedBorderColorColor">Border color for pressed state</param>
      /// <param name="showFocusRect">true if the focus rectangle should be visible; false if not</param>
      /// <remarks>
      /// The <see cref="Control.Width"/> and <see cref="Control.Height"/> are calculated automatically to fit the content text.
      /// </remarks>
      public Button(string name, string text, Font font, int x, int y, Color normalTextColor, Color pressedTextColor, Color borderColorColor, Color pressedBorderColorColor, bool showFocusRect = true) :
         base(name, x, y)
      {
         DefaultColors();

         _text = text;
         _font = font;
         _textColor = normalTextColor;
         _pressedTextColor = pressedTextColor;
         if (!showFocusRect)
         {
            _renderStyle &= ~ButtonRenderStyles.ShowFocusRectangle;
         }
         _state = PressState.Normal;
         _borderColor = borderColorColor;
         _pressedBorderColor = pressedBorderColorColor;

         SetPadding(new Thickness(11, 6, 11, 7));

         /*// Size button
         size sz = FontManager.ComputeExtentEx(_font, _text);
         // ReSharper disable DoNotCallOverridableMethodsInConstructor
         Width = sz.Width + 22;
         Height = sz.Height + 13;
         // ReSharper restore DoNotCallOverridableMethodsInConstructor*/
         if (!MeasureControl())
         {
            Invalidate();
         }
      }

      /// <summary>
      /// Creates a new button
      /// </summary>
      /// <param name="name">Name of the button</param>
      /// <param name="text">Content text of the button</param>
      /// <param name="font">Font to render the content text</param>
      /// <param name="x">X position relative to it's parent</param>
      /// <param name="y">Y position relative to it's parent</param>
      /// <param name="width">Width of the button in pixel</param>
      /// <param name="height">Height of the button in pixel</param>
      /// <param name="normalTextColor">Normal text color (unpressed)</param>
      /// <param name="pressedTextColor">Text color for pressed state</param>
      /// <param name="borderColorColor">Normal border color (unpressed)</param>
      /// <param name="pressedBorderColorColor">Border color for pressed state</param>
      /// <param name="showFocusRect">true if the focus rectangle should be visible; false if not</param>
      public Button(string name, string text, Font font, int x, int y, int width, int height, Color normalTextColor, Color pressedTextColor, Color borderColorColor, Color pressedBorderColorColor, bool showFocusRect = true) :
         base(name, x, y, width, height)
      {
         DefaultColors();

         _text = text;
         _font = font;
         _textColor = normalTextColor;
         _pressedTextColor = pressedTextColor;
         _borderColor = borderColorColor;
         _pressedBorderColor = pressedBorderColorColor;

         if (!showFocusRect)
         {
            _renderStyle &= ~ButtonRenderStyles.ShowFocusRectangle;
         }
         _state = PressState.Normal;

         SetPadding(new Thickness(11, 6, 11, 7));
      }

      #endregion

      #region Properties

      /// <summary>
      /// Gets/Sets the background image to display
      /// </summary>
      /// <remarks>
      /// The <see cref="Text"/> is rendered above the image
      /// </remarks>
      public Bitmap BackgroundImage
      {
         get { return _image; }
         set
         {
            if (_image == value)
            {
               return;
            }
            _image = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets the Scale Mode to use when rendering background image
      /// </summary>
      public ScaleMode BackgroundImageImageScaleModeMode
      {
         get { return _imageScaleMode; }
         set
         {
            if (_imageScaleMode == value)
            {
               return;
            }
            _imageScaleMode = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets color to use for border
      /// </summary>
      public Color BorderColor
      {
         get { return _borderColor; }
         set
         {
            if (_borderColor == value)
            {
               return;
            }
            _borderColor = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets color to use for border when pressed
      /// </summary>
      public Color BorderColorPressed
      {
         get { return _pressedBorderColor; }
         set
         {
            if (_pressedBorderColor == value)
            {
               return;
            }
            _pressedBorderColor = value;
            if (_state == PressState.Pressed)
            {
               Invalidate();
            }
         }
      }

      /// <summary>
      /// Gets/Sets the Font for rendering text
      /// </summary>
      public Font Font
      {
         get { return _font; }
         set
         {
            if (_font == value)
            {
               return;
            }
            _font = value;
            if (!MeasureControl())
            {
               Invalidate();
            }
         }
      }

      /// <summary>
      /// Gets/Sets bottom color to use in background gradient when button is not pressed
      /// </summary>
      public Color NormalColorBottom
      {
         get { return _backgroundGradientBottomColor; }
         set
         {
            if (_backgroundGradientBottomColor == value)
            {
               return;
            }
            _backgroundGradientBottomColor = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets top color to use in background gradient when button is not pressed
      /// </summary>
      public Color NormalColorTop
      {
         get { return _backgroundGradientTopColor; }
         set
         {
            if (_backgroundGradientTopColor == value)
            {
               return;
            }
            _backgroundGradientTopColor = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets the color to use when rendering text when button is not pressed
      /// </summary>
      public Color NormalTextColor
      {
         get { return _textColor; }
         set
         {
            if (_textColor == value)
            {
               return;
            }
            _textColor = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets the color to use when rendering text shadow when button is not pressed
      /// </summary>
      /// <remarks>
      /// Remove the <see cref="ButtonRenderStyles.TextShadow"/> flag from <see cref="RenderStyle"/> to turn off text shadows.
      /// </remarks>
      public Color NormalTextShadowColor
      {
         get { return _textShadowColor; }
         set
         {
            if (_textShadowColor == value)
            {
               return;
            }
            _textShadowColor = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets pressed state bottom color to use in background gradient when button is pressed
      /// </summary>
      public Color PressedColorBottom
      {
         get { return _pressdBackgroundGradientBottomColor; }
         set
         {
            if (_pressdBackgroundGradientBottomColor == value)
            {
               return;
            }
            _pressdBackgroundGradientBottomColor = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets pressed state top color to use in background gradient when button is pressed
      /// </summary>
      public Color PressedColorTop
      {
         get { return _pressdBackgroundGradientTopColor; }
         set
         {
            if (_pressdBackgroundGradientTopColor == value)
            {
               return;
            }
            _pressdBackgroundGradientTopColor = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets pressed state color to use when rendering text when button is pressed
      /// </summary>
      public Color PressedTextColor
      {
         get { return _pressedTextColor; }
         set
         {
            if (_pressedTextColor == value)
            {
               return;
            }
            _pressedTextColor = value;
            if (_state == PressState.Pressed)
            {
               Invalidate();
            }
         }
      }

      /// <summary>
      /// Gets/Sets the color to use when rendering text shadow when button is pressed
      /// </summary>
      /// <remarks>
      /// Remove the <see cref="ButtonRenderStyles.TextShadow"/> flag from <see cref="RenderStyle"/> to turn off text shadows.
      /// </remarks>
      public Color PressedTextShadowColor
      {
         get { return _pressedTextShadowColor; }
         set
         {
            if (_pressedTextShadowColor == value)
            {
               return;
            }
            _pressedTextShadowColor = value;
            if (_state == PressState.Pressed)
            {
               Invalidate();
            }
         }
      }

      /// <summary>
      /// Gets/Sets the render style of the button
      /// </summary>
      public ButtonRenderStyles RenderStyle
      {
         get { return _renderStyle; }
         set
         {
            if (value == _renderStyle)
            {
               return;
            }
            _renderStyle = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets whether or not to draw focus rectangle
      /// </summary>
      /// <remarks>
      /// If false a focus rectangle will not be drawn even if control has focus
      /// </remarks>
      [Obsolete("Use RenderStlye, RenderStyles.ShowFocusRectangle")]
      public bool ShowFocusRectangle
      {
         get { return (RenderStyle & ButtonRenderStyles.ShowFocusRectangle) != 0; }
         set
         {
            if (ShowFocusRectangle == value)
            {
               return;
            }
            if (value)
            {
               RenderStyle |= ButtonRenderStyles.ShowFocusRectangle;
            }
            else
            {
               RenderStyle &= ~ButtonRenderStyles.ShowFocusRectangle;
            }
         }
      }

      /// <summary>
      /// Gets/Sets the content text
      /// </summary>
      public string Text
      {
         get { return _text; }
         set
         {
            if (value == null)
            {
               value = string.Empty;
            }
            if (_text == value)
            {
               return;
            }
            _text = value;
            if (!MeasureControl())
            {
               Invalidate();
            }
         }
      }

      /// <summary>
      /// Gets/Sets horizontal text alignment
      /// </summary>
      public HorizontalAlignment HorizontalTextAlignment
      {
         get { return _horizontalTextAlignment; }
         set
         {
            if (_horizontalTextAlignment == value)
            {
               return;
            }
            _horizontalTextAlignment = value;
            Invalidate();
         }
      }

      /// <summary>
      /// Gets/Sets the vertical text alignment
      /// </summary>
      public VerticalAlignment VerticalTextAlignment
      {
         get { return _verticalTextAlignment; }
         set
         {
            if (_verticalTextAlignment == value)
            {
               return;
            }
            _verticalTextAlignment = value;
            Invalidate();
         }
      }

      #endregion

      #region Button Invokes

      /// <summary>
      /// Override this message to handle button pressed events internally.
      /// </summary>
      /// <param name="buttonId">Integer ID corresponding to the affected button</param>
      /// <param name="handled">true if the event is handled. Set to true if handled.</param>
      /// <remarks>
      /// On button id <see cref="ButtonIDs.Select"/> or <see cref="ButtonIDs.Click"/> the button is switched to <see cref="PressState.Pressed"/> state
      /// </remarks>
      protected override void ButtonPressedMessage(int buttonId, ref bool handled)
      {
         if (buttonId == (int)ButtonIDs.Select || buttonId == (int)ButtonIDs.Click)
         {
            _state = PressState.Pressed;
            Invalidate();
         }
         base.ButtonPressedMessage(buttonId, ref handled);
      }

      /// <summary>
      /// Override this message to handle button released events internally.
      /// </summary>
      /// <param name="buttonId">Integer ID corresponding to the affected button</param>
      /// <param name="handled">true if the event is handled. Set to true if handled.</param>
      /// <remarks>
      /// On button id <see cref="ButtonIDs.Select"/> or <see cref="ButtonIDs.Click"/> the button is switched back to <see cref="PressState.Normal"/> state
      /// and the <see cref="Control.Tap"/> event is fired.
      /// </remarks>
      protected override void ButtonReleasedMessage(int buttonId, ref bool handled)
      {
         if (_state == PressState.Pressed && (buttonId == (int)ButtonIDs.Select || buttonId == (int)ButtonIDs.Click))
         {
            _state = PressState.Normal;
            Invalidate();
            OnTap(this, new point(X, Y));
         }
         base.ButtonReleasedMessage(buttonId, ref handled);
      }

      #endregion

      #region Touch Invokes

      // ReSharper disable once RedundantAssignment
      /// <summary>
      /// Override this message to handle touch events internally.
      /// </summary>
      /// <param name="sender">Object sending the event</param>
      /// <param name="point">Point on screen touch event is occurring</param>
      /// <param name="handled">true if the event is handled. Set to true if handled.</param>
      /// <remarks>
      /// Switches the button into <see cref="PressState.Pressed"/> state
      /// </remarks>
      protected override void TouchDownMessage(object sender, point point, ref bool handled)
      {
         _state = PressState.Pressed;
         Invalidate();
         // do NOT set handled to true !
         base.TouchDownMessage(sender, point, ref handled);
      }

      /// <summary>
      /// Override this message to handle touch events internally.
      /// </summary>
      /// <param name="sender">Object sending the event</param>
      /// <param name="point">Point on screen touch event is occurring</param>
      /// <param name="handled">true if the event is handled. Set to true if handled.</param>
      /// <remarks>
      /// Switches the button to <see cref="PressState.Normal"/> state if currently pressed
      /// </remarks>
      protected override void TouchUpMessage(object sender, point point, ref bool handled)
      {
         if (Touching)
         {
            _state = PressState.Normal;
            Invalidate();
            // do NOT set handled to true !
         }
         base.TouchUpMessage(sender, point, ref handled);
      }

      #endregion

      #region Keyboard Methods

      /// <summary>
      /// Override this message to handle key events internally.
      /// </summary>
      /// <param name="key">Integer value of the key affected</param>
      /// <param name="pressed">True if the key is currently being pressed; false if released</param>
      /// <param name="handled">true if the event is handled. Set to true if handled.</param>
      /// <remarks>
      /// If the return Key (key == 10) is pressed or released the button is switched to
      /// <see cref="PressState.Pressed"/> and <see cref="PressState.Normal"/> state.
      /// On release the <see cref="Control.Tap"/> event is fired.
      /// </remarks>
      protected override void KeyboardKeyMessage(char key, bool pressed, ref bool handled)
      {
         if (key == 10)
         {
            handled = true;
            if (pressed)
            {
               if (_state != PressState.Pressed)
               {
                  _state = PressState.Pressed;
                  Invalidate();
               }
            }
            else
            {
               if (_state == PressState.Pressed)
               {
                  _state = PressState.Normal;
                  Invalidate();
                  OnTap(this, new point(Left, Top));
               }
            }
         }
         base.KeyboardKeyMessage(key, pressed, ref handled);
      }

      #endregion

      #region GUI

      private void CalcTextMetrics(AutoSizeModes autoSizeMode, out int textWidth, out int texhtHeight, out uint textFlags)
      {
         int availableWidth;
         int availHeight;
         textFlags = Bitmap.DT_TrimmingNone;

         if ((autoSizeMode & AutoSizeModes.Width) != 0)
         {
            availableWidth = Int32.MaxValue;
         }
         else
         {
            availableWidth = Width - Padding.Horizontal;
            textFlags |= Bitmap.DT_WordWrap;
         }
         if ((autoSizeMode & AutoSizeModes.Height) != 0)
         {
            availHeight = Int32.MaxValue;
         }
         else
         {
            availHeight = Height - Padding.Vertical;
         }
         switch (HorizontalTextAlignment)
         {
            case HorizontalAlignment.Center:
               textFlags |= Bitmap.DT_AlignmentCenter;
               break;

            case HorizontalAlignment.Right:
               textFlags |= Bitmap.DT_AlignmentRight;
               break;
         }
         _font.ComputeTextInRect(_text, out textWidth, out texhtHeight, 0, 0, availableWidth, availHeight, textFlags);
      }

      /// <summary>
      /// Is called when ever the size of the control needs to be calculated.
      /// </summary>
      /// <param name="autoSizeMode">Current <see cref="AutoSizeControl.AutoSizeMode"/></param>
      /// <returns>Returns the needed size for the control</returns>
      protected override size OnMeasureControl(AutoSizeModes autoSizeMode)
      {
         int textWidth;
         int textHeight;
         uint textFlags;

         CalcTextMetrics(autoSizeMode, out textWidth, out textHeight, out textFlags);

         return new size(textWidth + Padding.Horizontal, textHeight + Padding.Vertical);

         //var size = FontManager.ComputeExtentEx(_font, _text);
         //size.Grow(Padding.Horizontal, Padding.Vertical);
         //return size;
      }

      /// <summary>
      /// Renders the control contents
      /// </summary>
      /// <param name="x">X position in screen coordinates</param>
      /// <param name="y">Y position in screen coordinates</param>
      /// <param name="width">Width in pixel</param>
      /// <param name="height">Height in pixel</param>
      /// <remarks>
      /// Renders the button in disabled, normal and pressed state and the focus rectangle if needed.
      /// </remarks>
      protected override void OnRender(int x, int y, int width, int height)
      {
         /*int w;
         int h;
         //_font.ComputeTextInRect(_text, out w, out h, Width - 6);
         _font.ComputeTextInRect(_text, out w, out h, Width - Padding.Horizontal);*/

         int textWidth;
         int textHeight;
         uint textFlags;

         CalcTextMetrics(AutoSizeMode, out textWidth, out textHeight, out textFlags);

         int textY;
         switch (VerticalTextAlignment)
         {
            case VerticalAlignment.Center:
               textY = Top + Padding.Top + ((Height - Padding.Vertical) - textHeight)/2;
               break;

            case VerticalAlignment.Bottom:
               textY = Top + Height - Padding.Bottom - textHeight;
               break;

            default:
               textY = Top + Padding.Top;
               break;
         }

         // Draw Background
         if (Enabled)
         {
            if (_state == PressState.Pressed)
            {
               Core.Screen.DrawRectangle(_pressedBorderColor, 1, Left, Top, Width, Height, 0, 0, _pressdBackgroundGradientTopColor, Left, Top, _pressdBackgroundGradientBottomColor, Left, Top + Height, 256);

               if (_image != null)
               {
                  DrawBackground();
               }

               if ((RenderStyle & ButtonRenderStyles.TextShadow) != 0)
               {
                  //Core.Screen.DrawTextInRect(_text, Left + 4, Top + (Height / 2 - h / 2) - 1, Width - 9, h, Bitmap.DT_AlignmentCenter + Bitmap.DT_WordWrap + Bitmap.DT_TrimmingNone, _pressedShd, _font);
                  Core.Screen.DrawTextInRect(_text, Left + Padding.Left, textY - 1, Width - Padding.Horizontal - 1, textHeight, textFlags, _pressedTextShadowColor, _font);
               }
               //Core.Screen.DrawTextInRect(_text, Left + 4, Top + (Height / 2 - h / 2), Width - 8, h, Bitmap.DT_AlignmentCenter + Bitmap.DT_WordWrap + Bitmap.DT_TrimmingNone, _pfore, _font);
               Core.Screen.DrawTextInRect(_text, Left + Padding.Left, textY, Width - Padding.Horizontal, textHeight, textFlags, _pressedTextColor, _font);

               if ((RenderStyle & ButtonRenderStyles.PressedShadowBorder) != 0)
               {
                  Core.ShadowRegionInset(Left, Top, Width, Height);
               }
            }
            else
            {
               Core.Screen.DrawRectangle(_borderColor, 1, Left, Top, Width, Height, 0, 0, _backgroundGradientTopColor, Left, Top, _backgroundGradientBottomColor, Left, Top + Height, 256);

               if (_image != null)
               {
                  DrawBackground();
               }

               if ((RenderStyle & ButtonRenderStyles.TextShadow) != 0)
               {
                  //Core.Screen.DrawTextInRect(_text, Left + 4, Top + (Height / 2 - h / 2) + 1, Width - 7, h, Bitmap.DT_AlignmentCenter + Bitmap.DT_WordWrap + Bitmap.DT_TrimmingNone, Colors.White, _font);
                  Core.Screen.DrawTextInRect(_text, Left + Padding.Left, textY + 1, Width - Padding.Horizontal + 1, textHeight, textFlags, _textShadowColor, _font);
               }
               //Core.Screen.DrawTextInRect(_text, Left + 4, Top + (Height / 2 - h / 2), Width - 8, h, Bitmap.DT_AlignmentCenter + Bitmap.DT_WordWrap + Bitmap.DT_TrimmingNone, _nfore, _font);
               Core.Screen.DrawTextInRect(_text, Left + Padding.Left, textY, Width - Padding.Horizontal, textHeight, textFlags, _textColor, _font);
            }
         }
         else
         {
            Core.Screen.DrawRectangle(_borderColor, 1, Left, Top, Width, Height, 0, 0, _backgroundGradientBottomColor, Left, Top, _backgroundGradientBottomColor, Left, Top + Height, 256);

            if (_image != null)
            {
               DrawBackground();
            }

            //Core.Screen.DrawTextInRect(_text, Left + 4, Top + (Height / 2 - h / 2), Width - 8, h, Bitmap.DT_AlignmentCenter + Bitmap.DT_WordWrap + Bitmap.DT_TrimmingNone, _nfore, _font);
            Core.Screen.DrawTextInRect(_text, Left + Padding.Left, textY, Width - Padding.Horizontal, textHeight, textFlags, _textColor, _font);
         }

         // Focus rectangle
         if (_state != PressState.Pressed && Focused && (RenderStyle & ButtonRenderStyles.ShowFocusRectangle) != 0 && (Enabled || (RenderStyle & ButtonRenderStyles.ShowDisabledFocusRectangle) != 0))
         {
            Core.Screen.DrawRectangle(0, 0, Left + 1, Top + 1, Width - 2, 1, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 90);
            Core.Screen.DrawRectangle(0, 0, Left + 1, Top + Height - 2, Width - 2, 1, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 90);
            Core.Screen.DrawRectangle(0, 0, Left + 1, Top + 2, 1, Height - 4, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 90);
            Core.Screen.DrawRectangle(0, 0, Left + Width - 2, Top + 2, 1, Height - 4, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 90);
            Core.Screen.DrawRectangle(0, 0, Left + 2, Top + 2, Width - 4, 1, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 40);
            Core.Screen.DrawRectangle(0, 0, Left + 2, Top + Height - 3, Width - 4, 1, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 40);
            Core.Screen.DrawRectangle(0, 0, Left + 2, Top + 3, 1, Height - 6, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 40);
            Core.Screen.DrawRectangle(0, 0, Left + Width - 3, Top + 3, 1, Height - 6, 0, 0, Core.SystemColors.SelectionColor, 0, 0, Core.SystemColors.SelectionColor, 0, 0, 40);
         }

         // no need to call base.OnRender
      }

      #endregion

      #region Private Methods

      private void DefaultColors()
      {
         _textColor = Core.SystemColors.FontColor;
         _pressedTextColor = Core.SystemColors.SelectedFontColor;
         _borderColor = Core.SystemColors.BorderColor;
         _pressedBorderColor = Core.SystemColors.PressedControlTop;

         _backgroundGradientTopColor = Core.SystemColors.ControlTop;
         _backgroundGradientBottomColor = Core.SystemColors.ControlBottom;

         _pressdBackgroundGradientTopColor = Core.SystemColors.PressedControlTop;
         _pressdBackgroundGradientBottomColor = Core.SystemColors.PressedControlBottom;

         _textShadowColor = Core.SystemColors.TextShadow;
         _pressedTextShadowColor = Core.SystemColors.PressedTextShadow;
      }

      private void DrawBackground()
      {
         int w = Width;
         int h = Height;

         switch (_imageScaleMode)
         {
            case ScaleMode.Center:
               Core.Screen.DrawImage(Left + (w / 2 - _image.Width / 2), Top + (h / 2 - _image.Height / 2), _image, 0, 0, _image.Width, _image.Height);
               break;

            case ScaleMode.Normal:
               Core.Screen.DrawImage(Left, Top, _image, 0, 0, _image.Width, _image.Height);
               break;

            case ScaleMode.Scale:
               float multiplier;

               if (_image.Height > _image.Width)
               {
                  // Portrait
                  if (h > w)
                  {
                     multiplier = w/(float) _image.Width;
                  }
                  else
                  {
                     multiplier = h / (float)_image.Height;
                  }
               }
               else
               {
                  // Landscape
                  if (h > w)
                  {
                     multiplier = w / (float)_image.Width;
                  }
                  else
                  {
                     multiplier = h / (float)_image.Height;
                  }
               }

               var dsW = (int)(_image.Width * multiplier);
               var dsH = (int)(_image.Height * multiplier);
               var dX = (int)((float)w / 2 - (float)dsW / 2);
               var dY = (int)((float)h / 2 - (float)dsH / 2);

               Core.Screen.StretchImage(Left + dX, Top + dY, _image, dsW, dsH, 256);
               break;

            case ScaleMode.Stretch:
               Core.Screen.StretchImage(Left, Top, _image, w, h, 256);
               break;

            case ScaleMode.Tile:
               Core.Screen.TileImage(Left, Top, _image, w, h, 256);
               break;
         }
      }

      #endregion
   }

   /// <summary>
   /// Render style flags for <see cref="Button"/>
   /// </summary>
   [Flags]
   public enum ButtonRenderStyles
   {
      /// <summary>
      /// Disables all render styles
      /// </summary>
      None = 0,

      /// <summary>
      /// Render text shadow
      /// </summary>
      TextShadow = 0x01,

      /// <summary>
      /// Draw inner shadow on <see cref="Button"/> when pressed
      /// </summary>
      PressedShadowBorder = 0x02,

      /// <summary>
      /// Draw rectangle around <see cref="Button"/> when focused
      /// </summary>
      ShowFocusRectangle = 0x04,

      /// <summary>
      /// Draw focus rectangle around <see cref="Button"/> even when disabled
      /// </summary>
      ShowDisabledFocusRectangle = 0x08,

      /// <summary>
      /// Default <see cref="Button"/> render style
      /// </summary>
      /// <remarks>
      /// The default style includes <see cref="TextShadow"/>, <see cref="PressedShadowBorder"/>, <see cref="ShowFocusRectangle"/> and <see cref="ShowDisabledFocusRectangle"/>.
      /// </remarks>
      Default = TextShadow | PressedShadowBorder | ShowFocusRectangle | ShowDisabledFocusRectangle
   }
}


text:
layout: ja/eventja
title: Local Chapter congress
theme: Local community
theme_full: Local community
category: Local community
audience: "(3b) Core OSM: OSMF working groups (community, licence, data...)"
audience_full: "(3b) Core OSM: OSMF working groups (community, licence, data...)"
name: Martijn van Exel
organization: OSMF
twitter: openstreetmap
osm:
room: Room 1
tags:
  - turn23
youtube_recording:
---
So much of OpenStreetMap happens in Local Chapters. There's an incredible diversity of cultures and geography represented in our local groups, yet we have so much in common. There is much to learn about organizing and closely supporting mapping communities, outside of the usual skills of making maps and working with tech. Let's gather leaders in Local Chapters to figure out what kinds of organizational efforts we can share together.


text:
Creating Mocks
==============

Mocks are created with Mokka::mock() along with the name of the class that you want to mock.
Starting with PHP 5.5 you can use the 'class' keyword, which is highly recommended for better
refactoring support.

.. code-block:: php

    <?php
    $mock = Mokka::mock(SampleClass::class);

If you are using PHP 5.4 (which is the minimum required for Mokka),
you can alternatively pass the class name as a string.

.. code-block:: php

    <?php
    $mock = Mokka::mock('SampleClass');

The huge drawback of this is that your IDE won't recognize this as a class name,
meaning your mocks will break if you rename 'SampleClass' to something else
with a refactoring tool.

Using Mocks
^^^^^^^^^^^

The created Mock implements all methods of the mocked class (plus a few internal methods needed for mocking and stubbing).
All methods will return NULL when you call them.
See :doc:`mocking` and :doc:`stubbing` for information on how to change the behaviour of methods.