Load saml metadata into request context.

@param requestContext    the request context
@param entityId          the entity id
@param registeredService the registered service
18725
protected void loadSamlMetadataIntoRequestContext(final RequestContext requestContext, final String entityId, final RegisteredService registeredService) {
        LOGGER.debug("Locating SAML MDUI for entity [{}]", entityId);
        val mdui = MetadataUIUtils.locateMetadataUserInterfaceForEntityId(
            this.metadataAdapter, entityId, registeredService, WebUtils.getHttpServletRequestFromExternalWebflowContext(requestContext));
        LOGGER.debug("Located SAML MDUI for entity [{}] as [{}]", entityId, mdui);
        WebUtils.putServiceUserInterfaceMetadata(requestContext, mdui);
    }
1148593
public void loadContextMenu(
        final CmsUUID structureId,
        final AdeContext context,
        final CmsContextMenuButton menuButton) {

        CmsRpcAction<List<CmsContextMenuEntryBean>> action = new CmsRpcAction<List<CmsContextMenuEntryBean>>() {

            @Override
            public void execute() {

                CmsCoreProvider.getService().getContextMenuEntries(structureId, context, this);
            }

            @Override
            protected void onResponse(List<CmsContextMenuEntryBean> result) {

                menuButton.showMenu(transformEntries(result, structureId));
            }
        };
        action.execute();
    }
757627
protected void buildSamlResponse(final HttpServletResponse response,
                                     final HttpServletRequest request,
                                     final Pair<AuthnRequest, MessageContext> authenticationContext,
                                     final Assertion casAssertion,
                                     final String binding) {

        val authnRequest = authenticationContext.getKey();
        val pair = getRegisteredServiceAndFacade(authnRequest);

        val entityId = pair.getValue().getEntityId();
        LOGGER.debug("Preparing SAML response for [{}]", entityId);
        samlProfileHandlerConfigurationContext.getResponseBuilder().build(authnRequest, request, response, casAssertion,
            pair.getKey(), pair.getValue(), binding, authenticationContext.getValue());
        LOGGER.info("Built the SAML response for [{}]", entityId);
    }
87724
protected RegisteredService resolveRegisteredServiceInRequestContext(final RequestContext requestContext) {
        val resolvedService = resolveServiceFromAuthenticationRequest(requestContext);
        if (resolvedService != null) {
            val service = getWebflowEventResolutionConfigurationContext().getServicesManager().findServiceBy(resolvedService);
            RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(resolvedService, service);
            return service;
        }
        LOGGER.debug("Authentication request is not accompanied by a service given none is specified");
        return null;
    }
30803
protected String getBinding(ProfileRequestContext<?, ?> context) {
    SAMLBindingContext samlBinding = this.samlBindingContextLookupStrategy.apply(context);
    return samlBinding != null ? samlBinding.getBindingUri() : null;
  }
287513
@SuppressFBWarnings("PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS")
    public void initServiceRegistryIfNecessary() {
        val size = this.serviceRegistry.size();
        LOGGER.trace("Service registry contains [{}] service definition(s)", size);

        LOGGER.warn("Service registry [{}] will be auto-initialized from JSON service definitions. "
            + "This behavior is only useful for testing purposes and MAY NOT be appropriate for production. "
            + "Consider turning off this behavior via the setting [cas.serviceRegistry.initFromJson=false] "
            + "and explicitly register definitions in the services registry.", this.serviceRegistry.getName());

        val servicesLoaded = this.jsonServiceRegistry.load();
        LOGGER.debug("Loaded JSON services are [{}]", servicesLoaded.stream().map(RegisteredService::getName).collect(Collectors.joining(",")));

        servicesLoaded
            .forEach(r -> {
                if (!findExistingMatchForService(r)) {
                    LOGGER.debug("Initializing service registry with the [{}] JSON service definition...", r.getName());
                    this.serviceRegistry.save(r);
                }
            });
        this.servicesManager.load();
        LOGGER.info("Service registry [{}] contains [{}] service definitions", this.serviceRegistry.getName(), this.servicesManager.count());

    }
1161701
public void loadContentDefinition(final String entityId, final Command callback) {

        AsyncCallback<CmsContentDefinition> asyncCallback = new AsyncCallback<CmsContentDefinition>() {

            public void onFailure(Throwable caught) {

                onRpcError(caught);
            }

            public void onSuccess(CmsContentDefinition result) {

                registerContentDefinition(result);
                callback.execute();
            }
        };
        getService().loadContentDefinition(entityId, asyncCallback);
    }
812950
protected void verifyRegisteredService(final RequestContext requestContext, final RegisteredService registeredService) {
        if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
            LOGGER.debug("Service [{}] is not recognized/allowed by the CAS service registry", registeredService);
            if (registeredService != null) {
                WebUtils.putUnauthorizedRedirectUrlIntoFlowScope(requestContext, registeredService.getAccessStrategy().getUnauthorizedRedirectUrl());
            }
            throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, StringUtils.EMPTY);
        }
    }
1239391
public void verifySamlProfileRequestIfNeeded(final RequestAbstractType profileRequest,
                                                 final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                                 final HttpServletRequest request,
                                                 final MessageContext context) throws Exception {

        verifySamlProfileRequestIfNeeded(profileRequest, adaptor.getMetadataResolver(), request, context);
    }
1168251
public void registerServiceInstance(ProvidedServiceInstance instance){

        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.RegisterServiceInstance);

        RegisterServiceInstanceProtocol p = new RegisterServiceInstanceProtocol(instance);

        connection.submitRequest(header, p, null);

    }
90810
public static RegisteredService getRegisteredService(final RequestContext context) {
        return context != null ? (RegisteredService) context.getFlowScope().get(PARAMETER_REGISTERED_SERVICE) : null;
    }
