if we are dealing with the identity service and there is no endpoint
    in the current region, it is okay to use the first endpoint for any
    identity service endpoints and we can assume that it is global
778764
def get_url_for_service(service, region, endpoint_type):
    if 'type' not in service:
        return None

    identity_version = get_version_from_service(service)
    service_endpoints = service.get('endpoints', [])
    available_endpoints = [endpoint for endpoint in service_endpoints
                           if region == _get_endpoint_region(endpoint)]
    
    if service['type'] == 'identity' and not available_endpoints:
        available_endpoints = [endpoint for endpoint in service_endpoints]

    for endpoint in available_endpoints:
        try:
            if identity_version < 3:
                return endpoint.get(endpoint_type)
            else:
                interface = \
                    ENDPOINT_TYPE_TO_INTERFACE.get(endpoint_type, '')
                if endpoint.get('interface') == interface:
                    return endpoint.get('url')
        except (IndexError, KeyError):
            # it could be that the current endpoint just doesn't match the
            # type, continue trying the next one
            pass
    return None
431637
@Override
    public void unexportTransaction(String globalId) throws SystemException {

        // look up the tran or just get the one off the thread

        // blow up if there's no tran
        final UOWCoordinator uowCoord = _uowc.getUOWCoord();
        if (uowCoord == null || !uowCoord.isGlobal()) {
            throw new SystemException("No global transaction");
        }

        // Resume transaction association as we are coming back on server
        ((DistributableTransaction) uowCoord).resumeAssociation();
    }
1277684
private boolean noAuthn(HttpServletRequest hreq) {
		if(pathExceptions!=null) {
			String pi = hreq.getPathInfo();
			if(pi==null) return false; // JBoss sometimes leaves null
			for(String pe : pathExceptions) {
				if(pi.startsWith(pe))return true;
			}
		}
		return false;
	}
991769
def ShouldRetry(self, exception):
        
        if not self.connection_policy.EnableEndpointDiscovery:
            return False

        if self.failover_retry_count >= self.Max_retry_attempt_count:
            return False

        self.failover_retry_count += 1

        if self.location_endpoint:
            if _OperationType.IsReadOnlyOperation(self.request.operation_type):
                #Mark current read endpoint as unavailable
                self.global_endpoint_manager.mark_endpoint_unavailable_for_read(self.location_endpoint)
            else:
                self.global_endpoint_manager.mark_endpoint_unavailable_for_write(self.location_endpoint)

        # set the refresh_needed flag to ensure that endpoint list is
        # refreshed with new writable and readable locations
        self.global_endpoint_manager.refresh_needed = True
        
        # clear previous location-based routing directive
        self.request.clear_route_to_location()

        # set location-based routing directive based on retry count
        # simulating single master writes by ensuring usePreferredLocations
        # is set to false
        self.request.route_to_location_with_preferred_location_flag(self.failover_retry_count, False)
        
        # Resolve the endpoint for the request and pin the resolution to the resolved endpoint
        # This enables marking the endpoint unavailability on endpoint failover/unreachability
        self.location_endpoint = self.global_endpoint_manager.resolve_service_endpoint(self.request)
        self.request.route_to_location(self.location_endpoint)
        return True
1239448
private static ClientAuthenticationMethod firstSupportedMethod(final List<ClientAuthenticationMethod> metadataMethods) {
        Optional<ClientAuthenticationMethod> firstSupported = 
            metadataMethods.stream().filter((m) -> SUPPORTED_METHODS.contains(m)).findFirst();
        if (firstSupported.isPresent()) {
            return firstSupported.get();
        } else {
            throw new TechnicalException("None of the Token endpoint provider metadata authentication methods are supported: " + 
                metadataMethods);
        }
    }
949094
public static void initEndpointDirectories(MuleContext muleContext, String[] serviceNames, String[] endpointNames) throws Exception {

		// Stop all named services (either Flows or services
		List<Lifecycle> services = new ArrayList<Lifecycle>();
		for (String serviceName : serviceNames) {
			try {
				Lifecycle service = muleContext.getRegistry().lookupObject(serviceName);
//				logServiceStatus(service);
//				service.stop();
//				logServiceStatus(service);
				services.add(service);
			} catch (Exception e) {
				logger.error("Error '" + e.getMessage()
						+ "' occured while stopping the service " + serviceName
						+ ". Perhaps the service did not exist in the config?");
				throw e;
			}
		}

		// Now init the directory for each named endpoint, one by one
		for (String endpointName : endpointNames) {
			initEndpointDirectory(muleContext, endpointName);
		}

		// We are done, startup the services again so that the test can begin...
		for (@SuppressWarnings("unused") Lifecycle service : services) {
//			logServiceStatus(service);
//			service.start();
//			logServiceStatus(service);
		}
	}
708286
public static void loadGlobalApp(ServletRequest request, GlobalApp globalApp) {
        if(globalApp != null)
            request.setAttribute(GLOBAL_APP_IMPLICIT_OBJECT_KEY, globalApp);
    }
626349
def available_services_regions(self):
        """"""
        regions = []
        if self.service_catalog:
            for service in self.service_catalog:
                service_type = service.get('type')
                if service_type is None or service_type == 'identity':
                    continue
                for endpoint in service.get('endpoints', []):
                    region = utils.get_endpoint_region(endpoint)
                    if region not in regions:
                        regions.append(region)
        return regions
