/***********************************************************
Copyright (C) 2021 VeriSign, Inc.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library 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
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

http://www.verisign.com/nds/naming/namestore/techdocs.html
***********************************************************/
package com.verisign.epp.interfaces.secureauthinfo.v1_0;

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.verisign.epp.codec.domain.EPPDomainInfoResp;
import com.verisign.epp.codec.domain.EPPDomainStatus;
import com.verisign.epp.codec.gen.EPPAuthInfo;
import com.verisign.epp.codec.gen.EPPResponse;
import com.verisign.epp.codec.gen.EPPResult;
import com.verisign.epp.interfaces.EPPApplicationSingle;
import com.verisign.epp.interfaces.EPPCommandException;
import com.verisign.epp.interfaces.EPPDomain;
import com.verisign.epp.interfaces.EPPSession;
import com.verisign.epp.util.Environment;
import com.verisign.epp.util.TestThread;
import com.verisign.epp.util.secureauthinfo.EPPAuthInfoFactory;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Is a unit test of the com.verisign.epp.codec.domain package with implementing
 * the Secure Authorization Information for Transfer Best Common Practice (BCP).
 */
public class EPPSecureAuthInfoTst {
  /**
   * Handle to the Singleton EPP Application instance
   * (<code>EPPApplicationSingle</code>)
   */
  private static EPPApplicationSingle app = EPPApplicationSingle.getInstance();

  /**
   * Name of configuration file to use for test (default = epp.config).
   */
  private static String configFileName = "epp.config";

  /**
   * Logging category
   */
  private static Logger cat = LoggerFactory.getLogger(EPPSecureAuthInfoTst.class);


  /**
   * EPP Domain associated with test
   */
  private EPPDomain domain = null;

  /**
   * EPP Session associated with test
   */
  private EPPSession session = null;

  /**
   * Current test iteration
   */
  private int iteration = 0;

  /**
   * Random instance for the generation of unique objects (hosts, IP addresses,
   * etc.).
   */
  private Random rd = new Random(System.currentTimeMillis());

  /**
   * JUNIT test method to implement the
   * <code>EPPSecureAuthInfoTst TestCase</code>. Each sub-test will be invoked
   * in order to satisfy testing the EPPDomain interface.
   */
  @Test
  public void testDomain() {
    int numIterations = 1;

    String iterationsStr = System.getProperty("iterations");

    if (iterationsStr != null) {
      numIterations = Integer.parseInt(iterationsStr);
    }

    for (iteration = 0; (numIterations == 0) || (iteration < numIterations); iteration++) {
      printStart("Test Suite");

      domainSuccessfulTransfer();

      domainUnsuccessfulTransfer();

      printEnd("Test Suite");
    }
  }

  /**
   * Test the entire flow of a successful transfer from create until transfer
   * request. The test only uses a single session, so it will only work against
   * the Stub Server. The steps include: <br>
   * <ol>
   * <li>Create the domain without authorization information.
   * <li>Update the domain with generated secure random authorization
   * information.
   * <li>Info the domain with generated secure random authorization information
   * to validate it prior to a transfer request.
   * <li>Transfer request with generated secure random authorization
   * information, which should result in an immediate transfer.
   * </ol>
   */
  private void domainSuccessfulTransfer() {
    printStart("domainSuccessfulTransfer");

    EPPResponse response;

    try {
      String theDomainName = this.makeDomainName();
      String theAuthInfo = EPPAuthInfoFactory.createAuthInfoPasswordStr(20);

      // Create the domain without authorization information
      System.out.println("\n----------------------------------------------------------------");

      System.out.println("domainSuccessfulTransfer: Create the domain without authorization information");

      domain.setTransId("ABC-12345");

      domain.addDomainName(theDomainName);

      domain.setAuthString("");

      response = domain.sendCreate();

      // -- Output all of the response attributes
      System.out.println("domainSuccessfulTransfer: Create Response = [" + response + "]\n\n");

      // Update the domain with generated secure random authorization
      // information
      System.out.println("\n----------------------------------------------------------------");

      System.out.println(
            "domainSuccessfulTransfer: Update the domain with generated secure random authorization information");

      domain.setTransId("ABC-12345-XYZ");

      domain.addDomainName(theDomainName);

      domain.setAuthString(theAuthInfo);

      domain.setUpdateAttrib(EPPDomain.STATUS, new EPPDomainStatus(EPPDomain.STATUS_CLIENT_TRANSFER_PROHIBITED),
            EPPDomain.REMOVE);

      response = domain.sendUpdate();

      System.out.println("domainSuccessfulTransfer: Update Response = [" + response + "]\n\n");

      // Info the domain with generated secure random authorization
      // information to validate it prior to a transfer request
      System.out.println("\n----------------------------------------------------------------");

      System.out.println(
            "domainSuccessfulTransfer: Info the domain with generated secure random authorization information to validate it prior to a transfer request");

      domain.setTransId("ABC-12345-XYZ");

      domain.addDomainName(theDomainName);

      domain.setAuthString(theAuthInfo);

      response = domain.sendInfo();

      System.out.println("domainSuccessfulTransfer: Info Response = [" + response + "]\n\n");

      // Ensure that the auth info was not returned in the info response
      if (((EPPDomainInfoResp) response).hasAuthInfo()) {
        Assert.fail("domainSuccessfulTransfer: Info response must not return the authorization information value");
      }

      // Transfer request with generated secure random authorization
      // information, which should result in an immediate transfer
      System.out.println("\n----------------------------------------------------------------");

      System.out.println(
            "domainSuccessfulTransfer: Transfer request with generated secure random authorization information, which should result in an immediate transfer");

      domain.setTransId("ABC-12345");

      domain.addDomainName(theDomainName);

      domain.setAuthString(theAuthInfo);

      domain.setTransferOpCode(EPPDomain.TRANSFER_REQUEST);

      response = domain.sendTransfer();

      System.out.println("domainSuccessfulTransfer: Transfer Response = [" + response + "]\n\n");

      // Not immediate transfer?
      if (!response.hasResultCode(EPPResult.SUCCESS)) {
        Assert.fail("domainSuccessfulTransfer: Transfer request did not result in 1000 result");
      }

    }
    catch (EPPCommandException e) {
      handleException(e);
    }

    printEnd("domainSuccessfulTransfer");
  }

