/**
   * 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
      */
    }
  }
  /**
   * Retrieve all GridMaster nodes currently in the database.
   *
   * @return Collection of GridNode(s) which are GridMaster nodes.
   */
  private Collection getGridMasterNodes() throws Throwable {
    DataFilterImpl filter = new DataFilterImpl();
    filter.addSingleFilter(
        null, GridNode.STATE, filter.getEqualOperator(), new Short(GridNode.STATE_GM), false);

    return ServiceLookupHelper.getGridNodeManager().findGridNodesByFilter(filter);
  }
 /**
  * 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");
   }
 }
 /**
  * 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);
   }
 }
  /**
   * 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");
   }
 }
 /**
  * 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);
   }
 }
  /**
   * Create a GridMaster node.
   *
   * @param nodeID the GridNodeID for the GridMaster.
   * @param desc The GridNode Name for the GridMaster.
   */
  private void createGridMasterNode(String nodeID, String desc) throws Throwable {
    // create
    GridNode gmNode = new GridNode();
    gmNode.setID(nodeID);
    gmNode.setName(desc);
    gmNode.setState(GridNode.STATE_GM);
    gmNode.setCategory(DelegateHelper.getProperties().getGmCategory());

    Long uid = ServiceLookupHelper.getGridNodeManager().createGridNode(gmNode);

    // add uid to gms
    _ctx.getConnectionSetupResult().getAvailableGridMastersUIDs().add(uid);
  }
  /**
   * Retrieve the encryption Certificate used by a particular channel in a File.
   *
   * @param channel The Channel.
   * @return The certificate file.
   */
  static File getCertFile(ChannelInfo channel) throws Throwable {
    ICertificateManagerObj certMgr = ServiceLookupHelper.getCertificateManager();

    Certificate cert =
        certMgr.findCertificateByUID(channel.getSecurityProfile().getEncryptionCertificateID());
    String filename =
        FileUtil.getFile(IPathConfig.PATH_TEMP, "").getAbsolutePath() + "/myCert.cert";

    GridCertUtilities.writeX509Certificate(
        filename,
        GridCertUtilities.loadX509Certificate(GridCertUtilities.decode(cert.getCertificate())));

    return new File(filename);
  }
  /**
   * 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]);
  }
  /**
   * Delete Channels with the specified refId.
   *
   * @param refId The ReferenceId of the ChannelInfo and related profiles.
   */
  private void deleteChannel(String refId) throws Throwable {
    DataFilterImpl filter = new DataFilterImpl();
    filter.addSingleFilter(null, ChannelInfo.REF_ID, filter.getEqualOperator(), refId, false);
    // filter.addSingleFilter(filter.getAndConnector(), ChannelInfo.IS_MASTER,
    //  filter.getEqualOperator(), Boolean.TRUE, false);

    /** @todo to verify whether can just delete like that or don't delete */
    IChannelManagerObj mgr = ServiceLookupHelper.getChannelManager();
    Collection results = mgr.getChannelInfo(filter);
    for (Iterator i = results.iterator(); i.hasNext(); ) {
      ChannelInfo channel = (ChannelInfo) i.next();
      mgr.deleteChannelInfo((Long) channel.getKey());
      mgr.deleteCommInfo((Long) channel.getTptCommInfo().getKey());
      mgr.deletePackigingInfo((Long) channel.getPackagingProfile().getKey());
      mgr.deleteSecurityInfo((Long) channel.getSecurityProfile().getKey());
    }
  }
  /**
   * 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;
  }
  /** Remove the existing setup: GridMaster nodes, Channels, and JmsRouters. */
  private void clearExistingSetup() throws Throwable {
    // retrieve GridMaster nodes
    Collection gmNodes = getGridMasterNodes();

    IGridNodeManagerObj mgr = ServiceLookupHelper.getGridNodeManager();
    for (Iterator i = gmNodes.iterator(); i.hasNext(); ) {
      GridNode node = (GridNode) i.next();

      // delete GridMaster channel for each GridMaster node
      deleteChannel(node.getID());
      // delete each GridMaster node
      mgr.deleteGridNode((Long) node.getKey());
    }

    // delete existing JmsRouters
    deleteJmsRouters();

    // delete master channel
    // deleteChannel(_ctx.getGridNodeID().toString());

    _ctx.getConnectionSetupResult().getGridMasterTopics().clear();
    _ctx.getConnectionSetupResult().getAvailableGridMastersUIDs().clear();
    _ctx.getConnectionSetupResult().getAvailableRouterUIDs().clear();
  }