638448
public boolean matchesGlobalId(byte[] globalTransactionId) {
        if (globalTransactionId.length != Xid.MAXGTRIDSIZE) {
            return false;
        }
        for (int i = 8; i < globalTransactionId.length; i++) {
            if (globalTransactionId[i] != baseId[i]) {
                return false;
            }
        }
        // for recovery, only match old transactions
        long id = extractLong(globalTransactionId, 0);
        return (id < start);
    }
1363638
def get_sdc_endpoint_from_keystone(self, region_name, service_type, endpoint_type):
        

        logger.debug("Getting SDC endpoint")
        endpoint = None
        for service in self.keystone_client.auth_ref['serviceCatalog']:
            if service['name'] == service_type:
                for endpoint in service['endpoints']:
                    if endpoint['region'] == region_name:
                        endpoint = endpoint[endpoint_type]
                        break
                break
        logger.debug("SDC endpoint (Service: %s, Type: %s, Region: %s) is: %s", service_type, endpoint_type,
                     region_name, endpoint_type)
        return endpoint
956575
public boolean isGlobalTxActive()
   {
      TransactionContext ctx;
      try
      {
         // We need to check the status also to be able to manage properly suspend and resume
         return (ctx = contexts.get()) != null && ctx.getXidContext() != null && tm.getStatus() != Status.STATUS_NO_TRANSACTION;
      }
      catch (SystemException e)
      {
         log.warn("Could not check if a global Tx has been started", e);
      }
      return false;
   }
525919
private static Endpoint initServiceEndpoint(EndpointRegistry epRegistry, String contextPath, String servletName)
   {
      if (contextPath.startsWith("/"))
         contextPath = contextPath.substring(1);

      final ObjectName oname = ObjectNameFactory.create(Endpoint.SEPID_DOMAIN + ":" + Endpoint.SEPID_PROPERTY_CONTEXT
            + "=" + contextPath + "," + Endpoint.SEPID_PROPERTY_ENDPOINT + "=" + servletName);
      Endpoint endpoint = epRegistry.getEndpoint(oname);
      if (endpoint == null)
      {
         throw Messages.MESSAGES.cannotObtainEndpoint(oname);
      }

      //Inject the EJB and JNDI resources if possible
      injectServiceAndHandlerResources(endpoint);

      return endpoint;
   }
1198423
function createEndPoint (local) {
  var endPoint = new EndPoint(local), local = endPoint.local;
  if (!endPoints[local.port]) endPoints[local.port] = {};
  return endPoints[local.port][local.address] = endPoint;
}
830212
public static GlobalDiscoveryEntry newGlobalDiscoveryEntry(Version providerVesion,
                                                               String domain,
                                                               String interfaceName,
                                                               String participantId,
                                                               ProviderQos qos,
                                                               Long lastSeenDateMs,
                                                               Long expiryDateMs,
                                                               String publicKeyId,
                                                               Address address) {
        // CHECKSTYLE ON
        return new GlobalDiscoveryEntry(providerVesion,
                                        domain,
                                        interfaceName,
                                        participantId,
                                        qos,
                                        lastSeenDateMs,
                                        expiryDateMs,
                                        publicKeyId,
                                        serializeAddress(address));
    }
1081161
public static Endpoint determineEndpointForRequest(final RequestAbstractType authnRequest,
                                                       final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                                       final String binding) {
        var endpoint = (Endpoint) null;
        if (authnRequest instanceof LogoutRequest) {
            endpoint = adaptor.getSingleLogoutService(binding);
        } else {
            val endpointReq = getAssertionConsumerServiceFromRequest(authnRequest, binding);
            endpoint = endpointReq == null
                ? adaptor.getAssertionConsumerService(binding)
                : endpointReq;
        }

        if (endpoint == null || StringUtils.isBlank(endpoint.getBinding())) {
            throw new SamlException("Assertion consumer service does not define a binding");
        }
        val location = StringUtils.isBlank(endpoint.getResponseLocation()) ? endpoint.getLocation() : endpoint.getResponseLocation();
        if (StringUtils.isBlank(location)) {
            throw new SamlException("Assertion consumer service does not define a target location");
        }
        return endpoint;
    }
259570
def endpoint_delete(service, region=None, profile=None, interface=None, **connection_args):
    '''
    
    '''
    kstone = auth(profile, **connection_args)
    endpoint = endpoint_get(service, region, profile, interface, **connection_args)
    if not endpoint or 'Error' in endpoint:
        return {'Error': 'Could not find any endpoints for the service'}
    kstone.endpoints.delete(endpoint['id'])
    endpoint = endpoint_get(service, region, profile, interface, **connection_args)
    if not endpoint or 'Error' in endpoint:
        return True
1325300
void closeTransactionalBranch(Xid xid) {

        if (this.transactionBinding.getTransactionBindingType() != TransactionBindingType.GlobalTransaction) {
            throw new IllegalStateException("XAConnection not associated to a global transaction");
        }

        GlobalTransactionProxy<C> globalTransactionProxy = this.transactionBinding.getEnlistedGlobalTransaction();
        globalTransactionProxy.close();

        delistTransaction();
    }