/*
 * Copyright (c) 2001, 2018, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package nsk.jdi.BreakpointEvent._itself_;

import com.sun.jdi.AbsentInformationException;
import com.sun.jdi.ClassNotPreparedException;
import com.sun.jdi.ObjectCollectedException;
import com.sun.jdi.Location;
import com.sun.jdi.ReferenceType;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.request.BreakpointRequest;
import com.sun.jdi.request.EventRequestManager;
import com.sun.jdi.VMDisconnectedException;
import com.sun.jdi.VMMismatchException;
import com.sun.jdi.event.*;

import java.util.Iterator;
import java.util.List;
import java.io.*;

import nsk.share.*;
import nsk.share.jpda.*;
import nsk.share.jdi.*;

/**
 * The test checks up on the JDI interface
 * <b>com.sun.jdi.event.BreakpointEvent.</b>
 * A debugger
 * part of the test creates several <code>BreakpointRequest</code>s,
 * and then it verifies that appropriate events are generated by
 * the target VM. After that the debugger removes the requests by
 * <code>deleteAllBreakpoints()</code> call. Finally, the test checks
 * that the events corresponding to the deleted requests, are not
 * generated by the target VM any more.
 */
public class breakpoint002 {
    public static final int PASSED = 0;
    public static final int FAILED = 2;
    public static final int JCK_STATUS_BASE = 95;
    static final String DEBUGGEE_CLASS =
        "nsk.jdi.BreakpointEvent._itself_.breakpoint002t";
    static final String COMMAND_READY = "ready";
    static final String COMMAND_QUIT = "quit";

    static final int BPS_NUM = 4;
    static final String COMMAND_RUN[] = {
        "run1", "run2", "run3", "run4"
    };
    static final int DEBUGGEE_LNS[] = {
        76, 79, 82, 85
    };
    private volatile int eventCount[] = {
        0, 0, 0, 0
    };

    private ArgumentHandler argHandler;
    private Log log;
    private IOPipe pipe;
    private Debugee debuggee;
    private VirtualMachine vm;
    private EventListener elThread;
    private volatile BreakpointRequest bpRequest[];
    private volatile int tot_res = PASSED;

// for notification a main thread about received events
    private Object gotEvent = new Object();

    public static void main (String argv[]) {
        System.exit(run(argv,System.out) + JCK_STATUS_BASE);
    }

    public static int run(String argv[], PrintStream out) {
        return new breakpoint002().runIt(argv, out);
    }

    private int runIt(String args[], PrintStream out) {
        argHandler = new ArgumentHandler(args);
        log = new Log(out, argHandler);
        Binder binder = new Binder(argHandler, log);
        ReferenceType rType;
        String cmd;

        debuggee = binder.bindToDebugee(DEBUGGEE_CLASS);
        pipe = debuggee.createIOPipe();
        debuggee.redirectStderr(log, "breakpoint002t.err> ");
        vm = debuggee.VM();
        EventRequestManager erManager = vm.eventRequestManager();
        debuggee.resume();
        cmd = pipe.readln();
        if (!cmd.equals(COMMAND_READY)) {
            log.complain("TEST BUG: unknown debuggee's command: "
                + cmd);
            tot_res = FAILED;
            return quitDebuggee();
        }

// Create testing requests
        if ((rType = debuggee.classByName(DEBUGGEE_CLASS)) == null) {
            log.complain("TEST FAILED: Method Debugee.classByName() returned null");
            tot_res = FAILED;
            return quitDebuggee();
        }
        if (createRequests(erManager, rType) == FAILED) {
            tot_res = FAILED;
            return quitDebuggee();
        }

// Create a thread listening JDI events
        elThread = new EventListener();
        elThread.setPriority(Thread.NORM_PRIORITY + 2);
        synchronized(gotEvent) {
            elThread.start();

// Check all requested BreakpointEvents
            for (int i=0; i<BPS_NUM; i++) {
                bpRequest[i].enable();
            }
            log.display("\na) Getting all requested BreakpointEvents...");
            if (checkEvents(false) != PASSED)
                return FAILED;

// Remove all BreakpointRequests
            log.display("\nb) Removing all BreakpointRequests");
            erManager.deleteAllBreakpoints();

// Check that all BreakpointRequests are removed
            checkEvents(true);

            quitDebuggee();

// Verify that we did not receive any more breakpoint events
            for (int i=0; i<BPS_NUM; i++) {
                if (eventCount[i] > 0) {
                    log.complain("TEST FAILED: got more than one breakpoint event for bp "+i);
                    return FAILED;
                }
            }
            log.display("\nTEST PASSED: no events corresponding to the deleted BreakpointRequests");

        }

// Finish the test
        return tot_res;
    }

