<commit_before>/**
 * 
 */
package gov.nih.nci.cagrid.portal.portlet.credmgr;

import gov.nih.nci.cagrid.authentication.stubs.types.InvalidCredentialFault;
import gov.nih.nci.cagrid.portal.dao.PortalUserDao;
import gov.nih.nci.cagrid.portal.domain.IdPAuthentication;
import gov.nih.nci.cagrid.portal.domain.IdentityProvider;
import gov.nih.nci.cagrid.portal.domain.PortalUser;
import gov.nih.nci.cagrid.portal.security.AuthnService;
import gov.nih.nci.cagrid.portal.security.AuthnServiceException;
import gov.nih.nci.cagrid.portal.security.AuthnTimeoutException;
import gov.nih.nci.cagrid.portal.security.EncryptionService;
import gov.nih.nci.cagrid.portal.security.IdPAuthnInfo;
import gov.nih.nci.cagrid.portal.security.ProxyUtil;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.gaards.authentication.client.AuthenticationClient;
import org.cagrid.gaards.dorian.client.GridUserClient;
import org.cagrid.gaards.dorian.federation.TrustedIdentityProvider;
import org.globus.gsi.GlobusCredential;
import org.globus.wsrf.impl.security.authorization.IdentityAuthorization;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author <a href="mailto:<EMAIL>><NAME></a>
 * 
 */
@Transactional
public class CredentialManagerFacade {

	private static final Log logger = LogFactory
			.getLog(CredentialManagerFacade.class);

	private static final String BASIC_AUTH_PROFILE = "{http://gaards.cagrid.org/authentication}BasicAuthentication";

	private HibernateTemplate hibernateTemplate;
	private String ifsUrl;
	private AuthnService authnService;
	private EncryptionService encryptionService;
	private PortalUserDao portalUserDao;

	/**
	 * 
	 */
	public CredentialManagerFacade() {

	}

	public List<CredentialBean> listCredentials(String userId) {
		logger.debug("Listing credentials for user: " + userId);
		List<CredentialBean> credentials = null;
		try {
			PortalUser portalUser = getPortalUser(userId);

			credentials = new ArrayList<CredentialBean>();
			for (IdPAuthentication idpAuth : portalUser.getAuthentications()) {
				String credStr = this.getEncryptionService().decrypt(
						idpAuth.getGridCredential());
				GlobusCredential globusCred = new GlobusCredential(
						new ByteArrayInputStream(credStr.getBytes()));
				Date validUntil = new Date(System.currentTimeMillis()
						+ globusCred.getTimeLeft());
				CredentialBean credBean = new CredentialBean(idpAuth
						.getIdentity(), validUntil, new IdPBean(idpAuth
						.getIdentityProvider().getLabel(), idpAuth
						.getIdentityProvider().getUrl()));
				credBean.setDefaultCredential(idpAuth.isDefault());
				credentials.add(credBean);
			}
		} catch (Exception ex) {
			String msg = "Error listing credentials: " + ex.getMessage();
			logger.error(msg, ex);
			throw new RuntimeException(msg, ex);
		}
		return credentials;
	}

	private PortalUser getPortalUser(String userId) {

		try {
			String[] parts = userId.split(":");
			Long.valueOf(parts[0]);
			Long.valueOf(parts[1]);
		} catch (Exception ex) {
			throw new RuntimeException("Invalid portal ID: " + userId);
		}

		List l = getHibernateTemplate().find(
				"from PortalUser where portalId = ?", userId);
		if (l.size() != 1) {
			throw new RuntimeException("Found " + l.size()
					+ " used for portal ID: " + userId);
		}

		return (PortalUser) l.iterator().next();
	}

	public List<IdPBean> listIdPs() {
		List<IdPBean> idpBeans = new ArrayList<IdPBean>();
		try {
			List l = getHibernateTemplate().find("from IdentityProvider");
			for (Iterator<IdentityProvider> i = l.iterator(); i.hasNext();) {
				IdentityProvider idp = i.next();
				idpBeans.add(new IdPBean(idp.getLabel(), idp.getUrl()));
			}
		} catch (Exception ex) {
			String msg = "Error listing identity providers: " + ex.getMessage();
			logger.error(msg, ex);
			throw new RuntimeException(msg, ex);
		}
		return idpBeans;
	}

