package derbytest;

import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.derby.drda.NetworkServerControl;


/**
 *
 * @author mmiller
 */
public class LobTestCase {

    private static final String TEST_DATA = 
            
"License " +
"The Apache License, Version 2.0\n" +
"\n" +
"\n                                Apache License\n" +
"\n                            Version 2.0, January 2004\n" +
"                        http://www.apache.org/licenses/\n" +
"\n" +
"   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n" +
"\n" +
"   1. Definitions.\n" +
"\n" +
"      \"License\" shall mean the terms and conditions for use,\n" +
"      reproduction, and distribution as defined by Sections 1 through\n" +
"      9 of this document.\n" +
"\n" +
"      \"Licensor\" shall mean the copyright owner or entity authorized\n" +
"      by the copyright owner that is granting the License.\n" +
"\n" +
"      \"Legal Entity\" shall mean the union of the acting entity and all\n" +
"      other entities that control, are controlled by, or are under\n" +
"      common control with that entity. For the purposes of this\n" +
"      definition, \"control\" means (i) the power, direct or indirect,\n" +
"      to cause the direction or management of such entity, whether by\n" +
"      contract or otherwise, or (ii) ownership of fifty percent (50%)\n" +
"      or more of the outstanding shares, or (iii) beneficial ownership\n" +
"      of such entity.\n" +
"\n" +
"      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n" +
"      exercising permissions granted by this License.\n" +
"\n" +
"      \"Source\" form shall mean the preferred form for making\n" +
"      modifications, including but not limited to software source code,\n" +
"      documentation source, and configuration files.\n" +
"\n" +
"      \"Object\" form shall mean any form resulting from mechanical\n" +
"      transformation or translation of a Source form, including but\n" +
"      not limited to compiled object code, generated documentation,\n" +
"      and conversions to other media types.\n" +
"\n" +
"      \"Work\" shall mean the work of authorship, whether in Source or\n" +
"      Object form, made available under the License, as indicated by a\n" +
"      copyright notice that is included in or attached to the work\n" +
"      (an example is provided in the Appendix below).\n" +
"\n" +
"      \"Derivative Works\" shall mean any work, whether in Source or\n" +
"      Object form, that is based on (or derived from) the Work and\n" +
"      for which the editorial revisions, annotations, elaborations,\n" +
"      or other modifications represent, as a whole, an original work\n" +
"      of authorship.  For the purposes of this License, Derivative\n" +
"      Works shall not include works that remain separable from, or\n" +
"      merely link (or bind by name) to the interfaces of, the Work\n" +
"      and Derivative Works thereof.\n" +
"\n" +
"      \"Contribution\" shall mean any work of authorship, including\n" +
"      the original version of the Work and any modifications or\n" +
"      additions to that Work or Derivative Works thereof, that is\n" +
"      intentionally submitted to Licensor for inclusion in the Work\n" +
"      by the copyright owner or by an individual or Legal Entity\n" +
"      authorized to submit on behalf of the copyright owner. For the\n" +
"      purposes of this definition,\n" +
"      \"submitted\" means any form of electronic, verbal, or written\n" +
"      communication sent to the Licensor or its representatives,\n" +
"      including but not limited to communication on electronic mailing\n" +
"      lists, source code control systems, and issue tracking systems\n" +
"      that are managed by, or on behalf of, the Licensor for the\n" +
"      purpose of discussing and improving the Work, but excluding\n" +
"      communication that is conspicuously marked or otherwise\n" +
"      designated in writing by the copyright owner as \"Not a\n" +
"      Contribution.\"\n" +
"\n" +
"      \"Contributor\" shall mean Licensor and any individual or Legal\n" +
"      Entity on behalf of whom a Contribution has been received by\n" +
"      Licensor and subsequently incorporated within the Work.\n" +
"\n" +
"   2. Grant of Copyright License. Subject to the terms and conditions\n" +
"      of this License, each Contributor hereby grants to You a\n" +
"      perpetual, worldwide, non-exclusive, no-charge, royalty-free,\n" +
"      irrevocable copyright license to reproduce, prepare Derivative\n" +
"      Works of, publicly display, publicly perform, sublicense, and\n" +
"      distribute the Work and such Derivative Works in Source or\n" +
"      Object form.\n" +
"\n" +
"   3. Grant of Patent License. Subject to the terms and conditions of\n" +
"      this License, each Contributor hereby grants to You a perpetual,\n" +
"      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n" +
"      (except as stated in this section) patent license to make, have\n" +
"      made, use, offer to sell, sell, import, and otherwise transfer\n" +
"      the Work, where such license applies only to those patent claims\n" +
"      licensable by such Contributor that are necessarily infringed by\n" +
"      their Contribution(s) alone or by combination of their\n" +
"      Contribution(s) with the Work to which such Contribution(s) was\n" +
"      submitted. If You institute patent litigation against any entity\n" +
"      (including a cross-claim or counterclaim in a lawsuit) alleging\n" +
"      that the Work or a Contribution incorporated within the Work\n" +
"      constitutes direct or contributory patent infringement, then any\n" +
"      patent licenses granted to You under this License for that Work\n" +
"      shall terminate as of the date such litigation is filed.\n" +
"\n" +
"   4. Redistribution. You may reproduce and distribute copies of the\n" +
"      Work or Derivative Works thereof in any medium, with or without\n" +
"      modifications, and in Source or Object form, provided that You\n" +
"      meet the following conditions:\n" +
"\n" +
"      (a) You must give any other recipients of the Work or\n" +
"          Derivative Works a copy of this License; and\n" +
"\n" +
"      (b) You must cause any modified files to carry prominent notices\n" +
"          stating that You changed the files; and\n" +
"\n" +
"      (c) You must retain, in the Source form of any Derivative Works\n" +
"          that You distribute, all copyright, patent, trademark, and\n" +
"          attribution notices from the Source form of the Work,\n" +
"          excluding those notices that do not pertain to any part of\n" +
"          the Derivative Works; and\n" +
"\n" +
"      (d) If the Work includes a \"NOTICE\" text file as part of its\n" +
"          distribution, then any Derivative Works that You distribute\n" +
"          must include a readable copy of the attribution notices\n" +
"          contained within such NOTICE file, excluding those notices\n" +
"          that do not pertain to any part of the Derivative Works, in\n" +
"          at least one of the following places: within a NOTICE text\n" +
"          file distributed as part of the Derivative Works; within the\n" +
"          Source form or documentation, if provided along with the\n" +
"          Derivative Works; or, within a display generated by the\n" +
"          Derivative Works, if and wherever such third-party notices\n" +
"          normally appear. The contents of the NOTICE file are for\n" +
"          informational purposes only and do not modify the License.\n" +
"          You may add Your own attribution notices within Derivative\n" +
"          Works that You distribute, alongside or as an addendum to\n" +
"          the NOTICE text from the Work, provided that such additional\n" +
"          attribution notices cannot be construed as modifying the\n" +
"          License.\n" +
"\n" +
"      You may add Your own copyright statement to Your modifications\n" +
"      and may provide additional or different license terms and\n" +
"      conditions for use, reproduction, or distribution of Your\n" +
"      modifications, or for any such Derivative Works as a whole,\n" +
"      provided Your use, reproduction, and distribution of the Work\n" +
"      otherwise complies with the conditions stated in this License.\n" +
"\n" +
"   5. Submission of Contributions. Unless You explicitly state\n" +
"      otherwise, any Contribution intentionally submitted for\n" +
"      inclusion in the Work by You to the Licensor shall be under the\n" +
"      terms and conditions of this License, without any additional\n" +
"      terms or conditions.  Notwithstanding the above, nothing herein\n" +
"      shall supersede or modify the terms of any separate license\n" +
"      agreement you may have executed with Licensor regarding such\n" +
"      Contributions.\n" +
"\n" +
"   6. Trademarks. This License does not grant permission to use the\n" +
"      trade names, trademarks, service marks, or product names of the\n" +
"      Licensor, except as required for reasonable and customary use\n" +
"      in describing the origin of the Work and reproducing the content\n" +
"      of the NOTICE file.\n" +
"\n" +
"   7. Disclaimer of Warranty. Unless required by applicable law or\n" +
"      agreed to in writing, Licensor provides the Work (and each\n" +
"      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n" +
"      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n" +
"      implied, including, without limitation, any warranties or\n" +
"      conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or\n" +
"      FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for\n" +
"      determining the appropriateness of using or redistributing the\n" +
"      Work and assume any risks associated with Your exercise of\n" +
"      permissions under this License.\n" +
"\n" +
"   8. Limitation of Liability. In no event and under no legal theory,\n" +
"      whether in tort (including negligence), contract, or otherwise,\n" +
"      unless required by applicable law (such as deliberate and\n" +
"      grossly negligent acts) or agreed to in writing, shall any\n" +
"      Contributor be liable to You for damages, including any direct,\n" +
"      indirect, special, incidental, or consequential damages of any\n" +
"      character arising as a result of this License or out of the use\n" +
"      or inability to use the Work (including but not limited to\n" +
"      damages for loss of goodwill, work stoppage, computer failure or\n" +
"      malfunction, or any and all other commercial damages or losses),\n" +
"      even if such Contributor has been advised of the possibility of\n" +
"      such damages.\n" +
"\n" +
"   9. Accepting Warranty or Additional Liability. While redistributing\n" +
"      the Work or Derivative Works thereof, You may choose to offer,\n" +
"      and charge a fee for, acceptance of support, warranty, indemnity,\n" +
"      or other liability obligations and/or rights consistent with this\n" +
"      License. However, in accepting such obligations, You may act only\n" +
"      on Your own behalf and on Your sole responsibility, not on behalf\n" +
"      of any other Contributor, and only if You agree to indemnify,\n" +
"      defend, and hold each Contributor harmless for any liability\n" +
"      incurred by, or claims asserted against, such Contributor by\n" +
"      reason of your accepting any such warranty or additional\n" +
"      liability.\n" +
"\n" +
"   END OF TERMS AND CONDITIONS\n" +
"\n" +
"   APPENDIX: How to apply the Apache License to your work.\n" +
"\n" +
"      To apply the Apache License to your work, attach the following\n" +
"      boilerplate notice, with the fields enclosed by brackets \"[]\"\n" +
"      replaced with your own identifying information. (Don't include\n" +
"      the brackets!)  The text should be enclosed in the appropriate\n" +
"      comment syntax for the file format. We also recommend that a\n" +
"      file or class name and description of purpose be included on the\n" +
"      same \"printed page\" as the copyright notice for easier\n" +
"      identification within third-party archives.\n" +
"\n" +
"   Copyright [yyyy] [name of copyright owner]\n" +
"\n" +
"   Licensed under the Apache License, Version 2.0 (the \"License\");\n" +
"   you may not use this file except in compliance with the License.\n" +
"   You may obtain a copy of the License at\n" +
"\n" +
"       http://www.apache.org/licenses/LICENSE-2.0\n" +
"\n" +
"   Unless required by applicable law or agreed to in writing, software\n" +
"   distributed under the License is distributed on an \"AS IS\" BASIS,\n" +
"   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n" +
"   implied.  See the License for the specific language governing\n" +
"   permissions and limitations under the License.\n";

    
    