  /**
   * Test the entire flow of an unsuccessful transfer from create clearing the
   * authorization information. An unsuccessful transfer is one that resulted
   * in expiry of the Time-To-Live (TTL). The steps include: <br>
   * <ol>
   * <li>Create the domain without authorization information.
   * <li>Update the domain with generated secure random authorization
   * information.
   * <li>Update the domain to clear the authorization information with null
   * authorization information based on expiry of the Time-To-Live (TTL).
   * <li>Update the domain to clear the authorization information with empty
   * authorization information based on expiry of the Time-To-Live (TTL).
   * </ol>
   */
  private void domainUnsuccessfulTransfer() {
    printStart("domainUnsuccessfulTransfer");

    EPPResponse response;

    try {
      String theDomainName = this.makeDomainName();
      String theAuthInfo = EPPAuthInfoFactory.createAuthInfoPasswordStr(20);

      // Create the domain without authorization information
      System.out.println("\n----------------------------------------------------------------");

      System.out.println("domainUnsuccessfulTransfer: Create the domain without authorization information");

      domain.setTransId("ABC-12345");

      domain.addDomainName(theDomainName);

      domain.setAuthString("");

      response = domain.sendCreate();

      // -- Output all of the response attributes
      System.out.println("domainUnsuccessfulTransfer: Create Response = [" + response + "]\n\n");

      // Update the domain with generated secure random authorization
      // information
      System.out.println("\n----------------------------------------------------------------");

      System.out.println(
            "domainUnsuccessfulTransfer: Update the domain with generated secure random authorization information");

      domain.setTransId("ABC-12345-XYZ");

      domain.addDomainName(theDomainName);

      domain.setAuthString(theAuthInfo);

      domain.setUpdateAttrib(EPPDomain.STATUS, new EPPDomainStatus(EPPDomain.STATUS_CLIENT_TRANSFER_PROHIBITED),
            EPPDomain.REMOVE);

      response = domain.sendUpdate();

      System.out.println("domainUnsuccessfulTransfer: Update Response (Set AuthInfo) = [" + response + "]\n\n");

      // Update the domain to clear the authorization information with null
      // authorization information based on expiry of the Time-To-Live (TTL)
      System.out.println("\n----------------------------------------------------------------");

      System.out.println("domainUnsuccessfulTransfer: Update the domain to clear the authorization information"
            + " with null authorization information based on expiry \n" + "  * of the Time-To-Live (TTL)");

      domain.setTransId("ABC-12345-XYZ");

      domain.addDomainName(theDomainName);

      EPPAuthInfo theNullAuthInfo = new EPPAuthInfo();
      theNullAuthInfo.removePassword();
      domain.setAuthInfo(theNullAuthInfo);

      domain.setUpdateAttrib(EPPDomain.STATUS, new EPPDomainStatus(EPPDomain.STATUS_CLIENT_TRANSFER_PROHIBITED),
            EPPDomain.ADD);

      response = domain.sendUpdate();

      System.out.println("domainUnsuccessfulTransfer: Update Response (Unset AuthInfo with Null AuthInfo) = ["
            + response + "]\n\n");

      // Update the domain to clear the authorization information with empty
      // authorization information based on expiry of the Time-To-Live (TTL)
      System.out.println("\n----------------------------------------------------------------");

      System.out.println("domainUnsuccessfulTransfer: Update the domain to clear the authorization information"
            + " with empty authorization information based on expiry \n" + "   * of the Time-To-Live (TTL)");

      domain.setTransId("ABC-12345-XYZ");

      domain.addDomainName(theDomainName);

      domain.setAuthInfo(new EPPAuthInfo(""));

      domain.setUpdateAttrib(EPPDomain.STATUS, new EPPDomainStatus(EPPDomain.STATUS_CLIENT_TRANSFER_PROHIBITED),
            EPPDomain.ADD);

      response = domain.sendUpdate();

      System.out.println("domainUnsuccessfulTransfer: Update Response (Unset AuthInfo with Empty AuthInfo) = ["
            + response + "]\n\n");


    }
    catch (EPPCommandException e) {
      handleException(e);
    }

    printEnd("domainUnsuccessfulTransfer");
  }