184165
public InitializrServiceMetadata loadMetadata(String serviceUrl) throws IOException {
		CloseableHttpResponse httpResponse = executeInitializrMetadataRetrieval(
				serviceUrl);
		validateResponse(httpResponse, serviceUrl);
		return parseJsonMetadata(httpResponse.getEntity());
	}
1364493
@GetMapping
  public String init(
      @RequestParam(value = "entity", required = false) String selectedEntityName,
      @RequestParam(value = "entityId", required = false) String selectedEntityId,
      Model model) {
    StringBuilder message = new StringBuilder("");

    final boolean currentUserIsSu = SecurityUtils.currentUserIsSu();

    Map<String, EntityType> entitiesMeta =
        dataService
            .getMeta()
            .getEntityTypes()
            .filter(entityType -> !entityType.isAbstract())
            .filter(entityType -> currentUserIsSu || !EntityTypeUtils.isSystemEntity(entityType))
            .sorted(Comparator.comparing(EntityType::getLabel))
            .collect(toLinkedMap(EntityType::getId, Function.identity()));

    model.addAttribute("entitiesMeta", entitiesMeta);
    if (selectedEntityId != null && selectedEntityName == null) {
      EntityType entityType = dataService.getMeta().getEntityType(selectedEntityId).orElse(null);
      if (entityType == null) {
        message.append("Entity does not exist or you do not have permission on this entity");
      } else {
        selectedEntityName = entityType.getId();
      }

      if (selectedEntityName != null) {
        checkExistsAndPermission(selectedEntityName, message);
      }
    }
    if (StringUtils.isNotEmpty(message.toString())) {
      model.addAttribute("warningMessage", message.toString());
    }
    model.addAttribute("selectedEntityName", selectedEntityName);
    boolean navigatorAvailable = menuReaderService.findMenuItemPath(NAVIGATOR) != null;
    model.addAttribute(
        "showNavigatorLink", dataExplorerSettings.isShowNavigatorLink() && navigatorAvailable);

    model.addAttribute("hasTrackingId", null != appSettings.getGoogleAnalyticsTrackingId());
    model.addAttribute(
        "hasMolgenisTrackingId", null != appSettings.getGoogleAnalyticsTrackingIdMolgenis());

    return "view-dataexplorer";
  }
1123236
public static void preparePeerEntitySamlEndpointContext(final RequestAbstractType request,
                                                            final MessageContext outboundContext,
                                                            final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                                            final String binding) throws SamlException {
        val entityId = adaptor.getEntityId();
        if (!adaptor.containsAssertionConsumerServices()) {
            throw new SamlException("No assertion consumer service could be found for entity " + entityId);
        }

        val peerEntityContext = outboundContext.getSubcontext(SAMLPeerEntityContext.class, true);
        if (peerEntityContext == null) {
            throw new SamlException("SAMLPeerEntityContext could not be defined for entity " + entityId);
        }
        peerEntityContext.setEntityId(entityId);

        val endpointContext = peerEntityContext.getSubcontext(SAMLEndpointContext.class, true);
        if (endpointContext == null) {
            throw new SamlException("SAMLEndpointContext could not be defined for entity " + entityId);
        }

        val endpoint = determineEndpointForRequest(request, adaptor, binding);
        LOGGER.debug("Configured peer entity endpoint to be [{}] with binding [{}]", endpoint.getLocation(), endpoint.getBinding());
        endpointContext.setEndpoint(endpoint);
    }
93085
public void registerDeferredService(BundleContext bundleContext, Class<?> providedService, Dictionary dict) {
        Object obj = serviceReg.get();
        if (obj instanceof ServiceRegistration<?>) {
            // already registered - nothing to do here
            return;
        }
        if (obj instanceof CountDownLatch) {
            // another thread is in the process of (de)registering - wait for it to finish
            try {
                ((CountDownLatch) obj).await();

                if (serviceReg.get() instanceof ServiceRegistration<?>) {
                    // Another thread has successfully registered to return out (so we don't go
                    // into recursive loop).
                    return;
                }
            } catch (InterruptedException swallowed) {
                if (tc.isDebugEnabled()) {
                    Tr.debug(tc, "Count down interrrupted", swallowed);
                }
            }
        } else {
            // This is probably the first thread to register.
            // Claim the right to register by setting a latch for other threads to wait on.
            CountDownLatch latch = new CountDownLatch(1);
            if (serviceReg.compareAndSet(null, latch)) {
                // This thread won the right to register the service
                try {
                    serviceReg.set(bundleContext.registerService(providedService.getName(), this, dict));
                    // successfully registered - nothing more to do
                    return;
                } finally {
                    // if the serviceReg was not updated for any reason, we need to set it back to null
                    serviceReg.compareAndSet(latch, null);
                    // in any case we need to allow any blocked threads to proceed
                    latch.countDown();
                }
            }
        }
        // If we get to here we have not successfully registered 
        // nor seen another thread successfully register, so just recurse.
        registerDeferredService(bundleContext, providedService, dict);
    }
703489
protected void populateBindingContext(final SAML2MessageContext messageContext) {
        SAMLBindingContext bindingContext = messageContext.getSubcontext(SAMLBindingContext.class, true);
        bindingContext.setBindingUri(getBindingURI(messageContext));
        bindingContext.setHasBindingSignature(false);
        bindingContext.setIntendedDestinationEndpointURIRequired(SAMLBindingSupport.isMessageSigned(messageContext));
    }
412001
@SuppressWarnings("unchecked")
	public void requestInitialized(ServletRequestEvent sre) {
		WebContext<HttpServletRequest> context = (WebContext<HttpServletRequest>) container.component(container.contexts().get(Request.class));
		context.associate((HttpServletRequest) sre.getServletRequest());
	}