<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2014 OpenStack Foundation
#
# 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.

from keystone.common import sql
from keystone.common.sql import migration
from keystone.contrib.federation import core
from keystone import exception
from keystone.openstack.common.db.sqlalchemy import session as db_session
from keystone.openstack.common import jsonutils


class FederationProtocolModel(sql.ModelBase, sql.DictBase):
    __tablename__ = 'federation_protocol'
    attributes = ['id', 'idp_id', 'mapping_id']
    mutable_attributes = frozenset(['mapping_id'])

    id = sql.Column(sql.String(64), primary_key=True)
    idp_id = sql.Column(sql.String(64), sql.ForeignKey('identity_provider.id',
                        ondelete='CASCADE'), primary_key=True)
    mapping_id = sql.Column(sql.String(64), nullable=False)
    __table_args__ = (sql.UniqueConstraint('id', 'idp_id'), dict())

    @classmethod
    def from_dict(cls, dictionary):
        new_dictionary = dictionary.copy()
        return cls(**new_dictionary)

    def to_dict(self):
        """Return a dictionary with model's attributes."""
        d = dict()
        for attr in self.__class__.attributes:
            d[attr] = getattr(self, attr)
        return d


class IdentityProviderModel(sql.ModelBase, sql.DictBase):
    __tablename__ = 'identity_provider'
    attributes = ['id', 'enabled', 'description']
    mutable_attributes = frozenset(['description', 'enabled'])

    id = sql.Column(sql.String(64), primary_key=True)
    enabled = sql.Column(sql.Boolean, nullable=False)
    description = sql.Column(sql.Text(), nullable=True)

    @classmethod
    def from_dict(cls, dictionary):
        new_dictionary = dictionary.copy()
        return cls(**new_dictionary)

    def to_dict(self, include_extra_dict=False):
        """Return the model's attributes as a dictionary."""
        d = dict()
        for attr in self.__class__.attributes:
            d[attr] = getattr(self, attr)
        return d


class MappingModel(sql.ModelBase, sql.DictBase):
    __tablename__ = 'mapping'
    attributes = ['id', 'rules']

    id = sql.Column(sql.String(64), primary_key=True)
    rules = sql.Column(sql.JsonBlob(), nullable=False)

    @classmethod
    def from_dict(cls, dictionary):
        new_dictionary = dictionary.copy()
        return cls(**new_dictionary)

    def to_dict(self):
        """Return a dictionary with model's attributes."""
        d = dict()
        for attr in self.__class__.attributes:
            d[attr] = getattr(self, attr)
        return d


class Federation(sql.Base, core.Driver):

    def db_sync(self):
        migration.db_sync()

    # Identity Provider CRUD
    @sql.handle_conflicts(conflict_type='identity_provider')
    def create_idp(self, idp_id, idp):
        session = db_session.get_session()
        with session.begin():
            idp['id'] = idp_id
            idp_ref = IdentityProviderModel.from_dict(idp)
            session.add(idp_ref)
        return idp_ref.to_dict()

    def delete_idp(self, idp_id):
        session = db_session.get_session()
        with session.begin():
            idp_ref = self._get_idp(session, idp_id)
            q = session.query(IdentityProviderModel)
            q = q.filter_by(id=idp_id)
            q.delete(synchronize_session=False)
            session.delete(idp_ref)

    def _get_idp(self, session, idp_id):
        idp_ref = session.query(IdentityProviderModel).get(idp_id)
        if not idp_ref:
            raise exception.IdentityProviderNotFound(idp_id=idp_id)
        return idp_ref

    def list_idps(self):
        session = db_session.get_session()
        with session.begin():
            idps = session.query(IdentityProviderModel)
        idps_list = [idp.to_dict() for idp in idps]
        return idps_list

    def get_idp(self, idp_id):
        session = db_session.get_session()
        idp_ref = self._get_idp(session, idp_id)
        return idp_ref.to_dict()

    def update_idp(self, idp_id, idp):
        session = db_session.get_session()
        with session.begin():
            idp_ref = self._get_idp(session, idp_id)
            old_idp = idp_ref.to_dict()
            old_idp.update(idp)
            new_idp = IdentityProviderModel.from_dict(old_idp)
            for attr in IdentityProviderModel.mutable_attributes:
                setattr(idp_ref, attr, getattr(new_idp, attr))
        return idp_ref.to_dict()

    # Protocol CRUD
    def _get_protocol(self, session, idp_id, protocol_id):
        q = session.query(FederationProtocolModel)
        q = q.filter_by(id=protocol_id, idp_id=idp_id)
        try:
            return q.one()
        except sql.NotFound:
            kwargs = {'protocol_id': protocol_id,
                      'idp_id': idp_id}
            raise exception.FederatedProtocolNotFound(**kwargs)

    def _store_protocol(self, session, protocol_ref):
        try:
            session.add(protocol_ref)
        except sql.IntegrityError:
            raise exception.ValidationError()

    @sql.handle_conflicts(conflict_type='federation_protocol')
    def create_protocol(self, idp_id, protocol_id, protocol):
        session = db_session.get_session()
        with session.begin():<commit_msg>Remove unused method _store_protocol<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2014 OpenStack Foundation
