/**
   * Method populates fields localEntityId, localEntityRole, localEntityMetadata,
   * localEntityRoleMetadata and peerEntityRole. In case fields localAlias, localEntityId,
   * localEntiyRole or peerEntityRole are set they are used, defaults of default SP and IDP as a
   * peer are used instead.
   *
   * @param samlContext context to populate
   * @throws org.opensaml.saml2.metadata.provider.MetadataProviderException in case metadata do not
   *     contain expected entities or localAlias is specified but not found
   */
  private void populateLocalEntity(SAMLMessageContext samlContext)
      throws MetadataProviderException {

    String localEntityId = samlContext.getLocalEntityId();
    QName localEntityRole = samlContext.getLocalEntityRole();

    if (localEntityId == null) {
      throw new MetadataProviderException(
          "No hosted service provider is configured and no alias was selected");
    }

    EntityDescriptor entityDescriptor = metadata.getEntityDescriptor(localEntityId);
    RoleDescriptor roleDescriptor =
        metadata.getRole(localEntityId, localEntityRole, SAMLConstants.SAML20P_NS);
    ExtendedMetadata extendedMetadata = metadata.getExtendedMetadata(localEntityId);

    if (entityDescriptor == null || roleDescriptor == null) {
      throw new MetadataProviderException(
          "Metadata for entity "
              + localEntityId
              + " and role "
              + localEntityRole
              + " wasn't found");
    }

    samlContext.setLocalEntityMetadata(entityDescriptor);
    samlContext.setLocalEntityRoleMetadata(roleDescriptor);
    samlContext.setLocalExtendedMetadata(extendedMetadata);

    if (extendedMetadata.getSigningKey() != null) {
      samlContext.setLocalSigningCredential(
          keyManager.getCredential(extendedMetadata.getSigningKey()));
    } else {
      samlContext.setLocalSigningCredential(keyManager.getDefaultCredential());
    }
  }