<commit_before>/*
 * Copyright 2012 SURFnet bv, The Netherlands
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.surfnet.coin.selfservice.service.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import nl.surfnet.coin.selfservice.domain.FederatieConfig;
import nl.surfnet.coin.selfservice.domain.IdentityProvider;
import nl.surfnet.coin.selfservice.domain.ServiceProvider;
import nl.surfnet.coin.selfservice.service.IdentityProviderService;
import nl.surfnet.coin.selfservice.service.ServiceProviderService;
import nl.surfnet.coin.selfservice.service.SpringSchedulerLoadConfigurationService;
import nl.surfnet.coin.selfservice.util.XStreamFedConfigBuilder;

/**
 * Provider Service seeded with xml config from federation.
 */
public class FederationProviderService implements ServiceProviderService, IdentityProviderService,
    SpringSchedulerLoadConfigurationService {

  private static final Logger LOG = LoggerFactory.getLogger(FederationProviderService.class);
  private final String configurationLocation;
  private FederatieConfig federatieConfig = new FederatieConfig();

  /**
   * Constructor
   *
   * @param configurationLocation Location for the SURFfederatie configuration.
   */
  public FederationProviderService(String configurationLocation) {
    this.configurationLocation = configurationLocation;
    loadConfiguration();
  }

  // configured in coin-selfservice-scheduler.xml
  @Override
  public void loadConfiguration() {
    LOG.debug("Loading configuration from {}", configurationLocation);
    Resource resource;
    try {
      resource = getConfigurationFileAsResource(configurationLocation);
    } catch (MalformedURLException e) {
      LOG.error("URL for SURFfederatie metadata '" + configurationLocation +
          "' is malformed. Fix it in coin-selfservice.properties", e);
      return;
    }
    final XStream xStream = XStreamFedConfigBuilder.getXStreamForFedConfig(true);
    try {
      final FederatieConfig config = (FederatieConfig) xStream.fromXML(resource.getInputStream());
      writeUpdateReport(config);
      if (config != null) {
        federatieConfig = config;
        LOG.debug("Updated SURFfederatie config with content from {}", configurationLocation);
      }
    } catch (IOException e) {
      LOG.error("Could not retrieve SURFfederatie metadata from location '" + configurationLocation + "'",
          e.getMessage());
    }
  }

  private Resource getConfigurationFileAsResource(String configurationFilename) throws MalformedURLException {
    Resource resource;
    if (configurationFilename.matches("^(http://|https://|ftp://|file://)(.+)")) {
      resource = new UrlResource(configurationFilename);
    } else {
      resource = new ClassPathResource(configurationFilename);
    }
    return resource;
  }

  private void writeUpdateReport(FederatieConfig config) {
    if (LOG.isDebugEnabled() == false) {
      return;
    }
    if (config == null) {
      LOG.debug("Got empty SURFfederatie config file, will not update the existing configuration");
    } else {
      Object[] logValues = {CollectionUtils.isNotEmpty(config.getIdPs()), CollectionUtils.isNotEmpty(config.getSps())};
      LOG.debug("Parsed SURFfederatie config. List of IdP's contains items: {}, list of SP's contains items: {}", logValues);
    }
  }

  private boolean isLinked(String idpId, ServiceProvider sp) {
    return sp.getAcl() != null && sp.getAcl().getIdpRefs() != null && sp.getAcl().getIdpRefs().contains(idpId);
  }

  @Override
  @Cacheable(value = {"sps-federation"})
  public List<ServiceProvider> getAllServiceProviders(String idpId) {<commit_msg>Minor code cleanup for BACKLOG-539<commit_after>/*
 * Copyright 2012 SURFnet bv, The Netherlands
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.surfnet.coin.selfservice.service.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import com.thoughtworks.xstream.XStream;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;

import nl.surfnet.coin.selfservice.domain.FederatieConfig;
import nl.surfnet.coin.selfservice.domain.IdentityProvider;
import nl.surfnet.coin.selfservice.domain.ServiceProvider;
import nl.surfnet.coin.selfservice.service.IdentityProviderService;
import nl.surfnet.coin.selfservice.service.ServiceProviderService;
import nl.surfnet.coin.selfservice.service.SpringSchedulerLoadConfigurationService;
import nl.surfnet.coin.selfservice.util.XStreamFedConfigBuilder;

/**
 * Provider Service seeded with xml config from federation.
 */
public class FederationProviderService implements ServiceProviderService, IdentityProviderService,
    SpringSchedulerLoadConfigurationService {

  private static final Logger LOG = LoggerFactory.getLogger(FederationProviderService.class);
  private final String configurationLocation;
  private FederatieConfig federatieConfig = new FederatieConfig();

  /**
   * Constructor
   *
   * @param configurationLocation Location for the SURFfederatie configuration.
   */
  public FederationProviderService(String configurationLocation) {
    this.configurationLocation = configurationLocation;
    loadConfiguration();
  }

  // configured in coin-selfservice-scheduler.xml
  @Override
  public void loadConfiguration() {
    LOG.debug("Loading configuration from {}", configurationLocation);
    Resource resource;
    try {
      resource = getConfigurationFileAsResource(configurationLocation);
    } catch (MalformedURLException e) {
      LOG.error("URL for SURFfederatie metadata '{}' is malformed. Fix it in coin-selfservice.properties. Error: {}",
          configurationLocation, e);
      return;
    }
    final XStream xStream = XStreamFedConfigBuilder.getXStreamForFedConfig(true);
    try {
      final FederatieConfig config = (FederatieConfig) xStream.fromXML(resource.getInputStream());
      writeUpdateReport(config);
      if (config != null) {
        federatieConfig = config;
        LOG.debug("Updated SURFfederatie config with content from {}", configurationLocation);
      }
    } catch (IOException e) {
      LOG.error("Could not retrieve SURFfederatie metadata from location '{}', message: {}",
          configurationLocation, e.getMessage());
    }
  }

  private Resource getConfigurationFileAsResource(String configurationFilename) throws MalformedURLException {
    Resource resource;
    if (configurationFilename.matches("^(http://|https://|ftp://|file://)(.+)")) {
      resource = new UrlResource(configurationFilename);
    } else {
      resource = new ClassPathResource(configurationFilename);
    }
    return resource;
  }

  private void writeUpdateReport(FederatieConfig config) {
    if (!LOG.isDebugEnabled()) {
      return;
    }
    if (config == null) {
      LOG.debug("Got empty SURFfederatie config file, will not update the existing configuration");
    } else {
      LOG.debug("Parsed SURFfederatie config. List of IdP's contains items: {}, list of SP's contains items: {}",
          CollectionUtils.isNotEmpty(config.getIdPs()),
          CollectionUtils.isNotEmpty(config.getSps()));
    }
  }

  private boolean isLinked(String idpId, ServiceProvider sp) {
    return sp.getAcl() != null && sp.getAcl().getIdpRefs() != null && sp.getAcl().getIdpRefs().contains(idpId);
  }

  @Override
  @Cacheable(value = {"sps-federation"})
  public List<ServiceProvider> getAllServiceProviders(String idpId) {
{'fraction_non_alphanumeric': 0.09732307358838192, 'fraction_numerical': 0.002492684512842744, 'mean_word_length': 4.450679267572356, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6546829', 'n_tokens_mistral': 2500, 'n_tokens_neox': 2469, 'n_words': 636}