#
# 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.

from keystone.common import sql
from keystone.common.sql import migration
from keystone.contrib.federation import core
from keystone import exception
from keystone.openstack.common.db.sqlalchemy import session as db_session
from keystone.openstack.common import jsonutils


class FederationProtocolModel(sql.ModelBase, sql.DictBase):
    __tablename__ = 'federation_protocol'
    attributes = ['id', 'idp_id', 'mapping_id']
    mutable_attributes = frozenset(['mapping_id'])

    id = sql.Column(sql.String(64), primary_key=True)
    idp_id = sql.Column(sql.String(64), sql.ForeignKey('identity_provider.id',
                        ondelete='CASCADE'), primary_key=True)
    mapping_id = sql.Column(sql.String(64), nullable=False)
    __table_args__ = (sql.UniqueConstraint('id', 'idp_id'), dict())

    @classmethod
    def from_dict(cls, dictionary):
        new_dictionary = dictionary.copy()
        return cls(**new_dictionary)

    def to_dict(self):
        """Return a dictionary with model's attributes."""
        d = dict()
        for attr in self.__class__.attributes:
            d[attr] = getattr(self, attr)
        return d


class IdentityProviderModel(sql.ModelBase, sql.DictBase):
    __tablename__ = 'identity_provider'
    attributes = ['id', 'enabled', 'description']
    mutable_attributes = frozenset(['description', 'enabled'])

    id = sql.Column(sql.String(64), primary_key=True)
    enabled = sql.Column(sql.Boolean, nullable=False)
    description = sql.Column(sql.Text(), nullable=True)

    @classmethod
    def from_dict(cls, dictionary):
        new_dictionary = dictionary.copy()
        return cls(**new_dictionary)

    def to_dict(self, include_extra_dict=False):
        """Return the model's attributes as a dictionary."""
        d = dict()
        for attr in self.__class__.attributes:
            d[attr] = getattr(self, attr)
        return d


class MappingModel(sql.ModelBase, sql.DictBase):
    __tablename__ = 'mapping'
    attributes = ['id', 'rules']

    id = sql.Column(sql.String(64), primary_key=True)
    rules = sql.Column(sql.JsonBlob(), nullable=False)

    @classmethod
    def from_dict(cls, dictionary):
        new_dictionary = dictionary.copy()
        return cls(**new_dictionary)

    def to_dict(self):
        """Return a dictionary with model's attributes."""
        d = dict()
        for attr in self.__class__.attributes:
            d[attr] = getattr(self, attr)
        return d


class Federation(sql.Base, core.Driver):

    def db_sync(self):
        migration.db_sync()

    # Identity Provider CRUD
    @sql.handle_conflicts(conflict_type='identity_provider')
    def create_idp(self, idp_id, idp):
        session = db_session.get_session()
        with session.begin():
            idp['id'] = idp_id
            idp_ref = IdentityProviderModel.from_dict(idp)
            session.add(idp_ref)
        return idp_ref.to_dict()

    def delete_idp(self, idp_id):
        session = db_session.get_session()
        with session.begin():
            idp_ref = self._get_idp(session, idp_id)
            q = session.query(IdentityProviderModel)
            q = q.filter_by(id=idp_id)
            q.delete(synchronize_session=False)
            session.delete(idp_ref)

    def _get_idp(self, session, idp_id):
        idp_ref = session.query(IdentityProviderModel).get(idp_id)
        if not idp_ref:
            raise exception.IdentityProviderNotFound(idp_id=idp_id)
        return idp_ref

    def list_idps(self):
        session = db_session.get_session()
        with session.begin():
            idps = session.query(IdentityProviderModel)
        idps_list = [idp.to_dict() for idp in idps]
        return idps_list

    def get_idp(self, idp_id):
        session = db_session.get_session()
        idp_ref = self._get_idp(session, idp_id)
        return idp_ref.to_dict()

    def update_idp(self, idp_id, idp):
        session = db_session.get_session()
        with session.begin():
            idp_ref = self._get_idp(session, idp_id)
            old_idp = idp_ref.to_dict()
            old_idp.update(idp)
            new_idp = IdentityProviderModel.from_dict(old_idp)
            for attr in IdentityProviderModel.mutable_attributes:
                setattr(idp_ref, attr, getattr(new_idp, attr))
        return idp_ref.to_dict()

    # Protocol CRUD
    def _get_protocol(self, session, idp_id, protocol_id):
        q = session.query(FederationProtocolModel)
        q = q.filter_by(id=protocol_id, idp_id=idp_id)
        try:
            return q.one()
        except sql.NotFound:
            kwargs = {'protocol_id': protocol_id,
                      'idp_id': idp_id}
            raise exception.FederatedProtocolNotFound(**kwargs)

    @sql.handle_conflicts(conflict_type='federation_protocol')
    def create_protocol(self, idp_id, protocol_id, protocol):
        session = db_session.get_session()
        with session.begin():
{'fraction_non_alphanumeric': 0.10152819251712629, 'fraction_numerical': 0.003688740558580713, 'mean_word_length': 2.959318497913769, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, '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': '4729028', 'n_tokens_mistral': 3519, 'n_tokens_neox': 3399, 'n_words': 806}