public void execute() throws Throwable {
    Logger.debug("[ConnectionSetupRequestDelegate.execute] Enter");

    registerDelegate();

    preCreateMasterChannel();

    connectToServicingRouter();
    sendSetupInfo();

    // sleep
    if (!_resultsReturned) _helper.sleep(_ctx.getResponseTimeout());

    // make sure must wait until receiveAck() finish processing.
    synchronized (_lock) {
      Logger.debug("[ConnectionSetupRequestDelegate.execute] Examine result success=" + _success);

      // disconnect from temp connection
      DelegateHelper.disconnect((CommInfo) _ctx.getSecureCommInfo());

      storeSetupData();

      // check results
      if (!_success) throw new ConnectionSetupException(_failureReason);
    }
  }
 /**
  * Disconnect from the specified Jms router.
  *
  * @param commInfo the CommInfo indicating the Jms router to disconnect from.
  */
 static void disconnect(CommInfo commInfo) {
   try {
     if (getProperties().getIsTest()) {
       Logger.log("[DelegateHelper.disconnect] Testing only. No real disconnect initiated");
     } else {
       // disconnect, should not throw exception
       ServiceLookupHelper.getChannelManager().disconnect(commInfo);
     }
   } catch (Throwable t) {
     Logger.warn("[DelegateHelper.disconnect] Error disconnecting.. ", t);
   }
 }
 /** Wake up the sleeping thread, if any. */
 synchronized void wakeUp() {
   if (_sleepingThread != null && _sleepingThread.isAlive()) {
     try {
       Logger.debug("[DelegateHelper.wakeUp] Waking up...");
       notify();
     } catch (Exception ex) {
       Logger.debug("[DelegateHelper.wakeUp] ", ex);
     } finally {
       _sleepingThread = null;
     }
   }
   _isNotified = true;
 }
  private void storeSetupData() {
    try {
      Logger.debug("[ConnectionSetupRequestDelegate][storeSetupData][In storeSetupData() Begin]");
      if (_success) {
        if (_receivedFiles[0] != null)
          Logger.debug(
              "[ConnectionSetupRequestDelegate][storeSetupData][Received File]"
                  + _receivedFiles[0].getAbsolutePath());
        else
          Logger.debug("[ConnectionSetupRequestDelegate][storeSetupData][Received File is Null]");

        Long masterCert = createMasterCertificate(_receivedFiles[0]);

        updateMasterChannel(_receivedData[3], _receivedData[4], _receivedData[5], masterCert);

        clearExistingSetup();

        createGridMasterNode(_receivedData[6], _receivedData[8]);
        _ctx.getConnectionSetupResult().addGridMasterTopic(_receivedData[6], _receivedData[7]);
        if (_receivedData[9] != null) {
          createGridMasterNode(_receivedData[9], _receivedData[11]);
          _ctx.getConnectionSetupResult().addGridMasterTopic(_receivedData[9], _receivedData[10]);
        }
        if (_receivedData[12] != null) {
          createGridMasterNode(_receivedData[12], _receivedData[14]);
          _ctx.getConnectionSetupResult().addGridMasterTopic(_receivedData[12], _receivedData[13]);
        }
        createJmsRouter(_receivedData[15], _receivedData[16]);
        if (_receivedData[17] != null) createJmsRouter(_receivedData[17], _receivedData[18]);
        if (_receivedData[19] != null) createJmsRouter(_receivedData[19], _receivedData[20]);

        createGridMasterChannel(_receivedData[6], _receivedData[7], _receivedData[16], masterCert);

        _ctx.getConnectionSetupResult().setNetworkRouterTopic(_receivedData[3]);
        _ctx.getConnectionSetupResult().setNetworkRouterUser(_receivedData[4]);
        _ctx.getConnectionSetupResult().setNetworkRouterPassword(_receivedData[5]);
        generateLocalRouterPassword(_ctx.getGridNodeID());
        generateLocalRouterUser(_ctx.getGridNodeID());
        generateLocalRouterTopic(_ctx.getGridNodeID());

        // update SendChannel with new sign cert
        updateSendChannelSignCert(masterCert);
        _ctx.setSignCert(masterCert);
        Logger.debug("[ConnectionSetupRequestDelegate][storeSetupData][End storeSetupData()]");
      }
    } catch (Throwable t) {
      t.printStackTrace();
      _success = false;
      _failureReason = t.getMessage();
    }
  }
 /**
  * Let the current thread sleep for the specified number of seconds, or until a WakeUp is called.
  *
  * @param timeoutSeconds The number of seconds to sleep.
  */
 synchronized void sleep(long timeoutSeconds) {
   if (!_isNotified) {
     try {
       long duration = timeoutSeconds * 1000L; // to give discount??
       _sleepingThread = Thread.currentThread();
       Logger.debug(
           "[DelegateHelper.sleep] Sleeping for "
               + timeoutSeconds
               + " seconds... Please remember to wake me up.");
       wait(duration);
     } catch (Throwable ex) {
       Logger.debug("[DelegateHelper.sleep] ", ex);
     }
   }
 }
  /**
   * Send a message.
   *
   * @param eventID the Event ID of the message
   * @param transID The Trans ID for the message instance.
   * @param dataPayload The data payload of the message
   * @param filePayload The file payload of the message.
   * @param sendChannel The channel to send via.
   */
  void send(
      String eventID,
      String transID,
      String[] dataPayload,
      File[] filePayload,
      ChannelInfo sendChannel)
      throws Throwable {
    if (getProperties().getIsTest()) {
      Logger.log("[DelegateHelper.send] Testing only. No real sending initiated");
    } else {
      String fileID = null;
      if (filePayload != null) fileID = "connection_E" + eventID + "_T" + transID;

      // 031001NSL
      ChannelSendHeader header = new ChannelSendHeader(eventID, transID, null, fileID);
      header.setGridnodeHeaderInfo(
          ConnectionContext.getInstance().getMyNodeID(), sendChannel.getReferenceId(), null);

      // send via sendChannel
      ServiceLookupHelper.getChannelManager()
          .send(sendChannel, dataPayload, filePayload, header.getHeaderArray());
      /*031001NSL
      new String[] {eventID, transID, null, fileID,
      ConnectionContext.getInstance().getMyNodeID(), //sender
      sendChannel.getReferenceId()});  //recipient
      */
    }
  }
  /**
   * Invoked when acknowledgement is received for the setup request message.
   *
   * @param dataPayload The data payload should contain, in order:
   *     <p>
   *     <PRE>
   * 0) <ignore>
   * 1) Success/failure status, Boolean
   * 2) Error message from GMPrime, if not successful.
   * JMS Network Authentication Parameters for this GridTalk,
   *    3) JMS Network Topic
   *    4) JMS Network User
   *    6) JMS Network Password
   * GridMaster node 1,
   *    6) GridMaster Node Id
   *    7) GridMaster Topic
   *    8) GridMaster Description
   * GridMaster node 2 (optional),
   *    9) GridMaster Node Id
   *    10) GridMaster Topic
   *    11) GridMaster Description
   * GridMaster node 3 (optional),
   *    12) GridMaster Node Id
   *    13) GridMaster Topic
   *    14) GridMaster Description
   * JMS Router 1,
   *    15) JMS Router IP
   *    16) JMS Router Description
   * JMS Router 2 (optional),
   *    17) JMS Router IP
   *    18) JMS Router Description
   * JMS Router 3 (optional),
   *    19) JMS Router IP
   *    20) JMS Router Description</PRE>
   *
   * @param filePayload The file payload should contain, if status indicates success, the GridTalk's
   *     Certificate signed by GmPrime.
   */
  public void receiveAck(String[] dataPayload, File[] filePayload) throws Throwable {
    synchronized (_lock) {
      _resultsReturned = true;

      try {
        // collate the results
        Boolean status = Boolean.valueOf(dataPayload[1]);
        _success = status.booleanValue();
        _failureReason = (_success ? null : dataPayload[2]);

        Logger.debug(
            "[ConnectionSetupRequestDelegate.receiveAck] Status="
                + status
                + " Failure Reason="
                + _failureReason);

        _receivedData = dataPayload;
        _receivedFiles = filePayload;
      } catch (Throwable t) {
        _success = false;
        _failureReason = t.getMessage();
        throw t;
      } finally {
        // wake up the sleeping thread
        _helper.wakeUp();
      }
    }
  }
 /**
  * Update the CommInfo to the database.
  *
  * @param commInfo The CommInfo to update.
  */
 static void updateCommInfo(CommInfo commInfo) throws Throwable {
   try {
     ServiceLookupHelper.getChannelManager().updateCommInfo(commInfo);
   } catch (Throwable t) {
     Logger.warn("[DelegateHelper.updateCommInfo] Error ", t);
     throw new Exception("Unable to update CommInfo");
   }
 }
 /** Loads the Connection Properties. */
 private static void loadProperties() {
   try {
     _props = ConnectionProperties.load();
   } catch (Throwable t) {
     Logger.err("[DelegateHelper.loadProperties] Error ", t);
     _props = ConnectionProperties.getDefaultProperties();
   }
 }
 /**
  * Connect to the specified Jms router.
  *
  * @param commInfo The CommInfo indicating the Jms router to connect to.
  */
 static void connectOnly(CommInfo commInfo, boolean local) throws Throwable {
   if (getProperties().getIsTest()) {
     Logger.log("[DelegateHelper.connect] Testing only. No real connect initiated");
   } else {
     // connectAndListen
     ServiceLookupHelper.getChannelManager()
         .connect(commInfo, local ? _localConnectHeader : _networkConnectHeader);
   }
 }
 /**
  * Broadcast a Notification message.
  *
  * @param notification The Notification message to broadcast.
  */
 static void broadcast(INotification notification) {
   try {
     Notifier.getInstance().broadcast(notification);
   } catch (Exception ex) {
     Logger.error(
         ILogErrorCodes.GT_CONNECTION_DELEGATE_HELPER,
         "[DelegateHelper.broadcastConnectionState] Fail to broadcast. Error: " + ex.getMessage(),
         ex);
   }
 }
  /**
   * Update the ConnectionStatus to the database.
   *
   * @param connStatus The ConnectionStatus to update.
   */
  static ConnectionStatus updateConnectionStatus(ConnectionStatus connStatus) throws Throwable {
    try {
      ServiceLookupHelper.getGridNodeManager().updateConnectionStatus(connStatus);

      return getConnectionStatus(connStatus.getGridNodeID());
    } catch (Throwable t) {
      Logger.warn("[DelegateHelper.updateConnectionStatus] Error ", t);
      throw new Exception("Unable to update Connection Status");
    }
  }
  /**
   * Retrieve the ConnectionStatus for a particular GridNode.
   *
   * @param nodeID The GridNodeID of the GridNode.
   * @return The ConnectionStatus retrieved.
   * @throws Exception No such GridNode.
   */
  static ConnectionStatus getConnectionStatus(String nodeID) throws Throwable {
    ConnectionStatus connStatus = null;

    try {
      connStatus = ServiceLookupHelper.getGridNodeManager().findConnectionStatusByNodeID(nodeID);
    } catch (Throwable t) {
      Logger.warn("[DelegateHelper.getConnectionStatus] Error ", t);
      throw new Exception("Unable to retrieve Connection Status");
    }
    return connStatus;
  }
 /** Update the ChannelInfo and its related profiles to the database. */
 static void updateChannel(ChannelInfo channel) throws Throwable {
   try {
     IChannelManagerObj mgr = ServiceLookupHelper.getChannelManager();
     mgr.updateChannelInfo(channel);
     mgr.updateCommInfo(channel.getTptCommInfo());
     mgr.updatePackagingInfo(channel.getPackagingProfile());
     mgr.updateSecurityInfo(channel.getSecurityProfile());
   } catch (Throwable t) {
     Logger.warn("[DelegateHelper.updateChannel] Error ", t);
     throw new Exception("Unable to update Channel related information");
   }
 }
  /**
   * Create the Master Certificate for the GridTalk.
   *
   * @param certFile The file that contains the Certificate.
   * @return the UID of the created certificate.
   */
  private Long createMasterCertificate(File certFile) throws Throwable {
    Long certUID = null;

    X509Certificate cert = GridCertUtilities.loadX509Certificate(certFile.getAbsolutePath());

    ICertificateManagerObj mgr = ServiceLookupHelper.getCertificateManager();
    // retrieve existing master cert
    Certificate existCert =
        mgr.findCertificateByIDAndName(_ctx.getGridNodeID().intValue(), _ctx.getMasterCertName());

    // revoke
    Logger.log(
        "[ConnectionSetupRequestDelegate.createMasterCertificate] Revoking cert "
            + existCert.getUId());
    mgr.revokeCertificateByUId((Long) existCert.getKey());

    // insert new cert
    mgr.insertCertificate(_ctx.getGridNodeID(), _ctx.getMasterCertName(), cert);

    /*NSL20051115 Somehow this method still returns the revoked cert... so alternative is to
     * use issuername & serialnumber to retrieve -- guarantee to be unique
    Certificate newCert = mgr.findCertificateByIDAndName(
      _ctx.getGridNodeID().intValue(), _ctx.getMasterCertName());
      */
    String issuerName = GridCertUtilities.writeIssuerNameToString(cert.getIssuerX500Principal());
    String serialNum =
        GridCertUtilities.writeByteArrayToString(cert.getSerialNumber().toByteArray());
    Certificate newCert = mgr.findCertificateByIssureAndSerialNum(issuerName, serialNum);

    certUID = (Long) newCert.getKey();
    Logger.log("[ConnectionSetupRequestDelegate.createMasterCertificate] New cert UID=" + certUID);
    // update private key
    mgr.updatePrivateKeyByCertificate(existCert.getPrivateKey(), newCert.getCertificate());

    // update IsMaster
    mgr.updateMasterAndPartnerByUId(certUID, true, false);

    return certUID;
  }
  /**
   * Retrieve the master channel with a particular reference id.
   *
   * @param refID The referenceID.
   * @return The channel retrieved, or <b>null</b> if no such channel found.
   */
  static ChannelInfo retrieveMasterChannel(String refID) throws Throwable {
    Collection results = null;
    try {
      DataFilterImpl filter = new DataFilterImpl();
      filter.addSingleFilter(
          null, ChannelInfo.IS_MASTER, filter.getEqualOperator(), Boolean.TRUE, false);
      filter.addSingleFilter(
          filter.getAndConnector(), ChannelInfo.REF_ID, filter.getEqualOperator(), refID, false);

      results = ServiceLookupHelper.getChannelManager().getChannelInfo(filter);
    } catch (Throwable t) {
      Logger.warn("[ConnectDelegate.retrieveMasterChannel] Error ", t);
      throw new Exception("Error retrieving Master Channel for RefID: " + refID);
    }

    return (results.isEmpty() ? null : (ChannelInfo) results.toArray()[0]);
  }
  /**
   * Invoked when feedback is received for the setup-request message.
   *
   * @param success Whether the setup-request message was sent successfully.
   * @param message A feedback message description.
   */
  public void receiveFeedback(boolean success, String message) throws Throwable {
    Logger.debug(
        "[ConnectionSetupRequestDelegate.receiveFeedback] Success="
            + success
            + ", Message="
            + message);

    if (!success) {
      synchronized (_lock) {
        _resultsReturned = true;
        _success = false;
        _failureReason = message;

        _helper.wakeUp();
      }
    }
  }
  /** Send the setup information to GmPrime. */
  private void sendSetupInfo() throws Throwable {
    String[] dataPayload =
        new String[] {
          DelegateHelper.getProperties().getMsgFormatVersion(),
          _ctx.getGridNodeID().toString(),
          _ctx.getProductKey(),
          _ctx.getCountryCode(),
        };

    File[] filePayload =
        new File[] {
          _ctx.getCertRequest(),
        };

    Logger.debug("[ConnectionSetupRequestDelegate.sendSetupInfo] Sending...");

    _helper.send(_eventID, dataPayload, filePayload);
  }
  /** Create a temporary connection to the setup service router. */
  private void connectToServicingRouter() throws Throwable {
    // construct comminfo to listen to public gt topic
    // this comminfo is only transient
    CommInfo commInfo =
        DelegateHelper.createCommInfo(
            "TMP",
            _ctx.getServicingRouter(),
            DelegateHelper.getProperties().getServicingRouterPort().intValue(),
            _ctx.getSecureTopic(),
            _ctx.getSecureUser(),
            _ctx.getSecurePassword(),
            "CON.SETUP.COMM.TMP",
            "Temporary Communication Profile for Connection Setup");

    // connect
    DelegateHelper.connect(commInfo);
    _ctx.setSecureCommInfo(commInfo);

    Logger.debug("[ConnectionSetupRequestDelegate.connectToServicingRouter] Connected.");
  }