	public List<IdPBean> listIdPsFromDorian() {

		List<IdPBean> idpBeans = new ArrayList<IdPBean>();

		try {
			GridUserClient guc = new GridUserClient(getIfsUrl());
			List<TrustedIdentityProvider> idps = guc
					.getTrustedIdentityProviders();
			for (TrustedIdentityProvider idp : idps) {
				String idpUrl = idp.getAuthenticationServiceURL();

				try {
					AuthenticationClient ac = new AuthenticationClient(idpUrl);
					String idpIdent = idp.getAuthenticationServiceIdentity();
					if (idpIdent != null && idpIdent.trim().length() > 0) {
						ac
								.setAuthorization(new IdentityAuthorization(
										idpIdent));
					}
					try {
						for (QName profileQName : ac
								.getSupportedAuthenticationProfiles()) {
							if (profileQName.equals(BASIC_AUTH_PROFILE)) {
								IdPBean bean = new IdPBean(
										idp.getDisplayName(), idpUrl);
								idpBeans.add(bean);
							}
						}
					} catch (Exception ex) {
						String msg = "Couldn't get profiles for: " + idpUrl
								+ "\n" + ex.getMessage();
						logger.warn(msg, ex);
					}
				} catch (Exception ex) {
					String msg = "Error connecting to " + idpUrl + ": "
							+ ex.getMessage();
					logger.warn(msg, ex);
				}
			}
		} catch (Exception ex) {
			logger.error("Error getting identity provider list: "
					+ ex.getMessage(), ex);
			throw new RuntimeException("Error getting identity provider list.",
					ex);
		}

		return idpBeans;
	}

