package basextest;

import java.io.IOException;
import org.basex.api.client.LocalSession;
import org.basex.api.client.Query;
import org.basex.api.client.Session;
import org.basex.core.Context;
import org.basex.core.MainOptions;
import org.basex.core.cmd.Add;
import org.basex.core.cmd.CreateDB;
import org.basex.core.cmd.DropDB;
import org.basex.core.cmd.Flush;
import org.basex.core.cmd.Set;

public class OutOfMemoryWithQueryMore {

    public static void main(String[] args) {
        // first let's generate some "big" XML document
        final StringBuilder xmlBuilder = new StringBuilder();
        xmlBuilder.append("<notif id=\"name\" ts=\"1234\">");
        for (int i = 0; i < 300; i++) {
            xmlBuilder.append("<junk>").append(i).append("</junk>");
        }
        xmlBuilder.append("</notif>");
        final String xml = xmlBuilder.toString();

        final Context context = new Context();
        try (final Session session = new LocalSession(context)) {
            session.execute(new Set(MainOptions.AUTOFLUSH, false));
            session.execute(new DropDB("DB1"));
            session.execute(new CreateDB("DB1"));
            // fill the collection
            for (int i = 0; i < 60000; i++) {
                session.execute(new Add("TEST", xml));
                if ((i % 5000) == 0) {
                    session.execute(new Flush());
                    System.out.println("Flushed " + i);
                }
            }
            System.out.println("Query collection");
            try (final Query query = session.query("for $d in collection('DB1')/* return $d")) {
                query.more(); // => throws java.lang.OutOfMemoryError: Java heap space
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
