private String getUrl(NhinTargetSystemType target, String serviceName) {
   String url = null;
   try {
     url = ConnectionManagerCache.getEndpontURLFromNhinTarget(target, serviceName);
   } catch (ConnectionManagerException ex) {
     log.warn(
         "exception occurred accessing url from connection manager (getEndpontURLFromNhinTarget)",
         ex);
   }
   if (NullChecker.isNullish(url)) {
     try {
       url = ConnectionManagerCache.getLocalEndpointURLByServiceName(serviceName);
     } catch (ConnectionManagerException ex) {
       log.warn(
           "exception occurred accessing url from connection manager (getLocalEndpointURLByServiceName)",
           ex);
     }
   }
   return url;
 }
  private String getURL() {
    String url = "";

    try {
      url =
          ConnectionManagerCache.getLocalEndpointURLByServiceName(
              NhincConstants.HIEM_SUBSCRIBE_ENTITY_SERVICE_NAME_SECURED);
    } catch (Exception ex) {
      log.error(ex.getMessage(), ex);
    }

    return url;
  }
  protected CMUrlInfos getTargets(NhinTargetCommunitiesType targetCommunities) {
    CMUrlInfos urlInfoList = null;

    // Obtain all the URLs for the targets being sent to
    try {
      urlInfoList =
          ConnectionManagerCache.getEndpontURLFromNhinTargetCommunities(
              targetCommunities, NhincConstants.PATIENT_DISCOVERY_ASYNC_RESP_SERVICE_NAME);
    } catch (ConnectionManagerException ex) {
      log.error(
          "Failed to obtain target URLs for service "
              + NhincConstants.PATIENT_DISCOVERY_ASYNC_RESP_SERVICE_NAME);
      return null;
    }

    return urlInfoList;
  }
  private String getUrl(NhinTargetSystemType target) {
    String url = null;

    if (target != null) {
      try {
        url =
            ConnectionManagerCache.getEndpontURLFromNhinTarget(
                target, NhincConstants.SUBJECT_DISCOVERY_SERVICE_NAME);
      } catch (ConnectionManagerException ex) {
        log.error(
            "Error: Failed to retrieve url for service: "
                + NhincConstants.SUBJECT_DISCOVERY_SERVICE_NAME);
        log.error(ex.getMessage());
      }
    } else {
      log.error("Target system passed into the proxy is null");
    }

    return url;
  }
  private AdapterNotificationConsumerPortType getPort() {
    AdapterNotificationConsumerPortType port =
        adapterNotifyService.getAdapterNotificationConsumerPortSoap();
    String url = null;

    try {
      url =
          ConnectionManagerCache.getLocalEndpointURLByServiceName(
              NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_NAME);
    } catch (ConnectionManagerException ex) {
      log.error(
          "Error: Failed to retrieve url for service: "
              + NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_NAME
              + " for local home community");
      log.error(ex.getMessage());
    }

    log.info("Setting endpoint address to Adapter Hiem Notify Service to " + url);
    ((javax.xml.ws.BindingProvider) port)
        .getRequestContext()
        .put(javax.xml.ws.BindingProvider.ENDPOINT_ADDRESS_PROPERTY, url);

    return port;
  }
 protected String invokeConnectionManager(String serviceName) throws ConnectionManagerException {
   return ConnectionManagerCache.getLocalEndpointURLByServiceName(serviceName);
 }
  public FindAuditEventsResponseType auditQuery(FindAuditEventsRequestType request) {
    String url = null;

    try {
      log.debug(
          "NhincConstants.AUDIT_LOG_ADAPTER_SERVICE_NAME: "
              + NhincConstants.AUDIT_LOG_ADAPTER_SERVICE_NAME);
      url =
          ConnectionManagerCache.getLocalEndpointURLByServiceName(
              NhincConstants.AUDIT_LOG_ADAPTER_SERVICE_NAME);
    } catch (ConnectionManagerException ex) {
      log.error(
          "Error: Failed to retrieve url for service: "
              + NhincConstants.AUDIT_LOG_ADAPTER_SERVICE_NAME
              + " for local home community");
      log.error(ex.getMessage());
    }

    AdapterAuditLogQueryPortType port = getAdapterPort(url);
    FindAuditEventsResponseType resp = null;

    int retryCount =
        gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper.getInstance().getRetryAttempts();
    int retryDelay =
        gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper.getInstance().getRetryDelay();
    String exceptionText =
        gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper.getInstance().getExceptionText();
    javax.xml.ws.WebServiceException catchExp = null;
    if (retryCount > 0
        && retryDelay > 0
        && exceptionText != null
        && !exceptionText.equalsIgnoreCase("")) {
      int i = 1;
      while (i <= retryCount) {
        try {
          resp = port.findAuditEvents(request);
          break;
        } catch (javax.xml.ws.WebServiceException e) {
          catchExp = e;
          int flag = 0;
          StringTokenizer st = new StringTokenizer(exceptionText, ",");
          while (st.hasMoreTokens()) {
            if (e.getMessage().contains(st.nextToken())) {
              flag = 1;
            }
          }
          if (flag == 1) {
            log.warn("Exception calling ... web service: " + e.getMessage());
            System.out.println(
                "retrying the connection for attempt [ "
                    + i
                    + " ] after [ "
                    + retryDelay
                    + " ] seconds");
            log.info(
                "retrying attempt [ "
                    + i
                    + " ] the connection after [ "
                    + retryDelay
                    + " ] seconds");
            i++;
            try {
              Thread.sleep(retryDelay);
            } catch (InterruptedException iEx) {
              log.error(
                  "Thread Got Interrupted while waiting on AdapterAuditLogQuery call :" + iEx);
            } catch (IllegalArgumentException iaEx) {
              log.error(
                  "Thread Got Interrupted while waiting on AdapterAuditLogQuery call :" + iaEx);
            }
            retryDelay = retryDelay + retryDelay; // This is a requirement from Customer
          } else {
            log.error("Unable to call AdapterAuditLogQuery Webservice due to  : " + e);
            throw e;
          }
        }
      }

      if (i > retryCount) {
        log.error("Unable to call AdapterAuditLogQuery Webservice due to  : " + catchExp);
        throw catchExp;
      }

    } else {
      resp = port.findAuditEvents(request);
    }

    return resp;
  }
  public void notify(
      Element notifyElement,
      ReferenceParametersElements referenceParametersElements,
      AssertionType assertion,
      NhinTargetSystemType target) {
    String url = null;

    log.debug(
        "Notify element received in NhinHiemNotifyWebServiceProxy: "
            + XmlUtility.serializeElementIgnoreFaults(notifyElement));

    if (target != null) {
      try {
        url =
            ConnectionManagerCache.getEndpontURLFromNhinTarget(
                target, NhincConstants.HIEM_NOTIFY_SERVICE_NAME);
      } catch (ConnectionManagerException ex) {
        log.error(
            "Error: Failed to retrieve url for service: "
                + NhincConstants.HIEM_NOTIFY_SERVICE_NAME);
        log.error(ex.getMessage());
      }
    } else {
      log.error("Target system passed into the proxy is null");
    }

    try {
      if (NullChecker.isNotNullish(url)) {
        NotificationConsumer port = getPort(url);

        log.debug("unmarshaling notify message");
        WsntSubscribeMarshaller notifyMarshaller = new WsntSubscribeMarshaller();
        Notify notify = notifyMarshaller.unmarshalNotifyRequest(notifyElement);

        //                Element reMarshalled = notifyMarshaller.marshalNotifyRequest(notify);
        //                log.debug("REMARSHALLED: " +
        // XmlUtility.serializeElementIgnoreFaults(reMarshalled));

        // Policy check
        log.debug("Calling checkPolicy");
        if (checkPolicy(notify, assertion)) {
          log.debug("attaching reference parameter headers");
          SoapUtil soapUtil = new SoapUtil();
          soapUtil.attachReferenceParameterElements(
              (WSBindingProvider) port, referenceParametersElements);

          auditInputMessage(notify, assertion);

          log.debug("Calling token creator");
          SamlTokenCreator tokenCreator = new SamlTokenCreator();
          Map requestContext =
              tokenCreator.CreateRequestContext(assertion, url, NhincConstants.SUBSCRIBE_ACTION);
          ((BindingProvider) port).getRequestContext().putAll(requestContext);

          try {
            log.debug("Calling notification consumer port in NhinHiemWebServiceProxy.");
            port.notify(notify);
          } catch (Exception ex) {
            log.error("Error occurred while trying to invoke notify", ex);
          }

          ((Closeable) port).close();
        } else {
          log.error("Failed policy check on send NHIN notify message");
        }
      } else {
        log.error("The URL for service: " + NhincConstants.HIEM_NOTIFY_SERVICE_NAME + " is null");
      }
    } catch (Throwable t) {
      // TODO: Figure out what to do with the exception
      log.error("Error sending notify to remote gateway: " + t.getMessage(), t);
    }
  }
  public SubscribeResponse handleSubscribe(
      TopicConfigurationEntry topicConfig,
      Subscribe subscribe,
      Element subscribeElement,
      AssertionType assertion,
      NhinTargetCommunitiesType targetCommunitites)
      throws TopicNotSupportedFault, InvalidTopicExpressionFault, SubscribeCreationFailedFault {
    log.debug(
        "In handleSubscribe - patient id: "
            + patientIdentifier.getSubjectIdentifier()
            + ", assigning authority: "
            + patientIdentifier.getAssigningAuthorityIdentifier());
    SubscribeResponse response = new SubscribeResponse();
    CMUrlInfos urlInfoList = null;

    // Store initial subscription received from agency adapter (the parent subscription)
    EndpointReferenceType parentSubscriptionReference =
        storeSubscription(subscribe, subscribeElement, assertion, targetCommunitites);
    String parentSubscriptionReferenceXml = null;
    if (parentSubscriptionReference != null) {
      parentSubscriptionReferenceXml = serializeEndpointReferenceType(parentSubscriptionReference);
    }

    // Obtain all the URLs for the targets being sent to
    try {
      urlInfoList =
          ConnectionManagerCache.getEndpontURLFromNhinTargetCommunities(
              targetCommunitites, NhincConstants.HIEM_SUBSCRIBE_SERVICE_NAME);
    } catch (ConnectionManagerException ex) {
      log.error("Failed to obtain target URLs");
      return null;
    }

    // Find patient correlations
    List<QualifiedSubjectIdentifierType> correlations = determineTargets(urlInfoList);

    // Common message preparation

    int correlationCount = 1;
    if (correlations != null) {
      log.debug("Processing correlation #" + correlationCount++);
      AssigningAuthorityHomeCommunityMappingDAO assigningAuthorityDao =
          new AssigningAuthorityHomeCommunityMappingDAO();
      for (QualifiedSubjectIdentifierType correlation : correlations) {
        CMUrlInfo community = new CMUrlInfo();
        String remoteCommunityId =
            assigningAuthorityDao.getHomeCommunityId(correlation.getAssigningAuthorityIdentifier());
        if (log.isDebugEnabled()) {
          log.debug(
              "Remote assigning authority id: " + correlation.getAssigningAuthorityIdentifier());
          log.debug("Mapped remote community id: " + remoteCommunityId);
        }

        community = findTarget(remoteCommunityId, urlInfoList);

        if (community == null) {
          continue;
        }

        //      Update Subscribe
        updateSubscribe(subscribeElement, correlation);
        if (log.isDebugEnabled()) {
          log.debug(
              "@@@ Updated subscribe: "
                  + XmlUtility.serializeElementIgnoreFaults(subscribeElement));
        }
        //      Policy check - performed in proxy?
        //      Audit Event - performed in proxy?
        //      Send Subscribe
        Element childSubscribeElement = subscribeElement;
        SubscribeResponse subscribeResponse =
            sendSubscribeRequest(childSubscribeElement, assertion, community);
        //
        //      Store subscription
        if (subscribeResponse != null) {
          String childSubscriptionReference = null;

          // Use reflection to get the correct subscription reference object
          Object subRef = getSubscriptionReference(subscribeResponse);
          if (subRef != null) {
            if (subRef.getClass().isAssignableFrom(EndpointReferenceType.class)) {
              childSubscriptionReference =
                  serializeEndpointReferenceType((EndpointReferenceType) subRef);
            } else if (subRef.getClass().isAssignableFrom(W3CEndpointReference.class)) {
              childSubscriptionReference =
                  serializeW3CEndpointReference((W3CEndpointReference) subRef);
            } else {
              log.error("Unknown subscription reference type: " + subRef.getClass().getName());
            }

            String childSubscribeXml;
            try {
              childSubscribeXml = XmlUtility.serializeElement(childSubscribeElement);
            } catch (Exception ex) {
              log.error("failed to process subscribe xml", ex);
              childSubscribeXml = null;
            }

            storeChildSubscription(
                childSubscribeXml, childSubscriptionReference, parentSubscriptionReferenceXml);
          } else {
            log.error("Subscription reference was null");
          }
        } else {
          log.error("The subscribe response message was null.");
        }
      }
    }
    setSubscriptionReference(response, parentSubscriptionReference);

    return response;
  }