	public String addIdP(String label, String url) {<commit_msg>add identityproviderdao<commit_after>/**
 * 
 */
package gov.nih.nci.cagrid.portal.portlet.credmgr;

import gov.nih.nci.cagrid.authentication.stubs.types.InvalidCredentialFault;
import gov.nih.nci.cagrid.portal.dao.PortalUserDao;
import gov.nih.nci.cagrid.portal.domain.IdPAuthentication;
import gov.nih.nci.cagrid.portal.domain.IdentityProvider;
import gov.nih.nci.cagrid.portal.domain.PortalUser;
import gov.nih.nci.cagrid.portal.security.AuthnService;
import gov.nih.nci.cagrid.portal.security.AuthnServiceException;
import gov.nih.nci.cagrid.portal.security.AuthnTimeoutException;
import gov.nih.nci.cagrid.portal.security.EncryptionService;
import gov.nih.nci.cagrid.portal.security.IdPAuthnInfo;
import gov.nih.nci.cagrid.portal.security.ProxyUtil;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.cagrid.gaards.authentication.client.AuthenticationClient;
import org.cagrid.gaards.dorian.client.GridUserClient;
import org.cagrid.gaards.dorian.federation.TrustedIdentityProvider;
import org.globus.gsi.GlobusCredential;
import org.globus.wsrf.impl.security.authorization.IdentityAuthorization;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author <a href="mailto:<EMAIL>><NAME></a>
 * @author kherm <EMAIL>
 *
 */
@Transactional
public class CredentialManagerFacade {

	private static final Log logger = LogFactory
			.getLog(CredentialManagerFacade.class);

	private static final String BASIC_AUTH_PROFILE = "{http://gaards.cagrid.org/authentication}BasicAuthentication";

	private HibernateTemplate hibernateTemplate;
	private String ifsUrl;
	private AuthnService authnService;
	private EncryptionService encryptionService;
	private PortalUserDao portalUserDao;

	/**
	 * 
	 */
	public CredentialManagerFacade() {

	}

	public List<CredentialBean> listCredentials(String userId) {
		logger.debug("Listing credentials for user: " + userId);
		List<CredentialBean> credentials = null;
		try {
			PortalUser portalUser = getPortalUser(userId);

			credentials = new ArrayList<CredentialBean>();
			for (IdPAuthentication idpAuth : portalUser.getAuthentications()) {
				String credStr = this.getEncryptionService().decrypt(
						idpAuth.getGridCredential());
				GlobusCredential globusCred = new GlobusCredential(
						new ByteArrayInputStream(credStr.getBytes()));
				Date validUntil = new Date(System.currentTimeMillis()
						+ globusCred.getTimeLeft());
				CredentialBean credBean = new CredentialBean(idpAuth
						.getIdentity(), validUntil, new IdPBean(idpAuth
						.getIdentityProvider().getLabel(), idpAuth
						.getIdentityProvider().getUrl()));
				credBean.setDefaultCredential(idpAuth.isDefault());
				credentials.add(credBean);
			}
		} catch (Exception ex) {
			String msg = "Error listing credentials: " + ex.getMessage();
			logger.error(msg, ex);
			throw new RuntimeException(msg, ex);
		}
		return credentials;
	}

	private PortalUser getPortalUser(String userId) {

		try {
			String[] parts = userId.split(":");
			Long.valueOf(parts[0]);
			Long.valueOf(parts[1]);
		} catch (Exception ex) {
			throw new RuntimeException("Invalid portal ID: " + userId);
		}

		List l = getHibernateTemplate().find(
				"from PortalUser where portalId = ?", userId);
		if (l.size() != 1) {
			throw new RuntimeException("Found " + l.size()
					+ " used for portal ID: " + userId);
		}

		return (PortalUser) l.iterator().next();
	}

	public List<IdPBean> listIdPs() {
		List<IdPBean> idpBeans = new ArrayList<IdPBean>();
		try {
			List l = getHibernateTemplate().find("from IdentityProvider");
			for (Iterator<IdentityProvider> i = l.iterator(); i.hasNext();) {
				IdentityProvider idp = i.next();
				idpBeans.add(new IdPBean(idp.getLabel(), idp.getUrl()));
			}
		} catch (Exception ex) {
			String msg = "Error listing identity providers: " + ex.getMessage();
			logger.error(msg, ex);
			throw new RuntimeException(msg, ex);
		}
		return idpBeans;
	}

	public List<IdPBean> listIdPsFromDorian() {

		List<IdPBean> idpBeans = new ArrayList<IdPBean>();

		try {
			GridUserClient guc = new GridUserClient(getIfsUrl());
			List<TrustedIdentityProvider> idps = guc
					.getTrustedIdentityProviders();
			for (TrustedIdentityProvider idp : idps) {
				String idpUrl = idp.getAuthenticationServiceURL();

				try {
					AuthenticationClient ac = new AuthenticationClient(idpUrl);
					String idpIdent = idp.getAuthenticationServiceIdentity();
					if (idpIdent != null && idpIdent.trim().length() > 0) {
						ac
								.setAuthorization(new IdentityAuthorization(
										idpIdent));
					}
					try {
						for (QName profileQName : ac
								.getSupportedAuthenticationProfiles()) {
							if (profileQName.toString().trim().equals(BASIC_AUTH_PROFILE)) {
								IdPBean bean = new IdPBean(
										idp.getDisplayName(), idpUrl);
								idpBeans.add(bean);
							}
						}
					} catch (Exception ex) {
						String msg = "Couldn't get profiles for: " + idpUrl
								+ "\n" + ex.getMessage();
						logger.warn(msg, ex);
					}
				} catch (Exception ex) {
					String msg = "Error connecting to " + idpUrl + ": "
							+ ex.getMessage();
					logger.warn(msg, ex);
				}
			}
		} catch (Exception ex) {
			logger.error("Error getting identity provider list: "
					+ ex.getMessage(), ex);
			throw new RuntimeException("Error getting identity provider list.",
					ex);
		}

		return idpBeans;
	}

	public String addIdP(String label, String url) {
{'fraction_non_alphanumeric': 0.12126537785588752, 'fraction_numerical': 0.0008787346221441124, 'mean_word_length': 4.126576576576577, 'pattern_counts': {'":': 4, '<': 34, '<?xml version=': 0, '>': 36, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 2}, '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': '3408751', 'n_tokens_mistral': 4238, 'n_tokens_neox': 3649, 'n_words': 708}