package ejbclient85;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.jboss.as.quickstarts.ejb.multi.server.app.AppOne;
import org.jboss.as.quickstarts.ejb.multi.server.app.AppTwo;

public class TooManyChannelsOpenedClient {

    private static final Logger LOGGER = Logger.getLogger(TooManyChannelsOpenedClient.class.getName());
    final String user;
    final String password;
    final String port;

    public TooManyChannelsOpenedClient(String user, String password, String port, Boolean debug) {
        this.user = user;
        this.password = password;
        this.port = port;

        Level l = debug == null ? Level.SEVERE : debug.booleanValue() ? Level.ALL : Level.INFO;
        Logger.getLogger("").setLevel(l);
        Logger.getLogger("").getHandlers()[0].setLevel(Level.ALL);
        Logger.getLogger(TooManyChannelsOpenedClient.class.getPackage().getName()).setLevel(
            debug != null ? Level.FINEST : Level.INFO);
    }

    /**
     * Invoke using Remote Naming.
     */
    private void invokeUsingRemoteNaming() throws NamingException {
        Properties p = new Properties();
        // p.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
        p.put("jboss.naming.client.ejb.context","true");
        p.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
        p.put(Context.PROVIDER_URL, "remote://localhost:" + this.port);
        p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
        p.put(Context.SECURITY_PRINCIPAL, this.user);
        p.put(Context.SECURITY_CREDENTIALS, this.password);
        LOGGER.info("PARAMS : " + p);

        Properties props = new Properties();
        // props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
        props.putAll(p);
        InitialContext context = new InitialContext(props);

        try {
//              final String rcal = "IMSBusinessComponents/ejbs/AccountAgentBean!" + AccountAgent.class.getName();
//              final AccountAgent remote = (AccountAgent) context.lookup(rcal);
//              final Account result = remote.findAccountByKey(1L);

           final String rcal = "ejb:apptwo/ejb//AppTwoBean!" + AppTwo.class.getName();
           final AppTwo remote = (AppTwo) context.lookup(rcal);
           LOGGER.info("Calling EJB...");
           final String result = remote.invoke("TEST");
           LOGGER.info("The EJB call returns : " + result);
        } finally {
            context.close();
        }
    }

