//------------------------------------------------------------------------------
// <copyright file="BasicTests.java" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <summary>
//      Basic SOA tests using Java.
// </summary>
//------------------------------------------------------------------------------

import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

import org.tempuri.*;
import com.microsoft.hpc.scheduler.session.*;
import com.microsoft.hpc.exceptions.*;
import com.microsoft.hpc.sessionlauncher.*;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.binding.soap.*;
import org.apache.cxf.binding.Binding;
import org.apache.cxf.service.model.BindingInfo;

public class BasicTests
{    
    public static String username = "redmond\\hpclabsa";
    public static String password = "Pa55word55%";  
    private static String headnode = "liweiphn04";
    private static String serviceName = "CcpEchoSvc";

    private static String testname = "";
    
    public static void main(String[] args) 
    {
        HpcJava.hideCXF();
        int nerrs = 0;
        nerrs += ParseCmdLine(args);
        if (nerrs == 0) {           
            Date startTime = new Date();            
            try {           
                TestUtil.InitLog("log.txt");
                nerrs += RunTests();                                
            }
            catch(Exception e) {
                nerrs++;
                TestUtil.Log.WriteException(e);
            }
            Date endTime = new Date();
            long totalSeconds = (endTime.getTime() - startTime.getTime())/1000;
            int testItemCount = TestUtil.GetTestItemsCount();
            
            TestUtil.Log.WriteConsole("\n#Tests: " + testItemCount + "; #Errors: " + nerrs + "; Runtime(s): " + totalSeconds);
            TestUtil.Log.Close();
        }
        
        System.exit(nerrs);
    }


    private static void Usage()
    {
        System.out.println("Usage: BasicTests /scheduler scheduler /username user /password pwd /testname name");
    }


    private static int ParseCmdLine(String [] args)
    {
        int nerrs = 0;
        int i = 0;
        String arg;
        while (i < args.length && args[i].startsWith("/")) {
            arg = args[i++];
            if (arg.equalsIgnoreCase("/scheduler")) {
                headnode = args[i++];
            }
            else if (arg.equalsIgnoreCase("/username")) {
                username = args[i++];
            }
            else if (arg.equalsIgnoreCase("/password")) {
                password = args[i++];
            }            
            else if (arg.equalsIgnoreCase("/testname")) {
                testname = args[i++];
            }
            else {
                Usage();
                nerrs++;
                break;
            }
        }

        return nerrs;
    }
    
    static int RunTests()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;

        try
        {
            Method m[] = (BasicTests.class).getDeclaredMethods();
            for(Method t : m)
            {
                if(t.getName().startsWith("Test_") &&
                   (testname == "" || testname.equalsIgnoreCase(t.getName())))                
                {
                    TestUtil.Log.WriteConsole("%n>>>>> Run TestCase: " + t.getName());
                    int nerrs1 = (Integer)t.invoke(null);
                    if(nerrs1 > 0)
                    {
                        TestUtil.Log.WriteFails("%s \t NumberOfErrors: %d", t.getName(), nerrs1);
                    }
                    TestUtil.Log.WriteConsole("\tFinished %s; #Errors: %d", t.getName(), nerrs1);
                    nerrs += nerrs1;
                }
            }
            TestUtil.Log.Flush();
        }
        catch(Exception e)
        {
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }

    static int Test_BasicSession()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests = 200;
        TestUtil.LogTestItem("BasicSession: #Request=%d", nrequests);
        