  /**
   * Unit test of <code>EPPSession.initSession</code>. The session attribute is
   * initialized with the attributes defined in the EPP sample files.
   */
  private void initSession() {
    printStart("initSession");

    // Set attributes for initSession
    session.setTransId("ABC-12345-XYZ");

    session.setVersion("1.0");

    session.setLang("en");

    // Initialize the session
    try {
      session.initSession();
    }

    catch (EPPCommandException e) {
      EPPResponse response = session.getResponse();

      // Is a server specified error?
      if ((response != null) && (!response.isSuccess())) {
        Assert.fail("Server Error : " + response);
      }
      else {
        e.printStackTrace();

        Assert.fail("initSession Error : " + e);
      }
    }

    printEnd("initSession");
  }

  // End EPPSecureAuthInfoTst.initSession()

  /**
   * Unit test of <code>EPPSession.endSession</code>. The session with the EPP
   * Server will be terminated.
   */
  private void endSession() {
    printStart("endSession");

    session.setTransId("ABC-12345-XYZ");

    // End the session
    try {
      session.endSession();
    }

    catch (EPPCommandException e) {
      EPPResponse response = session.getResponse();

      // Is a server specified error?
      if ((response != null) && (!response.isSuccess())) {
        Assert.fail("Server Error : " + response);
      }

      else // Other error
      {
        e.printStackTrace();

        Assert.fail("initSession Error : " + e);
      }
    }

    printEnd("endSession");
  }

  // End EPPSecureAuthInfoTst.endSession()

  /**
   * JUNIT <code>setUp</code> method, which sets the default client Id to
   * "theRegistrar".
   */
  @Before
  public void setUp() {
    try {
      String theSessionClassName = System.getProperty("EPP.SessionClass");

      if (theSessionClassName != null) {
        try {
          Class theSessionClass = Class.forName(theSessionClassName);

          if (!EPPSession.class.isAssignableFrom((theSessionClass))) {
            Assert.fail(theSessionClassName + " is not a subclass of EPPSession");
          }

          session = (EPPSession) theSessionClass.getDeclaredConstructor().newInstance();
        }
        catch (Exception ex) {
          Assert.fail("Exception instantiating EPP.SessionClass value " + theSessionClassName + ": " + ex);
        }
      }
      else {
        session = new EPPSession();
      }

      session.setClientID(Environment.getProperty("EPP.Test.clientId", "ClientX"));
      session.setPassword(Environment.getProperty("EPP.Test.password", "foo-BAR2"));
    }

    catch (Exception e) {
      e.printStackTrace();

      Assert.fail("Error initializing the session: " + e);
    }

    initSession();

    // System.out.println("out init");
    domain = new EPPDomain(session);
  }


  /**
   * JUNIT <code>tearDown</code>, which currently does nothing.
   */
  @After
  public void tearDown() {
    endSession();
  }


  /**
   * JUNIT <code>suite</code> static method, which returns the tests associated
   * with <code>EPPSecureAuthInfoTst</code>.
   */
  @BeforeClass
  public static void beforeClass() {
    String theConfigFileName = System.getProperty("EPP.ConfigFile");
    if (theConfigFileName != null)
      configFileName = theConfigFileName;

    try {
      app.initialize(configFileName);
    }
    catch (EPPCommandException e) {
      e.printStackTrace();

      Assert.fail("Error initializing the EPP Application: " + e);
    }
  }