    private int createRequests(EventRequestManager erManager,
            ReferenceType rType) {
        List loctns;

        bpRequest =
            new BreakpointRequest[BPS_NUM];
        for (int i=0; i<BPS_NUM; i++) {
            try {
                loctns = rType.locationsOfLine(DEBUGGEE_LNS[i]);
            } catch(AbsentInformationException e) {
                log.complain("TEST FAILURE: ReferenceType.locationsOfLine(): caught "
                    + e);
                return FAILED;
            } catch(ClassNotPreparedException e) {
                log.complain("TEST FAILURE: ReferenceType.locationsOfLine(): caught "
                    + e);
                return FAILED;
            } catch(ObjectCollectedException e) {
                log.complain("TEST FAILURE: ReferenceType.locationsOfLine(): caught "
                    + e);
                return FAILED;
            }

            if (loctns.size() != 1) {
                log.complain("TEST FAILED: ReferenceType.locationsOfLine() returned "
                    + loctns.size() + " JDI Locations\n\tfor the debuggee's line #"
                    + DEBUGGEE_LNS[i] + " instead of only 1 Location");
                return FAILED;
            }
            Location loc = (Location) loctns.get(0);
            try {
                log.display("Creating BreakpointRequest #"
                    + i + " for the debuggee's location:\n\tfile: "
                    + loc.sourceName() + ":" + loc.lineNumber()
                    + "\tmethod: " + loc.method().returnTypeName()
                    + " " + loc.method().name());
            } catch(AbsentInformationException e) {
                log.complain("TEST FAILED: Location.sourceName(): caught "
                    + e);
                tot_res = FAILED;
            }
            try {
                bpRequest[i] = erManager.createBreakpointRequest(loc);
                bpRequest[i].setSuspendPolicy(BreakpointRequest.SUSPEND_NONE);
            } catch (NullPointerException e) {
                log.complain("TEST FAILED: BreakpointEvent.createBreakpointRequest(): caught "
                    + e);
                return FAILED;
            } catch (VMMismatchException e) {
                log.complain("TEST FAILED: BreakpointEvent.createBreakpointRequest(): caught "
                    + e);
                return FAILED;
            }
        }
        return PASSED;
    }

    private int runTestCase(int i, boolean waitForEvent) {
        String token = null;

        log.display("\n" + (i+1) + ") Sending the command \""
            + COMMAND_RUN[i] + "\" to a debuggee");
        pipe.println(COMMAND_RUN[i]);

// wait for a requested event
        if (waitForEvent) {
            try {
                gotEvent.wait(argHandler.getWaitTime() * 60 * 1000);
            } catch (InterruptedException e) {
                log.complain("TEST FAILURE: waiting for a requested BreakpointEvent #"
                    + i + ": caught " + e);
                e.printStackTrace();
                tot_res = FAILED;
                return quitDebuggee();
            }
            log.display("Notification about the BreakpointEvent #"
                + i + " received,\n\tor time has elapsed");
        }

        if ((token = pipe.readln()) == null) {
            log.complain("TEST FAILURE: debuggee's reply is empty, probably due to the VM crash");
            tot_res = FAILED;
            return quitDebuggee();
        }
        if (!token.equals(COMMAND_READY)) {
            log.complain("TEST BUG: unknown debuggee's command: "
                + token);
            tot_res = FAILED;
            return quitDebuggee();
        }
        else log.display("Debuggee's reply received: "
            + token);
        return PASSED;
    }