    /**
     * Will start a network server on port 2222, create a database in the C:/tmp (change if you are on a unix machine).
     * It will then create 20K records, then attempt to iterate through them.  You will get an out of memory error.
     * 
     * @param args the command line arguments
     */
    public static void main(String[] args) throws SQLException, Exception {
        final NetworkServerControl server = new NetworkServerControl(InetAddress.getByName("localhost"), 2222);
        server.start (null);
        //just making sure it starts
        Thread.sleep(2000);
        //if it fails, we fail
        server.ping();
        
        //fails
        final Connection conn = DriverManager.getConnection("jdbc:derby://localhost:2222/c:/tmp/testdb;create=true;user=TEST_CASE");

        createTable(conn);    
        createTestData(conn);    
        readTest(conn);

        readTest(conn);
        conn.close();
    }
    
    public static void createTestData(final Connection conn) throws SQLException {
        final PreparedStatement insertTestRecords;
        
        insertTestRecords = conn.prepareStatement(
                "INSERT INTO TEST_CASE.TEST_LOB (" +
                " CONTENT " +
                ", URI" +
                ", SITE" +
                ", TITLE" +
                ", CONTENT_LENGTH" +
                ", VERSION" +
                ")" +
                " VALUES " +
                "(" +
                "?,?,?,?,?,?" +
                ")");
                
        final byte[] bytes = TEST_DATA.getBytes();
        conn.setAutoCommit(false);
        for(int i = 0; i < 20000; i++) {
            insertTestRecords.setBytes(1, bytes);
            insertTestRecords.setString(2, "Hello String");
            insertTestRecords.setString(3, "http://www.apache.org");
            insertTestRecords.setString(4, "Derby Database");
            insertTestRecords.setInt(5, bytes.length);
            insertTestRecords.setInt(6, i);

            insertTestRecords.executeUpdate();
            System.out.println(i);
        }
        conn.setAutoCommit(true);
        
        conn.commit();
    }

    public static void createTable(final Connection conn) throws SQLException {
        final Statement stmt = conn.createStatement();
        stmt.execute("CREATE TABLE TEST_CASE.TEST_LOB (" +
               "CONTENT BLOB not null," +
               "URI VARCHAR(1024) not null," +
               "SITE VARCHAR(1024) not null," +
               "TITLE VARCHAR(1024)," +
               "CONTENT_LENGTH INTEGER," +
               "VERSION BIGINT not null" +
                ")");
        conn.commit();
    }
    
    /**
     * This method will show that you can't loop through all the records in network mode.
     * @param conn
     * @throws java.sql.SQLException
     */
    private static void readTest(Connection conn) throws SQLException {
        final Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        final ResultSet rs = stmt.executeQuery("select * from TEST_CASE.TEST_LOB");
        
        for(int i = 0; rs.next(); i++) {
            System.out.println("Read: " + i + " records.");
        }
    }
    
}