        try
        {
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);                        
            TestUtil.Log.WriteConsole("CreateSession...");
            Session session = Session.createSession(startInfo);            
            int sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);
            nerrs += TestSendRequestsOnly(client, nrequests);
            client.endRequests();
            TestUtil.Log.WriteConsole("Get responses...");
            nerrs += TestGetResponsesOnly(client, nrequests);
            TestUtil.Log.WriteConsole("Close session...");
            session.close();
            session.dispose();
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }
    
    static int Test_DurableSession()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests = 3333;
        TestUtil.LogTestItem("DurableSession: #Request=%d", nrequests);
        
        try
        {
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            TestUtil.Log.WriteConsole("CreateSession...");
            DurableSession session = DurableSession.createSession(startInfo);
            
            int sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);            
            nerrs += TestSendRequestsOnly(client, nrequests);
            client.endRequests();            
            TestUtil.Log.WriteConsole("Get responses...");
            nerrs += TestGetResponsesOnly(client, nrequests);
            TestUtil.Log.WriteConsole("Close session...");
            session.close();
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }
    
    static int Test_PullResponsesExcess()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests = 150;
        TestUtil.LogTestItem("PullResponseExcess: RequestCount=%d", nrequests);
        
        try
        {
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            TestUtil.Log.WriteConsole("CreateSession...");
            DurableSession session = DurableSession.createSession(startInfo);
            
            int sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);
            
            nerrs += TestSendRequestsOnly(client, nrequests-1);
            TestUtil.Log.WriteConsole("call endRequests() ...");
            client.endRequests();
            
            TestUtil.Log.WriteConsole("Get responses...");
            nerrs += TestGetResponsesOnly(client, nrequests-1, nrequests);
            TestUtil.Log.WriteConsole("Close session...");
            session.close();
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }
    
    static int Test_SendAndAttachNonDurable()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests = 50;
        TestUtil.LogTestItem("SendAndAttachSessionNonDurable: RequestCount=%d", nrequests);
        
        try
        {            
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            TestUtil.Log.WriteConsole("CreateSession...");
            Session session = Session.createSession(startInfo);
            
            int sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);
            
            nerrs += TestSendRequestsOnly(client, nrequests);
            TestUtil.Log.WriteConsole("call endRequests() ...");
            client.endRequests();
            
            //nerrs += TestWaitForJobFinish(sessionId, 36000);
            
            nerrs += TestAttachOnly(sessionId, nrequests);
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }
    
    static int Test_SendAndAttach()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests = 120;
        TestUtil.LogTestItem("SendAndAttachSession: #Request=%d", nrequests);
        
        try
        {            
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            TestUtil.Log.WriteConsole("CreateSession...");
            DurableSession session = DurableSession.createSession(startInfo);
            
            int sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);
            
            nerrs += TestSendRequestsOnly(client, nrequests);
            TestUtil.Log.WriteConsole("call endRequests() ...");
            client.endRequests();
            
            nerrs += TestAttachOnly(sessionId, nrequests);
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }
    
    
    static int Test_ClosePurge()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        TestUtil.LogTestItem("ClosePurge: CreateSession-ClosePurge");
        try
        {            
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            com.microsoft.hpc.ObjectFactory of = new com.microsoft.hpc.ObjectFactory();
            startInfo.setSessionIdleTimeout(300000);
            
            TestUtil.Log.WriteConsole("CreateSession...");
            DurableSession session = DurableSession.createSession(startInfo);
            
            int sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);
            TestUtil.Log.WriteLine("Purging client and session");
            client.close(true);
            session.close(true);
            nerrs += TestSessionTerminate(sessionId, false);
                        
            TestUtil.Log.WriteConsole("CreateSession 2...");
            session = DurableSession.createSession(startInfo);
            
            sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);
            TestUtil.Log.WriteLine("Purging client and session");
            client.close(false);
            session.close(false);
            nerrs += TestSessionTerminate(sessionId, false);
        }
        catch(Exception e)
        {
            TestUtil.Log.WriteException(e);
            nerrs++;
        }
        return nerrs;
    }
    
    static int Test_MultipleBatchtest()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests = 100;
        int nbatches = 10;
        TestUtil.LogTestItem("MultipleBatch: #Batches=%d, #Request/batch=%d", nbatches, nrequests);
        
        try
        {            
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            TestUtil.Log.WriteConsole("CreateSession...");
            DurableSession session = DurableSession.createSession(startInfo);
            
            int sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            LinkedList<BrokerClient<CcpEchoSvc>> clients = new LinkedList<BrokerClient<CcpEchoSvc>>();
            for(int i = 1; i <= nbatches; i++)
            {
                String clientid = "batch" + i;
                BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(clientid, session, CcpEchoSvc.class);                
                nerrs += TestSendRequestsOnly(client, nrequests);                
                client.endRequests();
                clients.add(client);
            }
            int i = 1;
            for(BrokerClient<CcpEchoSvc> client : clients)
            {
                String clientid = "batch" + i;
                TestUtil.Log.WriteConsole("Get responses from %s...", clientid);
                nerrs += TestGetResponsesOnly(client, nrequests);
                i++;
            }
            
            TestUtil.Log.WriteConsole("Close session...");
            session.close();
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }

    public static int Test_SharedSession()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests = 200;
        int nclients = 5;
        TestUtil.LogTestItem("SharedSession: #Client=%d, #Request=%d", nclients,  nrequests);
        
        try
        {            
            SessionStartInfo info = new SessionStartInfo(headnode, serviceName, username, password);            
            info.setShareSession(true);
            
            DurableSession session = DurableSession.createSession(info);
            int sessionId = session.getId();
            TestUtil.Log.WriteLine("New Shared Session: %d;, EPR=%s", sessionId, session.getEndpointReference());
            
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>("client-base", session, CcpEchoSvc.class);
            nerrs += TestSendRequestsOnly(client, nrequests);
            client.endRequests();
            
            for(int i = 1; i <= nclients; i++)
            {
                TestUtil.Log.WriteConsole("Creating client-" + i);
                SessionAttachInfo attachInfo = new SessionAttachInfo(headnode, sessionId, username, password); 
                DurableSession sharedSession = DurableSession.attachSession(attachInfo);
                BrokerClient<CcpEchoSvc> sharedClient = new BrokerClient<CcpEchoSvc>("client-" + i, sharedSession, CcpEchoSvc.class);
                TestUtil.Log.WriteConsole("\tSend %d requests to client %s", nrequests, "client-" + i);
                nerrs += TestSendRequestsOnly(sharedClient, nrequests);
                sharedClient.endRequests();
                TestUtil.Log.WriteConsole("Client-%d finished", i);
                sharedClient.close();
            }
            session.close();                
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }
    
    public static int Test_EndRequestsBad()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests = 20;
        TestUtil.LogTestItem("endRequests Bad values #Messages%d", nrequests);
        try
        {
            SessionStartInfo info = new SessionStartInfo(headnode, serviceName, username, password);
            info.setUsername(username);
            info.setPassword(password);
            
            DurableSession session = DurableSession.createSession(info);
            int sessionId = session.getId();
            TestUtil.Log.WriteLine("New Shared Session: %d;, EPR=%s", sessionId, session.getEndpointReference());
            
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);
            nerrs += TestSendRequestsOnly(client, nrequests);
            try
            {
                TestUtil.Log.WriteConsole("Trying eom -1");
                client.endRequests(-1);
                nerrs++;
                TestUtil.Log.WriteLine("Exception expected");
            }
            catch(Exception e)
            {
                TestUtil.Log.WriteLine("Exception successfully caught");
                TestUtil.Log.WriteException(e);
            }
            try
            {
                TestUtil.Log.WriteConsole("Trying eom 0");
                client.endRequests(0);
                nerrs++;
                TestUtil.Log.WriteLine("Exception expected");
            }
            catch(Exception e)
            {
                TestUtil.Log.WriteLine("Exception successfully caught");
                TestUtil.Log.WriteException(e);
            }
            client.endRequests();
            client.close();
            session.close();
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }
    
    public static int Test_CustomBinding()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests  = 200;
        TestUtil.LogTestItem("CustomBinding(HTTP): CreateSession-SendRequests-Flush-Response. RequestCount=%d", nrequests);
        
        try
        {
            TestUtil.Log.WriteConsole("Grabbing existing binding info from CcpEchoSvc");
            String filename = "/" + (CcpEchoSvc.WSDL_LOCATION.getPath());
            CcpEchoSvc es = new CcpEchoSvc(BasicTests.class.getResource(filename));
            IEchoSvc ies = es.getDefaultBindingIEchoSvc();
            Client bl = ClientProxy.getClient(ies);
            BindingInfo bi = bl.getEndpoint().getBinding().getBindingInfo();
            
            TestUtil.Log.WriteConsole("Generating custom binding from existing binding info");
            Binding custom = new SoapBindingFactory().createBinding(bi);
                         
            TestUtil.Log.WriteConsole("Create Non-Durable session using custom binding");
            
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            
            TestUtil.Log.WriteConsole("CreateSession...");
            Session session = Session.createSession(startInfo);
            
            int sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, custom, CcpEchoSvc.class);
            
            nerrs += TestSendRequestsOnly(client, nrequests);
            TestUtil.Log.WriteConsole("call endRequests() ...");
            client.endRequests();
            TestUtil.Log.WriteConsole("Get responses...");
            nerrs += TestGetResponsesOnly(client, nrequests);
            TestUtil.Log.WriteConsole("Close session...");
            session.close();
            session.dispose();
            
            TestUtil.Log.WriteConsole("Create Durable session using custom binding");
            
            startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            
            TestUtil.Log.WriteConsole("CreateSession...");
            DurableSession session2 = DurableSession.createSession(startInfo);
            
            sessionId = session2.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            client = new BrokerClient<CcpEchoSvc>(session2, custom, CcpEchoSvc.class);
            
            nerrs += TestSendRequestsOnly(client, nrequests);
            TestUtil.Log.WriteConsole("call endRequests() ...");
            client.endRequests();
            TestUtil.Log.WriteConsole("Get responses...");
            nerrs += TestGetResponsesOnly(client, nrequests);
            TestUtil.Log.WriteConsole("Close session...");
            session2.close();
            session2.dispose();
           
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        return nerrs;
    }
    
    public static int Test_InstantTimeout()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        TestUtil.LogTestItem("TimeoutTest: CreateSession-Timeout. CreateSession, AttachSession-Timeout");
        
        try
        {            
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            TestUtil.Log.WriteConsole("Create session with timeout = 1ms");
            int id = 0;
            DurableSession session = null;
            try
            {
                session = DurableSession.createSession(startInfo, 1);
                nerrs++;
                TestUtil.Log.WriteConsole("Error: exception expected but never caught");
            }
            catch(TimeoutException e)
            {
                TestUtil.Log.WriteConsole("Expected Exception successfully caught:");
                TestUtil.Log.WriteException(e);
            }
            
            TestUtil.Log.WriteConsole("Create session. Then attach session with timeout = 1ms");
            
            try
            {
                session = DurableSession.createSession(startInfo, Timeout.Infinite);
                id = session.getId();
                TestUtil.Log.WriteConsole("Session created with session id = %d", id);
                SessionAttachInfo attachInfo = new SessionAttachInfo(headnode, id);
                DurableSession session2 = DurableSession.attachSession(attachInfo, 1);
                TestUtil.Log.WriteConsole("Error: exception expected but never caught");
                nerrs++;                
            }
            catch(TimeoutException e)
            {                   
                TestUtil.Log.WriteConsole("Expected exception successfully caught:");
                TestUtil.Log.WriteException(e);
            }
            
        }
        catch(Exception e)
        { 
            nerrs++;
            TestUtil.Log.WriteLine("Error: unexpected exception:");
            TestUtil.Log.WriteException(e);
        }
        return nerrs;
        
    }
    
    public static int Test2PromptforCredentials()
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        int nrequests = 20;
        TestUtil.LogTestItem("PromptPassword: CreateSession-SendRequests-Flush-Response. RequestCount=%d", nrequests);

        try
        {
            HpcJava.setUsernamePassword("", "");
            SessionStartInfo startInfo = new SessionStartInfo(headnode, serviceName, username, password);
            TestUtil.Log.WriteConsole("CreateSession...");
            Session.setInterfaceMode(true);
            Session session = Session.createSession(startInfo);

            int sessionId = session.getId();
            TestUtil.Log.WriteConsole("New session created. SessionId=%d", sessionId);
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);
            
            nerrs += TestSendRequestsOnly(client, nrequests);
            TestUtil.Log.WriteConsole("call endRequests() ...");
            client.endRequests();

            TestUtil.Log.WriteConsole("Get responses...");
            nerrs += TestGetResponsesOnly(client, nrequests);
            TestUtil.Log.WriteConsole("Close session...");
            session.close();
            session.dispose();
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }

        return nerrs;
    }
        
    private static int TestAttachOnly(int sessionId, int nrequests)
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
             
        try
        {
            SessionAttachInfo startInfo = new SessionAttachInfo(headnode, sessionId, username, password);
            TestUtil.Log.WriteConsole("AttachSession sessionId: %d...", sessionId);
            DurableSession session = DurableSession.attachSession(startInfo);
            TestUtil.Log.WriteConsole("Attach successful");
            BrokerClient<CcpEchoSvc> client = new BrokerClient<CcpEchoSvc>(session, CcpEchoSvc.class);
            TestUtil.Log.WriteConsole("Client successfully created");
            nerrs += TestGetResponsesOnly(client, nrequests);
            TestUtil.Log.WriteConsole("Close session...");
            session.close();
            
        } catch (Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        
        TestUtil.EndAPI(nerrs);
        return nerrs;
    }
    
    private static int TestSessionTerminate(int sessionId, Boolean exceptionExpected)
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        
        try
        {
            ISessionLauncher sessionLauncher = SOAUtil.GetSessionLauncher(headnode);
            sessionLauncher.terminate(headnode, sessionId);
            if(exceptionExpected)
            {
                TestUtil.Log.WriteFails("Exception was not caught where expected");
                nerrs++;
            }
        }
        catch(Exception e)
        {
            if(!exceptionExpected)
            {
                nerrs++;
                TestUtil.Log.WriteException(e);
            }
            else
            {
                TestUtil.Log.WriteConsole("Exception successfully caught: %s", e.getMessage());
                TestUtil.Log.WriteException(e);
            }
        }
        
        TestUtil.EndAPI(nerrs);
        return nerrs;
    }

    private static int TestGetResponsesOnly(BrokerClient<CcpEchoSvc> client,
            int expectedMsgCount)
    {
        return TestGetResponsesOnly(client, expectedMsgCount, expectedMsgCount);
    }
    
    
    private static int TestGetResponsesOnly(BrokerClient<CcpEchoSvc> client,
            int expectedMsgCount, int amountToPull)
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        
        int nMsgReceived = 0;
        int nMsgToPrint = (expectedMsgCount <= 100) ? expectedMsgCount : 100;
        
        try
        {
            TestUtil.Log.WriteLine("calling client.PullResponses - %d messages", expectedMsgCount);
            for(BrokerResponse<EchoResponse> response : client.<EchoResponse>pullResponses(EchoResponse.class, amountToPull))
            { 
                nMsgReceived++;
                String reply = response.getResult().getEchoResult().getValue();
                String userData = response.getUserData();
                if(nMsgReceived <= nMsgToPrint/2 || nMsgReceived >= (expectedMsgCount - (nMsgToPrint/2)))
                {
                    TestUtil.Log.WriteLine("\tReceived Request (%d/%d): %s, %s", nMsgReceived, expectedMsgCount, reply, userData);
                }
            }
            nerrs += TestUtil.ValidateObject(expectedMsgCount, nMsgReceived, "Number of messages received");
        }
        catch (Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteException(e);
        }
        TestUtil.EndAPI(nerrs);
        return nerrs;
    }
    
   
    private static int TestSendRequestsOnly(BrokerClient<CcpEchoSvc> client, int nrequests)
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        
        int nMsgSent = 0;
        int nMsgToPrint = (nrequests <= 100) ? nrequests : 100;
        
        try {
            TestUtil.Log.WriteConsole("Sending requests. nrequests=%d", nrequests);
            for(int i = 1; i <= nrequests; i++)
            {
                nMsgSent++;
                String request = "Hello World!";
                Echo echo = HpcJava.<Echo>createRequest(Echo.class, request);
                
                if(nMsgSent <= nMsgToPrint/2 || nMsgSent >= (nrequests - (nMsgToPrint/2)))
                {
                    TestUtil.Log.WriteLine("\tSend Request (%d/%d): %s, %d", nMsgSent, nrequests, request, i);
                }
                client.sendRequest(echo, i);
            }
            TestUtil.ValidateObject(nrequests, nMsgSent, "Number of messages Sent");
        }
        catch(Exception e)
        {
            nerrs++;
            TestUtil.Log.WriteLine("NumberOfMessage SentOut: %d", nMsgSent);
            TestUtil.Log.WriteException(e);
        }
        
        TestUtil.EndAPI(nerrs);
        
        return nerrs;
    }
    
    private static int TestWaitForJobFinish(int sessionId, int secondsToWait)
    {
        TestUtil.IntoAPI();
        int nerrs = 0;
        
        TestUtil.LogTestItem("Waiting for JobFinished (.net) to exit");
        
        try
        {
            TestUtil.Log.WriteConsole("waiting...");
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec("JobFinished.exe " + sessionId + " " + secondsToWait);
            
            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            
            String line = null;
            
            while((line=input.readLine()) != null) {
                System.out.println(line);
            }
            
            int exitVal = pr.waitFor();
            nerrs = exitVal;
            
        } catch (Exception e) {
            nerrs ++;
            TestUtil.Log.WriteException(e);
        }
     
        TestUtil.EndAPI(nerrs);
        return nerrs;
    }

}