    /**
     * Invoke with EJB Client API.
     */
    private void invokeApp1WithEJBClientAPI() throws NamingException {
      Properties p = new Properties();
      // p.put("endpoint.name", "nonClustered-client-endpoint");
      p.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
      // p.put("deployment.node.selector", SimpleLoadFactorNodeSelector.class.getName());
      p.put("remote.connections", "appOneA");
      p.put("remote.connection.appOneA.port", this.port);
      p.put("remote.connection.appOneA.host", "localhost");
      p.put("remote.connection.appOneA.username", this.user);
      p.put("remote.connection.appOneA.password", this.password);
      p.put("remote.connection.appOneA.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
      p.put("org.jboss.ejb.client.scoped.context", "true");

//      EJBClientConfiguration cc = new PropertiesBasedEJBClientConfiguration(p);
//      ContextSelector<EJBClientContext> selector = new ConfigBasedEJBClientContextSelector(cc);
//      EJBClientContext.setSelector(selector);

      p.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
      LOGGER.info("PARAMS : " + p);
      InitialContext context = new InitialContext(p);
//      Context workaround = (Context)context.lookup("ejb:");

      try {
//            final String rcal = "ejb:IMSBusinessComponents/ejbs/AccountAgentBean!" + AccountAgent.class.getName();
//            final AccountAgent remote = (AccountAgent) context.lookup(rcal);
//            final Account result = remote.findAccountByKey(1L);

        final String rcal = "ejb:appone/ejb//AppOneBean!" + AppOne.class.getName();
        final AppOne remote = (AppOne) context.lookup(rcal);
        LOGGER.info("Calling EJB...");
        final String result = remote.invoke("TEST");
        LOGGER.info("The EJB call returns : " + result);
      } finally {
//        workaround.close();
          context.close();
      }
  }

    private void invokeApp2WithEJBClientAPI() throws NamingException {
      Properties p = new Properties();
      // p.put("endpoint.name", "nonClustered-client-endpoint");
      p.put("remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "false");
      // p.put("deployment.node.selector", SimpleLoadFactorNodeSelector.class.getName());
      p.put("remote.connections", "appTwoA");
      p.put("remote.connection.appTwoA.port", this.port);
      p.put("remote.connection.appTwoA.host", "localhost");
      p.put("remote.connection.appTwoA.username", this.user);
      p.put("remote.connection.appTwoA.password", this.password);
      p.put("remote.connection.appTwoA.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false");
      p.put("org.jboss.ejb.client.scoped.context", "true");

//      EJBClientConfiguration cc = new PropertiesBasedEJBClientConfiguration(p);
//      ContextSelector<EJBClientContext> selector = new ConfigBasedEJBClientContextSelector(cc);
//      EJBClientContext.setSelector(selector);

      Properties props = new Properties();
      props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
      props.putAll(p);
      LOGGER.info("PARAMS : " + props);
      InitialContext context = new InitialContext(props);
      Context workaround = (Context)context.lookup("ejb:");

      try {
//            final String rcal = "ejb:IMSBusinessComponents/ejbs/AccountAgentBean!" + AccountAgent.class.getName();
//            final AccountAgent remote = (AccountAgent) context.lookup(rcal);
//            final Account result = remote.findAccountByKey(1L);

        final String rcal = "ejb:apptwo/ejb//AppTwoBean!" + AppTwo.class.getName();
        final AppTwo remote = (AppTwo) context.lookup(rcal);
        LOGGER.info("Calling EJB...");
        final String result = remote.invoke("TEST");
        LOGGER.info("The EJB call returns : " + result);
      } finally {
        workaround.close();
//        context.close();
      }
  }

    /**
     * Main method.
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws NamingException, InterruptedException {
        String user = null, passwd = null;
        String port = null;
        Boolean debug = null;

         user = "quickuser1";
         passwd = "quick123+";
//        user = "quickstartUser";
//        passwd = "quickstartPwd1!";
        port = "5147";
        if (args.length > 0 && "-D".equals(args[0])) {
            debug = Boolean.TRUE;
        }
//        debug = Boolean.TRUE;
        
              
//        Map<String, Object> env = new Hashtable<String, Object>();
//        if (System.getProperty("username") != null) {
//            env.put(BusinessDelegatorFactory.USERNAME, System.getProperty("username"));
//        } else {
//            env.put(BusinessDelegatorFactory.USERNAME, "jba");
//        }
//
//        if (System.getProperty("password") != null) {
//            env.put(BusinessDelegatorFactory.PASSWORD, (System.getProperty("password")).toCharArray());
//        } else {
//            env.put(BusinessDelegatorFactory.PASSWORD, "jba".toCharArray());
//        }
//        env.put(BusinessDelegatorFactory.IMSPRINCIPAL_TYPE, IMSPrincipal.SELFCAREUSER);
//        env.put(BusinessDelegatorFactory.IP_ADDRESS, "127.0.0.1");
//
//        if (System.getProperty("PROVIDER_HOST") != null) {
//            env.put(BusinessDelegatorFactory.PROVIDER_HOST, System.getProperty("PROVIDER_HOST"));
//        } else {
//            env.put(BusinessDelegatorFactory.PROVIDER_HOST, "localhost");
//        }
//        if (System.getProperty("JEE_VENDOR") != null) {
//            env.put(BusinessDelegatorFactory.JEE_VENDOR, System.getProperty("JEE_VENDOR"));
//        } else {
//            env.put(BusinessDelegatorFactory.JEE_VENDOR, "jboss");
//        }
//
//        BusinessDelegatorFactory bdf = new BusinessDelegatorFactory();
//        try {
//            bdf.login(env);
//            AccountAgent agent = bdf.getBusinessDelegator(AccountAgent.class);
//            System.out.println(agent.findAccountByKey(new Long(1)));
//            bdf.logout();
//        } catch (LoginException ex) {
//            ex.printStackTrace();
////            Logger.getLogger(Case00833851SimpleJBossApiClient.class.getName()).log(Level.SEVERE, null, ex);
//        }
////        
//
//        Case00833851SimpleJBossApiClient client1 = new Case00833851SimpleJBossApiClient(user, passwd, port, debug);
//        client1.invokeUsingRemoteNaming();
//        client1.invokeUsingRemoteNaming();
//        client1.invokeUsingRemoteNaming();
//        client1.invokeUsingRemoteNaming();
//        
//        client1 = new Case00833851SimpleJBossApiClient("cy", "cy", port, debug);
//        client1.invokeUsingRemoteNaming();
//        client1.invokeUsingRemoteNaming();
//        client1.invokeUsingRemoteNaming();
//        client1.invokeUsingRemoteNaming();

        TooManyChannelsOpenedClient client2 = new TooManyChannelsOpenedClient("quickuser1", "quick123+", "4447", debug);
//        client2.invokeUsingRemoteNaming();
        for (int i = 0; i < 100; i++) {
          client2.invokeApp1WithEJBClientAPI();
        }
        Thread.sleep(1000);
//        client2.invokeApp2WithEJBClientAPI();
//        Thread.sleep(1000);
        
        client2 = new TooManyChannelsOpenedClient("quickuser2", "quick+123", "4447", debug);
        client2.invokeApp2WithEJBClientAPI();
        client2.invokeApp1WithEJBClientAPI();
    }
}