  /**
   * Handle an <code>EPPCommandException</code>, which can be either a server
   * generated error or a general exception. If the exception was caused by a
   * server error, "Server Error :&lt;Response XML&gt;" will be specified. If
   * the exception was caused by a general algorithm error, "General Error
   * :&lt;Exception Description&gt;" will be specified.
   *
   * @param aException
   *           Exception thrown during test
   */
  public void handleException(Exception aException) {
    EPPResponse theResponse = null;
    if (aException instanceof EPPCommandException) {
      theResponse = ((EPPCommandException) aException).getResponse();
    }

    aException.printStackTrace();

    // Is a server specified error?
    if ((theResponse != null) && (!theResponse.isSuccess())) {
      Assert.fail("Server Error : " + theResponse);
    }

    else {
      Assert.fail("General Error : " + aException);
    }
  }


  /**
   * This method tries to generate a unique String as Domain Name and Name
   * Server
   *
   * @return A unique domain name
   */
  public String makeDomainName() {
    long tm = System.currentTimeMillis();

    return new String("EPPSecureAuthInfoTst" + Thread.currentThread()
          + String.valueOf(tm + rd.nextInt(12)).substring(10) + ".com");
  }

  /**
   * Makes a unique IP address based off of the current time.
   *
   * @return Unique IP address <code>String</code>
   */
  public String makeIP() {
    long tm = System.currentTimeMillis();

    return new String(
          String.valueOf(tm + rd.nextInt(50)).substring(10) + "." + String.valueOf(tm + rd.nextInt(50)).substring(10)
                + "." + String.valueOf(tm + rd.nextInt(50)).substring(10) + "."
                + String.valueOf(tm + rd.nextInt(50)).substring(10));
  }

  /**
   * Makes a unique host name for a domain using the current time.
   *
   * @param aDomainName
   *           Domain name
   *
   * @return Unique host name <code>String</code>
   */
  public String makeHostName(String aDomainName) {
    long tm = System.currentTimeMillis();

    return new String(String.valueOf(tm + rd.nextInt(10)).substring(10) + "." + aDomainName);
  }

  /**
   * Makes a unique contact name using the current time.
   *
   * @return Unique contact name <code>String</code>
   */
  public String makeContactName() {
    long tm = System.currentTimeMillis();

    return new String("SAI" + String.valueOf(tm + rd.nextInt(5)).substring(7));
  }

  /**
   * Print the start of a test with the <code>Thread</code> name if the current
   * thread is a <code>TestThread</code>.
   *
   * @param aTest
   *           name for the test
   */
  private void printStart(String aTest) {
    if (Thread.currentThread() instanceof TestThread) {
      System.out.print(Thread.currentThread().getName() + ", iteration " + iteration + ": ");

      cat.info(Thread.currentThread().getName() + ", iteration " + iteration + ": " + aTest + " Start");
    }

    System.out.println("Start of " + aTest);

    System.out.println("****************************************************************\n");
  }


  /**
   * Print the end of a test with the <code>Thread</code> name if the current
   * thread is a <code>TestThread</code>.
   *
   * @param aTest
   *           name for the test
   */
  private void printEnd(String aTest) {
    System.out.println("****************************************************************");

    if (Thread.currentThread() instanceof TestThread) {
      System.out.print(Thread.currentThread().getName() + ", iteration " + iteration + ": ");

      cat.info(Thread.currentThread().getName() + ", iteration " + iteration + ": " + aTest + " End");
    }

    System.out.println("End of " + aTest);

    System.out.println("\n");
  }


  /**
   * Print message
   *
   * @param aMsg
   *           message to print
   */
  private void printMsg(String aMsg) {
    if (Thread.currentThread() instanceof TestThread) {
      System.out.println(Thread.currentThread().getName() + ", iteration " + iteration + ": " + aMsg);

      cat.info(Thread.currentThread().getName() + ", iteration " + iteration + ": " + aMsg);
    }

    else {
      System.out.println(aMsg);

      cat.info(aMsg);
    }
  }


  /**
   * Print error message
   *
   * @param aMsg
   *           errpr message to print
   */
  private void printError(String aMsg) {
    if (Thread.currentThread() instanceof TestThread) {
      System.err.println(Thread.currentThread().getName() + ", iteration " + iteration + ": " + aMsg);

      cat.error(Thread.currentThread().getName() + ", iteration " + iteration + ": " + aMsg);
    }

    else {
      System.err.println(aMsg);

      cat.error(aMsg);
    }
  }

}

// End class EPPSecureAuthInfoTst