    private int checkEvents(boolean shouldNtBe) {
        for (int i=0; i<BPS_NUM; i++) {
            eventCount[i] = 0;
            if (runTestCase(i, !shouldNtBe) == FAILED)
                return FAILED;
            if (shouldNtBe) {
                if (eventCount[i] != 0) {
                    log.complain("TEST FAILED: got BreakpointEvent for the request #"
                        + i + "\n\tbut all BreakpointRequests should be deleted\n\t"
                        + "by the EventRequestManager.deleteAllBreakpoints()");
                    tot_res = FAILED;
                } else
                    log.display("\nTEST PASSED: no event corresponding to the deleted BreakpointRequest #"
                        + i);
            } else {
                if (eventCount[i] != 0) {
                    log.display("Got expected BreakpointEvent for the request #"
                        + i);
                } else {
                    log.complain("TEST FAILED: no BreakpointEvent for the request #"
                        + i);
                    tot_res = FAILED;
                }
            }
        }
        return PASSED;
    }

    private int quitDebuggee() {
        if (elThread != null) {
            elThread.isConnected = false;
            try {
                if (elThread.isAlive())
                    elThread.join();
            } catch (InterruptedException e) {
                log.complain("TEST INCOMPLETE: caught InterruptedException "
                    + e);
                tot_res = FAILED;
            }
        }

        pipe.println(COMMAND_QUIT);
        debuggee.waitFor();
        int debStat = debuggee.getStatus();
        if (debStat != (JCK_STATUS_BASE + PASSED)) {
            log.complain("TEST FAILED: debuggee's process finished with status: "
                + debStat);
            tot_res = FAILED;
        } else
            log.display("Debuggee's process finished with status: "
                + debStat);

        return tot_res;
    }

    class EventListener extends Thread {
        public volatile boolean isConnected = true;

        public void run() {
            try {
                do {
                    EventSet eventSet = vm.eventQueue().remove(10);
                    if (eventSet != null) { // there is not a timeout
                        EventIterator it = eventSet.eventIterator();
                        while (it.hasNext()) {
                            Event event = it.nextEvent();
                            if (event instanceof VMDeathEvent) {
                                tot_res = FAILED;
                                isConnected = false;
                                log.complain("TEST FAILED: caught unexpected VMDeathEvent");
                            } else if (event instanceof VMDisconnectEvent) {
                                tot_res = FAILED;
                                isConnected = false;
                                log.complain("TEST FAILED: caught unexpected VMDisconnectEvent");
                            } else {
                                log.display("EventListener: following JDI event occured: "
                                    + event.toString());

                                if (event instanceof BreakpointEvent) {
                                    BreakpointEvent bpEvent =
                                        (BreakpointEvent) event;
                                    Location loc = bpEvent.location();
                                    boolean notFound = true;
                                    for (int i=0; i<BPS_NUM; i++) {
                                        if (bpRequest[i].equals(event.request())) {
                                            try {
                                                log.display("EventListener: BreakpointEvent #"
                                                    + i + " for the debuggee's location:\n\tfile: "
                                                    + loc.sourceName() + ":" + loc.lineNumber()
                                                    + "\tmethod: " + loc.method().returnTypeName() + " "
                                                    + loc.method().name());
                                            } catch(AbsentInformationException e) {
                                                log.complain("EventListener: Location.sourceName(): caught "
                                                    + e);
                                                tot_res = FAILED;
                                            }
                                            eventCount[i] += 1;
                                            notFound = false;
                                            log.display("EventListener: notifying about the received event #"
                                                + i);
                                            synchronized(gotEvent) {
                                                gotEvent.notify(); // notify the main thread
                                            }
                                            break;
                                        }
                                    }
                                    if (notFound) {
                                        try {
                                            log.complain("TEST FAILED: found in the received BreakpointEvent\n"
                                            + "\tunexpected debuggee's location:\n\tfile: "
                                            + loc.sourceName() + ":" + loc.lineNumber()
                                            + "\tmethod: " + loc.method().returnTypeName() + " "
                                            + loc.method().name());
                                        } catch(AbsentInformationException e) {
                                            log.complain("EventListener: Location.sourceName(): caught "
                                                + e);
                                        } finally {
                                            tot_res = FAILED;
                                        }
                                    }
                                }

                            }
                        }
                        if (isConnected) {
                            eventSet.resume();
                        }
                    }
                } while (isConnected);
            } catch (InterruptedException e) {
                tot_res = FAILED;
                log.complain("FAILURE in EventListener: caught unexpected "
                    + e);
            } catch (VMDisconnectedException e) {
                tot_res = FAILED;
                log.complain("FAILURE in EventListener: caught unexpected "
                    + e);
                e.printStackTrace();
            }
            log.display("EventListener: exiting");
        }
    }
}
