You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by co...@apache.org on 2017/01/27 11:22:44 UTC

[01/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Repository: cxf-fediz
Updated Branches:
  refs/heads/master f9c0026d7 -> 15690cad1


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPATest.java b/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPATest.java
deleted file mode 100644
index 4a2970c..0000000
--- a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPATest.java
+++ /dev/null
@@ -1,348 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.net.URI;
-import java.util.Arrays;
-import java.util.List;
-
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
-import org.apache.cxf.fediz.service.idp.service.ApplicationDAO;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.EmptyResultDataAccessException;
-import org.springframework.orm.jpa.JpaObjectRetrievalFailureException;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.util.Assert;
-
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = { "classpath:testContext.xml" })
-public class ApplicationDAOJPATest {
-
-    @Autowired
-    private ApplicationDAO applicationDAO;
-    
-    
-    @BeforeClass
-    public static void init() {
-        System.setProperty("spring.profiles.active", "jpa");
-    }
-    
-    
-    @Test
-    public void testReadAllApplications() {
-        List<Application> applications = applicationDAO.getApplications(0, 999, null);
-        // Application could have been removed, Order not given as per JUnit design
-        Assert.isTrue(1 < applications.size(), "Size doesn't match [" + applications.size() + "]");
-    }
-    
-    
-    @Test
-    public void testReadExistingApplicationEmbeddedAll() {
-        Application application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld",
-                                                                Arrays.asList("all"));
-        
-        Assert.isTrue(application.getLifeTime() == 3600,
-                      "LifeTime doesn't match");
-        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(application.getProtocol()),
-                      "Protocol doesn't match");
-        Assert.isTrue("urn:org:apache:cxf:fediz:fedizhelloworld".equals(application.getRealm()),
-                      "Realm doesn't match");
-        Assert.isTrue("ApplicationServiceType".equals(application.getRole()),
-                      "Role doesn't match");
-        Assert.isTrue("Web Application to illustrate WS-Federation".equals(application.getServiceDescription()),
-                      "ServiceDescription doesn't match");
-        Assert.isTrue("Fedizhelloworld".equals(application.getServiceDisplayName()),
-                      "ServiceDisplayName doesn't match");
-        Assert.isTrue("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
-                      .equals(application.getTokenType()),
-                      "TokenType doesn't match");
-        Assert.isTrue(4 == application.getRequestedClaims().size(),
-                      "Number of claims doesn't match [" + application.getRequestedClaims().size() + "]");
-    }
-    
-    @Test
-    public void testReadExistingApplicationEmbeddedClaims() {
-        Application application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld",
-                                                                Arrays.asList("claims"));
-        
-        Assert.isTrue(4 == application.getRequestedClaims().size(),
-                      "Number of claims doesn't match");
-    }
-    
-    @Test
-    public void testReadExistingApplicationEmbeddedNull() {
-        Application application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld",
-                                                                null);
-        
-        Assert.isTrue(0 == application.getRequestedClaims().size(),
-                      "Number of claims doesn't match");
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryReadNonexistingApplication() {
-        applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld:NOTEXIST", null);
-    }
-    
-    
-    @Test
-    public void testAddNewApplication() {
-        
-        String realm = "urn:org:apache:cxf:fediz:application:testaddnew";
-        Application application = createApplication(realm);
-        applicationDAO.addApplication(application);
-        
-        application = applicationDAO.getApplication(realm, null);
-        
-        Assert.isTrue("".equals(application.getEncryptionCertificate()),
-                      "EncryptionCertificate doesn't match");
-        Assert.isTrue(application.getLifeTime() == 3600,
-                      "LifeTime doesn't match");
-        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(application.getProtocol()),
-                      "Protocol doesn't match");
-        Assert.isTrue(realm.equals(application.getRealm()),
-                      "Realm doesn't match");
-        Assert.isTrue("ApplicationServiceType".equals(application.getRole()),
-                      "Role doesn't match");
-        Assert.isTrue("Fedizhelloworld2 description".equals(application.getServiceDescription()),
-                      "ServiceDescription doesn't match");
-        Assert.isTrue("Fedizhelloworld2".equals(application.getServiceDisplayName()),
-                      "ServiceDisplayName doesn't match");
-        Assert.isTrue("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"
-                      .equals(application.getTokenType()),
-                      "TokenType doesn't match");
-        Assert.isTrue("http://www.w3.org/ns/ws-policy"
-                      .equals(application.getPolicyNamespace()),
-                      "Policy Namespace doesn't match");
-        Assert.isTrue(0 == application.getRequestedClaims().size(),
-                      "Number of claims doesn't match");
-    }
-    
-    @Test
-    public void testUpdateApplication() {
-        String realm = "urn:org:apache:cxf:fediz:application:testupdate";
-        
-        //Prepare
-        Application application = createApplication(realm);
-        applicationDAO.addApplication(application);
-        
-        //Testcase
-        application = new Application();
-        application.setRealm(realm);
-        application.setEncryptionCertificate("U");
-        application.setLifeTime(1800);
-        application.setProtocol("Uhttp://docs.oasis-open.org/wsfed/federation/200706");
-        application.setRole("UApplicationServiceType");
-        application.setServiceDescription("UFedizhelloworld2 description");
-        application.setServiceDisplayName("UFedizhelloworld2");
-        application.setTokenType("Uhttp://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1");
-        application.setPolicyNamespace("Uhttp://www.w3.org/ns/ws-policy");
-        
-        Assert.isTrue("U".equals(application.getEncryptionCertificate()),
-                      "EncryptionCertificate doesn't match");
-        Assert.isTrue(application.getLifeTime() == 1800,
-                      "LifeTime doesn't match");
-        Assert.isTrue("Uhttp://docs.oasis-open.org/wsfed/federation/200706".equals(application.getProtocol()),
-                      "Protocol doesn't match");
-        Assert.isTrue(realm.equals(application.getRealm()),
-                      "Realm doesn't match");
-        Assert.isTrue("UApplicationServiceType".equals(application.getRole()),
-                      "Role doesn't match");
-        Assert.isTrue("UFedizhelloworld2 description".equals(application.getServiceDescription()),
-                      "ServiceDescription doesn't match");
-        Assert.isTrue("UFedizhelloworld2".equals(application.getServiceDisplayName()),
-                      "ServiceDisplayName doesn't match");
-        Assert.isTrue("Uhttp://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"
-                      .equals(application.getTokenType()),
-                      "TokenType doesn't match");
-        Assert.isTrue("Uhttp://www.w3.org/ns/ws-policy"
-                      .equals(application.getPolicyNamespace()),
-                      "Policy Namespace doesn't match");
-        Assert.isTrue(0 == application.getRequestedClaims().size(),
-                      "Number of claims doesn't match");
-    }
-    
-    @Test(expected = DataIntegrityViolationException.class)
-    public void testTryAddExistingApplication() {
-        Application application = new Application();
-        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
-        application.setEncryptionCertificate("");
-        application.setLifeTime(3600);
-        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-        application.setRole("ApplicationServiceType");
-        application.setServiceDescription("Fedizhelloworld description");
-        application.setServiceDisplayName("Fedizhelloworld");
-        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
-        
-        applicationDAO.addApplication(application);
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryRemoveUnknownApplication() {
-        applicationDAO.deleteApplication("urn:org:apache:cxf:fediz:fedizhelloworld:NOTEXIST");
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testRemoveExistingApplication() {
-        String realm = "urn:org:apache:cxf:fediz:app:testdelete";
-        Application application = createApplication(realm);
-        
-        applicationDAO.addApplication(application);
-        
-        applicationDAO.deleteApplication(realm);
-        
-        applicationDAO.getApplication(realm, null);
-    }
-    
-    @Test
-    public void testAddClaimToApplication() {
-        //Prepare step
-        Application application = new Application();
-        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld:testaddclaim");
-        application.setEncryptionCertificate("");
-        application.setLifeTime(3600);
-        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-        application.setRole("ApplicationServiceType");
-        application.setServiceDescription("Fedizhelloworld description");
-        application.setServiceDisplayName("Fedizhelloworld");
-        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
-        
-        applicationDAO.addApplication(application);
-        
-        //Testcase
-        RequestClaim requestClaim = new RequestClaim();
-        requestClaim.setOptional(false);
-        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
-        
-        applicationDAO.addClaimToApplication(application, requestClaim);
-               
-        application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld:testaddclaim",
-                                                    Arrays.asList("all"));
-        
-        Assert.isTrue(1 == application.getRequestedClaims().size(), "requestedClaims size doesn't match");
-    }
-    
-    @Test(expected = DataIntegrityViolationException.class)
-    public void testTryAddExistingClaimToApplication() {
-        Application application = new Application();
-        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
-        
-        RequestClaim requestClaim = new RequestClaim();
-        requestClaim.setOptional(false);
-        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
-        
-        applicationDAO.addClaimToApplication(application, requestClaim);
-    }
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryAddUnknownClaimToApplication() {
-        Application application = new Application();
-        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
-        
-        RequestClaim requestClaim = new RequestClaim();
-        requestClaim.setOptional(false);
-        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/UNKOWN"));
-        
-        applicationDAO.addClaimToApplication(application, requestClaim);
-    }
-    
-    
-    @Test
-    public void testRemoveClaimFromApplication() {
-        //Prepare step
-        Application application = new Application();
-        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld:testremoveclaim");
-        application.setEncryptionCertificate("");
-        application.setLifeTime(3600);
-        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-        application.setRole("ApplicationServiceType");
-        application.setServiceDescription("Fedizhelloworld description");
-        application.setServiceDisplayName("Fedizhelloworld");
-        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
-        
-        applicationDAO.addApplication(application);
-        
-        RequestClaim requestClaim = new RequestClaim();
-        requestClaim.setOptional(false);
-        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
-        
-        applicationDAO.addClaimToApplication(application, requestClaim);
-               
-        application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld:testremoveclaim",
-                                                    Arrays.asList("all"));
-        Assert.isTrue(1 == application.getRequestedClaims().size(), "requestedClaims size doesn't match");
-        
-        //Testcase
-        applicationDAO.removeClaimFromApplication(application, requestClaim);
-        application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld:testremoveclaim",
-                                                    Arrays.asList("all"));
-        Assert.isTrue(0 == application.getRequestedClaims().size(), "requestedClaims size doesn't match");
-    }
-    
-    @Test(expected = JpaObjectRetrievalFailureException.class)
-    public void testTryRemoveNotAssignedClaimFromApplication() {
-        Application application = new Application();
-        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
-                
-        RequestClaim requestClaim = new RequestClaim();
-        requestClaim.setOptional(false);
-        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/city"));
-        
-        applicationDAO.removeClaimFromApplication(application, requestClaim);
-    }
-    
-    @Test(expected = JpaObjectRetrievalFailureException.class)
-    public void testTryRemoveUnknownClaimFromApplication() {
-        Application application = new Application();
-        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
-                
-        RequestClaim requestClaim = new RequestClaim();
-        requestClaim.setOptional(false);
-        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/UNKNOWN"));
-        
-        applicationDAO.removeClaimFromApplication(application, requestClaim);
-    }
-    
-    private static Application createApplication(String realm) {
-        Application application = new Application();
-        application.setRealm(realm);
-        application.setEncryptionCertificate("");
-        application.setLifeTime(3600);
-        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-        application.setRole("ApplicationServiceType");
-        application.setServiceDescription("Fedizhelloworld2 description");
-        application.setServiceDisplayName("Fedizhelloworld2");
-        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1");
-        application.setPolicyNamespace("http://www.w3.org/ns/ws-policy");
-        return application;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPATest.java b/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPATest.java
deleted file mode 100644
index 767a989..0000000
--- a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPATest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.net.URI;
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.EmptyResultDataAccessException;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.util.Assert;
-
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = { "classpath:testContext.xml" })
-public class ClaimDAOJPATest {
-
-    @Autowired
-    private ClaimDAO claimDAO;
-    
-    
-    @BeforeClass
-    public static void init() {
-        System.setProperty("spring.profiles.active", "jpa");
-    }
-    
-    
-    @Test
-    public void testReadAllClaims() {
-        List<Claim> claims = claimDAO.getClaims(0, 999);
-        Assert.isTrue(5 == claims.size(), "Size doesn't match");
-    }
-    
-    @Test
-    public void testReadExistingClaim() {
-        Claim claim = claimDAO.getClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname");
-        Assert.isTrue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"
-                      .equals(claim.getClaimType().toString()),
-                      "ClaimType doesn't match");
-        Assert.isTrue("firstname".equals(claim.getDisplayName()),
-                      "Claim Display name doesn't match");
-        Assert.isTrue("Description for firstname".equals(claim.getDescription()),
-                      "Claim Description name doesn't match");
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryReadNonexistingClaim() {
-        claimDAO.getClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givennamenotexist");
-    }
-    
-    
-    @Test
-    public void testAddNewClaim() {
-        Claim claim5 = new Claim();
-        claim5.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/town"));
-        claim5.setDisplayName("Town");
-        claim5.setDescription("Town Description");
-        claimDAO.addClaim(claim5);
-        
-        List<Claim> claims = claimDAO.getClaims(0, 999);
-        Assert.isTrue(6 == claims.size(), "Size doesn't match. Claim not added");
-    }
-    
-    
-    @Test(expected = DataIntegrityViolationException.class)
-    public void testTryAddExistingClaim() {
-        Claim claim5 = new Claim();
-        claim5.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
-        claim5.setDisplayName("firstname");
-        claim5.setDescription("Description for firstname");
-        claimDAO.addClaim(claim5);
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryRemoveUnknownClaim() {
-        claimDAO.deleteClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/town/WRONG");
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testRemoveExistingClaim() {
-        claimDAO.deleteClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email");
-        
-        claimDAO.getClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email");
-    }
-    
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPATest.java b/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPATest.java
deleted file mode 100644
index 1d63fde..0000000
--- a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPATest.java
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-import org.apache.cxf.fediz.service.idp.service.EntitlementDAO;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.EmptyResultDataAccessException;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.util.Assert;
-
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = { "classpath:testContext.xml" })
-public class EntitlementDAOJPATest {
-
-    @Autowired
-    private EntitlementDAO entitlementDAO;
-    
-    
-    @BeforeClass
-    public static void init() {
-        System.setProperty("spring.profiles.active", "jpa");
-    }
-    
-    
-    @Test
-    public void testReadAllEntitlements() {
-        List<Entitlement> entitlements = entitlementDAO.getEntitlements(0, 999);
-        Assert.isTrue(30 == entitlements.size(), "Size doesn't match");
-    }
-    
-    @Test
-    public void testReadExistingEntitlement() {
-        Entitlement entitlement = entitlementDAO.getEntitlement("CLAIM_LIST");
-        Assert.isTrue("CLAIM_LIST".equals(entitlement.getName()),
-                      "Entitlement name doesn't match");
-        Assert.isTrue("Description for CLAIM_LIST".equals(entitlement.getDescription()),
-                      "Entitlement Description doesn't match");
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryReadNonexistingEntitlement() {
-        entitlementDAO.getEntitlement("CLAIM_NOT_EXIST");
-    }
-    
-    
-    @Test
-    public void testAddNewEntitlement() {
-        Entitlement entitlement5 = new Entitlement();
-        entitlement5.setName("GUGUS_CREATE");
-        entitlement5.setDescription("Any entitlement");
-        entitlementDAO.addEntitlement(entitlement5);
-        
-        List<Entitlement> entitlements = entitlementDAO.getEntitlements(0, 999);
-        Assert.isTrue(31 == entitlements.size(), "Size doesn't match. Entitlement not added");
-    }
-    
-    
-    @Test(expected = DataIntegrityViolationException.class)
-    public void testTryAddExistingEntitlement() {
-        Entitlement entitlement5 = new Entitlement();
-        entitlement5.setName("CLAIM_DELETE");
-        entitlement5.setDescription("Description for CLAIM_DELETE");
-        entitlementDAO.addEntitlement(entitlement5);
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryRemoveUnknownEntitlement() {
-        entitlementDAO.deleteEntitlement("GUGUS_NOT_EXIST");
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testRemoveExistingEntitlement() {
-        
-        Entitlement entitlement5 = new Entitlement();
-        entitlement5.setName("CLAIM_TO_DELETE");
-        entitlement5.setDescription("Description for CLAIM_TO_DELETE");
-        entitlementDAO.addEntitlement(entitlement5);
-        
-        entitlementDAO.deleteEntitlement("CLAIM_TO_DELETE");
-        
-        entitlementDAO.getEntitlement("CLAIM_TO_DELETE");
-    }
-    
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPATest.java b/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPATest.java
deleted file mode 100644
index 6256371..0000000
--- a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPATest.java
+++ /dev/null
@@ -1,653 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.service.IdpDAO;
-import org.apache.wss4j.dom.WSConstants;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.EmptyResultDataAccessException;
-import org.springframework.orm.jpa.JpaObjectRetrievalFailureException;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.util.Assert;
-
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = { "classpath:testContext.xml" })
-public class IdpDAOJPATest {
-
-    @Autowired
-    private IdpDAO idpDAO;
-    
-    
-    @BeforeClass
-    public static void init() {
-        System.setProperty("spring.profiles.active", "jpa");
-    }
-    
-    
-    @Test
-    public void testReadAllIdps() {
-        List<Idp> idps = idpDAO.getIdps(0, 999, null);
-        // Idp could have been removed, Order not given as per JUnit design
-        Assert.isTrue(0 < idps.size(), "Size doesn't match [" + idps.size() + "]");
-    }
-    
-    
-    @Test
-    public void testReadExistingIdpEmbeddedAll() throws MalformedURLException {
-        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A", Arrays.asList("all"));
-        
-        Assert.isTrue("stsKeystoreA.properties".equals(idp.getCertificate()),
-                      "Certificate doesn't match");
-        Assert.isTrue("realma".equals(idp.getCertificatePassword()),
-                      "Certificate password doesn't match");
-        Assert.isTrue("urn:org:apache:cxf:fediz:idp:realm-A".equals(idp.getRealm()),
-                      "Realm doesn't match");
-        Assert.isTrue("IDP of Realm A".equals(idp.getServiceDescription()),
-                      "ServiceDescription doesn't match");
-        Assert.isTrue("REALM A".equals(idp.getServiceDisplayName()),
-                      "ServiceDisplayName doesn't match");        
-        Assert.isTrue(new URL("https://localhost:9443/fediz-idp/federation").equals(idp.getIdpUrl()),
-                      "IdpUrl doesn't match");
-        Assert.isTrue(new URL("https://localhost:9443/fediz-idp-sts/REALMA").equals(idp.getStsUrl()),
-                      "StsUrl doesn't match");
-        Assert.isTrue("realma".equals(idp.getUri()),
-                      "Uri doesn't match");
-        Assert.isTrue(idp.isProvideIdpList(),
-                      "ProvideIDPList doesn't match");
-        Assert.isTrue(idp.isUseCurrentIdp(),
-                      "UseCurrentIDP doesn't match");
-        Assert.isTrue(4 == idp.getAuthenticationURIs().size(),
-                      "Number of AuthenticationURIs doesn't match");
-        Assert.isTrue(2 == idp.getSupportedProtocols().size(),
-                      "Number of SupportedProtocols doesn't match");
-        Assert.isTrue(2 == idp.getTokenTypesOffered().size(),
-                      "Number of TokenTypesOffered doesn't match");
-        Assert.isTrue(2 == idp.getApplications().size(),
-                      "Number of applications doesn't match");
-        Assert.isTrue(1 == idp.getTrustedIdps().size(),
-                      "Number of trusted IDPs doesn't match");
-        Assert.isTrue(4 == idp.getClaimTypesOffered().size(),
-                      "Number of claims doesn't match");
-    }
-    
-    @Test
-    public void testReadExistingIdpEmbeddedTrustedIdps() {
-        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A",
-                                                                Arrays.asList("trusted-idps"));
-        
-        Assert.isTrue(1 == idp.getTrustedIdps().size(),
-                      "Number of trusted IDPs doesn't match");
-    }
-    
-    @Test
-    public void testReadExistingIdpEmbeddedClaims() {
-        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A",
-                                                                Arrays.asList("claims"));
-        
-        Assert.isTrue(4 == idp.getClaimTypesOffered().size(),
-                      "Number of claims doesn't match");
-    }
-    
-    @Test
-    public void testReadExistingIdpEmbeddedApplications() {
-        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A", Arrays.asList("applications"));
-        
-        Assert.isTrue(2 == idp.getApplications().size(), "Number of applications doesn't match");
-    }
-    
-    @Test
-    public void testReadExistingIdpEmbeddedNull() {
-        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A",
-                                                                null);
-        
-        Assert.isTrue(0 == idp.getClaimTypesOffered().size(),
-                      "Number of claims doesn't match");
-        Assert.isTrue(0 == idp.getApplications().size(),
-                      "Number of applications doesn't match");
-        Assert.isTrue(0 == idp.getTrustedIdps().size(),
-                      "Number of trusted IDPs doesn't match");
-       
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryReadNonexistingIdp() {
-        idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:NOTEXIST", null);
-    }
-    
-    
-    @Test
-    public void testAddNewIdp() throws MalformedURLException {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:testadd");
-        idp.setCertificate("stsKeystoreA.properties");
-        idp.setCertificatePassword("realma");
-        idp.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federation"));
-        idp.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMN"));
-        idp.setServiceDisplayName("NEW REALM");
-        idp.setServiceDescription("IDP of New Realm");
-        idp.setUri("realmn");
-        idp.setProvideIdpList(true);
-        Map<String, String> authUris = new HashMap<>();
-        authUris.put("default", "/login/default");
-        idp.setAuthenticationURIs(authUris);
-        List<String> protocols = new ArrayList<>();
-        protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
-        protocols.add("http://docs.oasis-open.org/ws-sx/ws-trust/200512");
-        idp.setSupportedProtocols(protocols);
-        List<String> tokenTypes = new ArrayList<>();
-        tokenTypes.add(WSConstants.SAML2_NS);
-        tokenTypes.add(WSConstants.SAML_NS);
-        idp.setTokenTypesOffered(tokenTypes);
-        idp.setUseCurrentIdp(true);
-        
-        idpDAO.addIdp(idp);
-        
-        idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:testadd", null);
-        
-        Assert.isTrue("stsKeystoreA.properties".equals(idp.getCertificate()),
-                      "Certificate doesn't match");
-        Assert.isTrue("realma".equals(idp.getCertificatePassword()),
-                      "Certificate password doesn't match");
-        Assert.isTrue("urn:org:apache:cxf:fediz:idp:testadd".equals(idp.getRealm()),
-                      "Realm doesn't match");
-        Assert.isTrue("IDP of New Realm".equals(idp.getServiceDescription()),
-                      "ServiceDescription doesn't match");
-        Assert.isTrue("NEW REALM".equals(idp.getServiceDisplayName()),
-                      "ServiceDisplayName doesn't match");        
-        Assert.isTrue(new URL("https://localhost:9443/fediz-idp/federation").equals(idp.getIdpUrl()),
-                      "IdpUrl doesn't match");
-        Assert.isTrue(new URL("https://localhost:9443/fediz-idp-sts/REALMN").equals(idp.getStsUrl()),
-                      "StsUrl doesn't match");
-        Assert.isTrue("realmn".equals(idp.getUri()),
-                      "Uri doesn't match");
-        Assert.isTrue(idp.isProvideIdpList(),
-                      "ProvideIDPList doesn't match");
-        Assert.isTrue(idp.isUseCurrentIdp(),
-                      "UseCurrentIDP doesn't match");
-        Assert.isTrue(1 == idp.getAuthenticationURIs().size(),
-                      "Number of AuthenticationURIs doesn't match");
-        Assert.isTrue(2 == idp.getSupportedProtocols().size(),
-                      "Number of SupportedProtocols doesn't match");
-        Assert.isTrue(2 == idp.getTokenTypesOffered().size(),
-                      "Number of TokenTypesOffered doesn't match");
-        Assert.isTrue(0 == idp.getApplications().size(),
-                      "Number of applications doesn't match");
-        Assert.isTrue(0 == idp.getTrustedIdps().size(),
-                      "Number of trusted IDPs doesn't match");
-        Assert.isTrue(0 == idp.getClaimTypesOffered().size(),
-                      "Number of claims doesn't match");
-
-    }
-    
-    
-    @Test(expected = DataIntegrityViolationException.class)
-    public void testTryAddExistingIdp() throws MalformedURLException {
-        Idp idp = createIdp("urn:org:apache:cxf:fediz:idp:realm-A");
-        idpDAO.addIdp(idp);
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryRemoveUnknownIdp() {
-        idpDAO.deleteIdp("urn:org:apache:cxf:fediz:idp:NOTEXIST");
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testRemoveExistingIdp() throws MalformedURLException {
-        Idp idp = createIdp("urn:org:apache:cxf:fediz:idp:testdelete");
-        
-        idpDAO.addIdp(idp);
-        
-        idpDAO.deleteIdp("urn:org:apache:cxf:fediz:idp:testdelete");
-        
-        idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:testdelete", null);
-    }
-    
-    @Test
-    public void testUpdateIdp() throws MalformedURLException {
-        String realm = "urn:org:apache:cxf:fediz:idp:testupdate";
-        //Prepare
-        Idp idp = createIdp(realm);
-        idpDAO.addIdp(idp);
-        
-        //Testcase
-        idp = new Idp();
-        idp.setRealm(realm);
-        idp.setCertificate("UstsKeystoreA.properties");
-        idp.setCertificatePassword("Urealma");
-        idp.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federationUU"));
-        idp.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMAUU"));
-        idp.setServiceDisplayName("UNEW REALM");
-        idp.setServiceDescription("UIDP of New Realm");
-        idp.setUri("Urealmn");
-        idp.setProvideIdpList(true);
-        Map<String, String> authUris = new HashMap<>();
-        authUris.put("default", "/login/default");
-        idp.setAuthenticationURIs(authUris);
-        List<String> protocols = new ArrayList<>();
-        protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
-        idp.setSupportedProtocols(protocols);
-        List<String> tokenTypes = new ArrayList<>();
-        tokenTypes.add(WSConstants.SAML2_NS);
-        idp.setTokenTypesOffered(tokenTypes);
-        idp.setUseCurrentIdp(false);
-        idpDAO.updateIdp(realm, idp);
-        
-        idp = idpDAO.getIdp(realm, null);
-        
-        Assert.isTrue("UstsKeystoreA.properties".equals(idp.getCertificate()),
-                      "Certificate doesn't match");
-        Assert.isTrue("Urealma".equals(idp.getCertificatePassword()),
-                      "Certificate password doesn't match");
-        Assert.isTrue(realm.equals(idp.getRealm()),
-                      "Realm doesn't match");
-        Assert.isTrue("UIDP of New Realm".equals(idp.getServiceDescription()),
-                      "ServiceDescription doesn't match");
-        Assert.isTrue("UNEW REALM".equals(idp.getServiceDisplayName()),
-                      "ServiceDisplayName doesn't match");        
-        Assert.isTrue(new URL("https://localhost:9443/fediz-idp/federationUU").equals(idp.getIdpUrl()),
-                      "IdpUrl doesn't match");
-        Assert.isTrue(new URL("https://localhost:9443/fediz-idp-sts/REALMAUU").equals(idp.getStsUrl()),
-                      "StsUrl doesn't match");
-        Assert.isTrue("Urealmn".equals(idp.getUri()),
-                      "Uri doesn't match");
-        Assert.isTrue(idp.isProvideIdpList(),
-                      "ProvideIDPList doesn't match");
-        Assert.isTrue(!idp.isUseCurrentIdp(),
-                      "UseCurrentIDP doesn't match");
-        Assert.isTrue(1 == idp.getAuthenticationURIs().size(),
-                      "Number of AuthenticationURIs doesn't match");
-        Assert.isTrue(1 == idp.getSupportedProtocols().size(),
-                      "Number of SupportedProtocols doesn't match");
-        Assert.isTrue(1 == idp.getTokenTypesOffered().size(),
-                      "Number of TokenTypesOffered doesn't match");
-        Assert.isTrue(0 == idp.getApplications().size(),
-                      "Number of applications doesn't match");
-        Assert.isTrue(0 == idp.getTrustedIdps().size(),
-                      "Number of trusted IDPs doesn't match");
-        Assert.isTrue(0 == idp.getClaimTypesOffered().size(),
-                      "Number of claims doesn't match");
-        
-    }
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testUpdateUnknownIdp() throws MalformedURLException {
-        String realm = "urn:org:apache:cxf:fediz:idp:testupdate2";
-        
-        //Prepare
-        Idp idp = createIdp(realm);
-        idpDAO.addIdp(idp);
-        
-        //Testcase
-        idp = new Idp();
-        idp.setRealm(realm);
-        idp.setCertificate("UstsKeystoreA.properties");
-        idp.setCertificatePassword("Urealma");
-        idp.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federationUU"));
-        idp.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMNUU"));
-        idp.setServiceDisplayName("UNEW REALM");
-        idp.setServiceDescription("UIDP of New Realm");
-        idp.setUri("Urealmn");
-        idp.setProvideIdpList(true);
-        Map<String, String> authUris = new HashMap<>();
-        authUris.put("default", "/login/default");
-        idp.setAuthenticationURIs(authUris);
-        List<String> protocols = new ArrayList<>();
-        protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
-        idp.setSupportedProtocols(protocols);
-        List<String> tokenTypes = new ArrayList<>();
-        tokenTypes.add(WSConstants.SAML2_NS);
-        idp.setTokenTypesOffered(tokenTypes);
-        idp.setUseCurrentIdp(false);
-        idpDAO.updateIdp("urn:UNKNOWN", idp);
-    }
-    
-    @Test
-    public void testAddClaimToIdp() throws MalformedURLException {
-        String realm = "urn:org:apache:cxf:fediz:idp:testaddclaim";
-        
-        //Prepare
-        Idp idp = createIdp(realm);
-        idpDAO.addIdp(idp);
-        
-        //Testcase
-        Claim claim = new Claim();
-        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
-        
-        idpDAO.addClaimToIdp(idp, claim);
-               
-        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        
-        Assert.isTrue(1 == idp.getClaimTypesOffered().size(), "claimTypesOffered size doesn't match");
-    }
-    
-    @Test(expected = DataIntegrityViolationException.class)
-    public void testTryAddExistingClaimToIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-        
-        Claim claim = new Claim();
-        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
-        
-        idpDAO.addClaimToIdp(idp, claim);
-    }
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryAddUnknownClaimToIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-        
-        Claim claim = new Claim();
-        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/UNKOWN"));
-        
-        idpDAO.addClaimToIdp(idp, claim);
-        
-    }
-    
-    @Test
-    public void testRemoveClaimFromIdp() throws MalformedURLException {
-        String realm = "urn:org:apache:cxf:fediz:fedizhelloworld:testremoveclaim";
-        //Prepare step
-        Idp idp = createIdp(realm);
-        idpDAO.addIdp(idp);
-        
-        Claim claim = new Claim();
-        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
-        idpDAO.addClaimToIdp(idp, claim);
-               
-        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        Assert.isTrue(1 == idp.getClaimTypesOffered().size(),
-                      "claimTypesOffered size doesn't match [" + idp.getClaimTypesOffered().size() + "]");
-        
-        //Testcase
-        idpDAO.removeClaimFromIdp(idp, claim);
-        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        Assert.isTrue(0 == idp.getClaimTypesOffered().size(),
-                      "claimTypesOffered size doesn't match [" + idp.getClaimTypesOffered().size() + "]");
-    }
-    
-    @Test(expected = JpaObjectRetrievalFailureException.class)
-    public void testTryRemoveNotAssignedClaimFromIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-                
-        Claim claim = new Claim();
-        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/city"));
-        
-        idpDAO.removeClaimFromIdp(idp, claim);
-    }
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryRemoveUnknownClaimFromIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-                
-        Claim claim = new Claim();
-        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/UNKNOWN"));
-        
-        idpDAO.removeClaimFromIdp(idp, claim);
-    }
-    
-    @Test
-    public void testAddApplicationToIdp() throws MalformedURLException {
-        String realm = "urn:org:apache:cxf:fediz:app:testaddApplication";
-        
-        //Prepare
-        Idp idp = createIdp(realm);
-        idpDAO.addIdp(idp);
-        
-        //Testcase
-        //Application app = createApplication(realm);
-        Application app = new Application();
-        app.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
-        idpDAO.addApplicationToIdp(idp, app);
-               
-        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        
-        Assert.isTrue(1 == idp.getApplications().size(), "applications size doesn't match");
-    }
-    
-    
-    @Test(expected = DataIntegrityViolationException.class)
-    public void testTryAddExistingApplicationToIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-        
-        Application app = new Application();
-        app.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
-        
-        idpDAO.addApplicationToIdp(idp, app);
-    }
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryAddUnknownApplicationToIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-        
-        Application app = new Application();
-        app.setRealm("urn:org:apache:cxf:fediz:UNKNOWN");
-        
-        idpDAO.addApplicationToIdp(idp, app);
-        
-    }
-    
-    @Test
-    public void testRemoveApplicationFromIdp() throws MalformedURLException {
-        String realm = "urn:org:apache:cxf:fediz:fedizhelloworld:testremoveapp";
-        //Prepare step
-        Idp idp = createIdp(realm);
-        idpDAO.addIdp(idp);
-        
-        Application app = new Application();
-        app.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
-        idpDAO.addApplicationToIdp(idp, app);
-               
-        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        Assert.isTrue(1 == idp.getApplications().size(),
-                      "applications size doesn't match [" + idp.getApplications().size() + "]");
-        
-        //Testcase
-        idpDAO.removeApplicationFromIdp(idp, app);
-        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        Assert.isTrue(0 == idp.getApplications().size(),
-                      "applications size doesn't match [" + idp.getApplications().size() + "]");
-    }
-    
-    
-    @Test(expected = JpaObjectRetrievalFailureException.class)
-    public void testTryRemoveNotAssignedApplicationFromIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-                
-        Application app = new Application();
-        app.setRealm("myrealm2");
-        
-        idpDAO.removeApplicationFromIdp(idp, app);
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryRemoveUnknownApplicationFromIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-                
-        Application app = new Application();
-        app.setRealm("urn:org:apache:cxf:fediz:UNKNOWN");
-        
-        idpDAO.removeApplicationFromIdp(idp, app);
-    }
-    
-    
-    
-    
-    
-    
-    @Test
-    public void testAddTrustedIdpToIdp() throws MalformedURLException {
-        String realm = "urn:org:apache:cxf:fediz:trusted-idp:testaddTrustedIdp";
-        
-        //Prepare
-        Idp idp = createIdp(realm);
-        idpDAO.addIdp(idp);
-        
-        //Testcase
-        //Application app = createApplication(realm);
-        TrustedIdp trustedIdp = new TrustedIdp();
-        trustedIdp.setRealm("urn:org:apache:cxf:fediz:idp:realm-B");
-        idpDAO.addTrustedIdpToIdp(idp, trustedIdp);
-               
-        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        
-        Assert.isTrue(1 == idp.getTrustedIdps().size(), "applications size doesn't match");
-    }
-    
-    /*
-    @Test(expected = DataIntegrityViolationException.class)
-    public void testTryAddExistingTrustedIdpToIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-        
-        TrustedIdp trustedIdp = new TrustedIdp();
-        trustedIdp.setRealm("urn:org:apache:cxf:fediz:idp:realm-B");
-        
-        idpDAO.addTrustedIdpToIdp(idp, trustedIdp);
-    }
-    
-    @Test(expected = NoResultException.class)
-    public void testTryAddUnknownTrustedIdpToIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-        
-        TrustedIdp trustedIdp = new TrustedIdp();
-        trustedIdp.setRealm("urn:org:apache:cxf:fediz:UNKNOWN");
-        
-        idpDAO.addTrustedIdpToIdp(idp, trustedIdp);
-    }
-    
-    @Test
-    public void testRemoveTrustedIdpFromIdp() {
-        String realm = "urn:org:apache:cxf:fediz:trustedidp:testremove";
-        //Prepare step
-        Idp idp = createIdp(realm);
-        idpDAO.addIdp(idp);
-        
-        TrustedIdp trustedIdp = new TrustedIdp();
-        trustedIdp.setRealm("urn:org:apache:cxf:fediz:idp:realm-B");
-        idpDAO.addTrustedIdpToIdp(idp, trustedIdp);
-               
-        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        Assert.isTrue(1 == idp.getTrustedIdps().size(),
-                      "trustedIdps size doesn't match [" + idp.getTrustedIdps().size() + "]");
-        
-        //Testcase
-        idpDAO.removeTrustedIdpFromIdp(idp, trustedIdp);
-        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        Assert.isTrue(0 == idp.getTrustedIdps().size(),
-                      "trustedIdps size doesn't match [" + idp.getTrustedIdps().size() + "]");
-    }
-    
-    
-    @Test(expected = EntityNotFoundException.class)
-    public void testTryRemoveNotAssignedTrustedIdpFromIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-                
-        TrustedIdp trustedIdp = new TrustedIdp();
-        trustedIdp.setRealm("trustedidp2realm");
-        
-        idpDAO.removeTrustedIdpFromIdp(idp, trustedIdp);
-    }
-    
-    
-    @Test(expected = NoResultException.class)
-    public void testTryRemoveUnknownTrustedIdpFromIdp() {
-        Idp idp = new Idp();
-        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-                
-        TrustedIdp trustedIdp = new TrustedIdp();
-        trustedIdp.setRealm("urn:org:apache:cxf:fediz:UNKNOWN");
-        
-        idpDAO.removeTrustedIdpFromIdp(idp, trustedIdp);
-    }
-    */
-    
-    
-    private static Idp createIdp(String realm) throws MalformedURLException {
-        Idp idp = new Idp();
-        idp.setRealm(realm);
-        idp.setCertificate("stsKeystoreA.properties");
-        idp.setCertificatePassword("realma");
-        idp.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federation"));
-        idp.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMA"));
-        idp.setServiceDisplayName("NEW REALM");
-        idp.setServiceDescription("IDP of New Realm");
-        idp.setUri("realma");
-        idp.setProvideIdpList(true);
-        Map<String, String> authUris = new HashMap<>();
-        authUris.put("default", "/login/default");
-        idp.setAuthenticationURIs(authUris);
-        List<String> protocols = new ArrayList<>();
-        protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
-        protocols.add("http://docs.oasis-open.org/ws-sx/ws-trust/200512");
-        idp.setSupportedProtocols(protocols);
-        List<String> tokenTypes = new ArrayList<>();
-        tokenTypes.add(WSConstants.SAML2_NS);
-        tokenTypes.add(WSConstants.SAML_NS);
-        idp.setTokenTypesOffered(tokenTypes);
-        idp.setUseCurrentIdp(true);
-        return idp;
-    }
-    /*
-    private static Application createApplication(String realm) {
-        Application application = new Application();
-        application.setRealm(realm);
-        application.setEncryptionCertificate("");
-        application.setLifeTime("3600");
-        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-        application.setRole("ApplicationServiceType");
-        application.setServiceDescription("Fedizhelloworld description");
-        application.setServiceDisplayName("Fedizhelloworld");
-        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
-        return application;
-    }
-    */
-    
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TestDBLoader.java
----------------------------------------------------------------------
diff --git a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TestDBLoader.java b/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TestDBLoader.java
deleted file mode 100644
index 222277a..0000000
--- a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TestDBLoader.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-
-import org.apache.cxf.fediz.service.idp.domain.FederationType;
-import org.apache.cxf.fediz.service.idp.domain.TrustType;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional
-public class TestDBLoader implements DBLoader {
-    
-    public static final String NAME = "UNITTESTDBLOADER";
-    
-    private static final Logger LOG = LoggerFactory.getLogger(TestDBLoader.class);
-    
-    private EntityManager em;
-
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-    
-    @Override
-    public String getName() {
-        return NAME;
-    }
-    
-    public void load() {
-        
-        try {
-            ClaimEntity claimEntity5 = new ClaimEntity();
-            claimEntity5.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/city");
-            claimEntity5.setDisplayName("city");
-            claimEntity5.setDescription("Description for city");
-            em.persist(claimEntity5);
-                        
-            ApplicationEntity entity2 = new ApplicationEntity();
-            entity2.setEncryptionCertificate("my encryption cert2");
-            entity2.setLifeTime(1800);
-            entity2.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-            entity2.setRealm("myrealm2");
-            entity2.setRole("myrole");
-            entity2.setServiceDescription("service description2");
-            entity2.setServiceDisplayName("service displayname2");
-            entity2.setTokenType("my tokentype");
-            // must be persistet here already as the ApplicationClaimEntity requires the Application Id
-            em.persist(entity2);
-            ApplicationClaimEntity ace5 = new ApplicationClaimEntity(entity2, claimEntity5);
-            ace5.setOptional(false);
-            em.persist(ace5);
-            entity2.getRequestedClaims().add(ace5);
-            em.persist(entity2);
-            
-            TrustedIdpEntity entity4 = new TrustedIdpEntity();
-            entity4.setCacheTokens(true);
-            entity4.setCertificate("trusted cert");
-            entity4.setDescription("Realm B description");
-            entity4.setFederationType(FederationType.FEDERATE_IDENTITY);
-            entity4.setName("Realm B");
-            entity4.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-            entity4.setRealm("trustedidp2realm");
-            entity4.setTrustType(TrustType.PEER_TRUST);
-            entity4.setUrl("https://localhost:${realmB.port}/fediz-idp-remote/federation");
-            em.persist(entity4);
-            
-            em.flush();
-            
-        } catch (Exception ex) {
-            LOG.warn("Failed to initialize DB with data", ex);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPATest.java b/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPATest.java
deleted file mode 100644
index 2ebe5ba..0000000
--- a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPATest.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.domain.FederationType;
-import org.apache.cxf.fediz.service.idp.domain.TrustType;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.service.TrustedIdpDAO;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.EmptyResultDataAccessException;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.util.Assert;
-
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@ContextConfiguration(locations = { "classpath:testContext.xml" })
-public class TrustedIdpDAOJPATest {
-
-    @Autowired
-    private TrustedIdpDAO trustedIdpDAO;
-        
-    
-    @BeforeClass
-    public static void init() {
-        System.setProperty("spring.profiles.active", "jpa");
-    }
-    
-    
-    @Test
-    public void testReadAllTrustedIdps() {
-        List<TrustedIdp> trustedIdps = trustedIdpDAO.getTrustedIDPs(0, 999);
-        Assert.isTrue(2 <= trustedIdps.size(), "Size doesn't match");
-    }
-    
-    @Test
-    public void testReadExistingTrustedIdp() {
-        TrustedIdp trustedIdp = trustedIdpDAO.getTrustedIDP("urn:org:apache:cxf:fediz:idp:realm-B");
-        Assert.isTrue("realmb.cert".equals(trustedIdp.getCertificate()),
-                      "Certificate name doesn't match");
-        Assert.isTrue("Realm B description".equals(trustedIdp.getDescription()),
-                      "Description name doesn't match");
-        Assert.isTrue(FederationType.FEDERATE_IDENTITY.equals(trustedIdp.getFederationType()),
-                      "FederationType doesn't match");        
-        Assert.isTrue("Realm B".equals(trustedIdp.getName()),
-                      "Name doesn't match");      
-        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(trustedIdp.getProtocol()),
-                      "Protocol doesn't match");          
-        Assert.isTrue("urn:org:apache:cxf:fediz:idp:realm-B".equals(trustedIdp.getRealm()),
-                      "Realm doesn't match");          
-        Assert.isTrue(TrustType.PEER_TRUST.equals(trustedIdp.getTrustType()),
-                      "TrustType doesn't match");
-        Assert.isTrue("https://localhost:12443/fediz-idp-remote/federation".equals(trustedIdp.getUrl()),
-                      "Url doesn't match"); 
-        Assert.isTrue(trustedIdp.isCacheTokens(), "CacheTokens doesn't match"); 
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryReadNonexistingTrustedIdp() {
-        trustedIdpDAO.getTrustedIDP("urn:org:apache:cxf:fediz:idp:NOTEXIST");
-    }
-    
-    
-    @Test
-    public void testAddNewTrustedIdp() {
-        String realm = "urn:org:apache:cxf:fediz:trusted-idp:testadd";
-        TrustedIdp trustedIdp = createTrustedIdp(realm);
-        trustedIdpDAO.addTrustedIDP(trustedIdp);
-        
-        trustedIdp = trustedIdpDAO.getTrustedIDP(realm);
-        
-        Assert.isTrue("realmb.cert".equals(trustedIdp.getCertificate()),
-                      "Certificate name doesn't match");
-        Assert.isTrue("Realm B description".equals(trustedIdp.getDescription()),
-                      "Description name doesn't match");
-        Assert.isTrue(FederationType.FEDERATE_IDENTITY.equals(trustedIdp.getFederationType()),
-                      "FederationType doesn't match");        
-        Assert.isTrue("Realm B".equals(trustedIdp.getName()),
-                      "Name doesn't match");      
-        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(trustedIdp.getProtocol()),
-                      "Protocol doesn't match");          
-        Assert.isTrue(realm.equals(trustedIdp.getRealm()),
-                      "Realm doesn't match");          
-        Assert.isTrue(TrustType.PEER_TRUST.equals(trustedIdp.getTrustType()),
-                      "TrustType doesn't match");
-        Assert.isTrue("https://localhost:12443/fediz-idp-remote/federation".equals(trustedIdp.getUrl()),
-                      "Url doesn't match"); 
-        Assert.isTrue(!trustedIdp.isCacheTokens(), "CacheTokens doesn't match"); 
-    }
-    
-    
-    @Test
-    public void testUpdateTrustedIdp() {
-        String realm = "urn:org:apache:cxf:fediz:trusted-idp:testupdate";
-        //Prepare
-        TrustedIdp trustedIdp = createTrustedIdp(realm);
-        trustedIdpDAO.addTrustedIDP(trustedIdp);
-        
-        //Testcase
-        trustedIdp = new TrustedIdp();
-        trustedIdp.setRealm(realm);
-        trustedIdp.setCacheTokens(true);
-        trustedIdp.setCertificate("Utrusted cert");
-        trustedIdp.setDescription("URealm B description");
-        trustedIdp.setFederationType(FederationType.FEDERATE_CLAIMS);
-        trustedIdp.setName("URealm B");
-        trustedIdp.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-        trustedIdp.setTrustType(TrustType.INDIRECT_TRUST);
-        trustedIdp.setUrl("Uhttps://localhost:12443/fediz-idp-remote/federation");
-        
-        trustedIdpDAO.updateTrustedIDP(realm, trustedIdp);
-        
-        trustedIdp = trustedIdpDAO.getTrustedIDP(realm);
-        
-        Assert.isTrue("Utrusted cert".equals(trustedIdp.getCertificate()),
-                      "Certificate name doesn't match");
-        Assert.isTrue("URealm B description".equals(trustedIdp.getDescription()),
-                      "Description name doesn't match");
-        Assert.isTrue(FederationType.FEDERATE_CLAIMS.equals(trustedIdp.getFederationType()),
-                      "FederationType doesn't match");        
-        Assert.isTrue("URealm B".equals(trustedIdp.getName()),
-                      "Name doesn't match");      
-        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(trustedIdp.getProtocol()),
-                      "Protocol doesn't match");          
-        Assert.isTrue(realm.equals(trustedIdp.getRealm()),
-                      "Realm doesn't match");          
-        Assert.isTrue(TrustType.INDIRECT_TRUST.equals(trustedIdp.getTrustType()),
-                      "TrustType doesn't match");
-        Assert.isTrue("Uhttps://localhost:12443/fediz-idp-remote/federation".equals(trustedIdp.getUrl()),
-                      "Url doesn't match"); 
-        Assert.isTrue(trustedIdp.isCacheTokens(), "CacheTokens doesn't match");
-        
-    }
-    
-    
-    @Test(expected = DataIntegrityViolationException.class)
-    public void testTryAddExistingTrustedIdp() {
-        TrustedIdp trustedIdp = createTrustedIdp("urn:org:apache:cxf:fediz:idp:realm-B");
-        trustedIdpDAO.addTrustedIDP(trustedIdp);
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testTryRemoveUnknownTrustedIdp() {
-        trustedIdpDAO.deleteTrustedIDP("urn:org:apache:cxf:fediz:trusted-idp:NOTEXIST");
-    }
-    
-    
-    @Test(expected = EmptyResultDataAccessException.class)
-    public void testRemoveExistingTrustedIdp() {
-        String realm = "urn:org:apache:cxf:fediz:trusted-idp:testdelete";
-        TrustedIdp trustedIdp = createTrustedIdp(realm);
-        
-        trustedIdpDAO.addTrustedIDP(trustedIdp);
-        
-        trustedIdpDAO.deleteTrustedIDP(realm);
-        
-        trustedIdpDAO.getTrustedIDP(realm);
-    }
-    
-    
-    private static TrustedIdp createTrustedIdp(String realm) {
-        TrustedIdp trustedIdp = new TrustedIdp();
-        trustedIdp.setRealm(realm);
-        trustedIdp.setCacheTokens(false);
-        trustedIdp.setCertificate("realmb.cert");
-        trustedIdp.setDescription("Realm B description");
-        trustedIdp.setFederationType(FederationType.FEDERATE_IDENTITY);
-        trustedIdp.setName("Realm B");
-        trustedIdp.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-        trustedIdp.setTrustType(TrustType.PEER_TRUST);
-        trustedIdp.setUrl("https://localhost:12443/fediz-idp-remote/federation");
-        return trustedIdp;
-    }
-    
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/util/MetadataWriterTest.java
----------------------------------------------------------------------
diff --git a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/util/MetadataWriterTest.java b/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/util/MetadataWriterTest.java
deleted file mode 100644
index 85c369b..0000000
--- a/services/idp/src/test/java/org/apache/cxf/fediz/service/idp/util/MetadataWriterTest.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.util;
-
-import org.w3c.dom.Document;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.metadata.IdpMetadataWriter;
-import org.apache.cxf.fediz.service.idp.service.ConfigService;
-import org.apache.wss4j.common.util.DOM2Writer;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-import org.springframework.util.Assert;
-
-public class MetadataWriterTest {
-
-    private static ApplicationContext applicationContext;
-    
-    @BeforeClass
-    public static void init() {
-        applicationContext = new ClassPathXmlApplicationContext("/idp-config.xml");
-    }
-    
-    @Test
-    public void testWriteIDPMetadata() {
-        ConfigService config = (ConfigService)applicationContext.getBean("config");
-        Assert.notNull(config, "ConfigService must not be null");
-        Idp idpConfig = config.getIDP("urn:org:apache:cxf:fediz:idp:realm-A");
-        Assert.notNull(idpConfig, "IDPConfig must not be null");
-        
-        IdpMetadataWriter writer = new IdpMetadataWriter();
-        Document doc = writer.getMetaData(idpConfig);
-        Assert.notNull(doc, "doc must not be null");
-        
-        System.out.println(DOM2Writer.nodeToString(doc));
-        
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/resources/idp-config.xml
----------------------------------------------------------------------
diff --git a/services/idp/src/test/resources/idp-config.xml b/services/idp/src/test/resources/idp-config.xml
deleted file mode 100644
index 61d0bbd..0000000
--- a/services/idp/src/test/resources/idp-config.xml
+++ /dev/null
@@ -1,152 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  Licensed to the Apache Software Foundation (ASF) under one
-  or more contributor license agreements. See the NOTICE file
-  distributed with this work for additional information
-  regarding copyright ownership. The ASF licenses this file
-  to you 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.
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
-       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xmlns:util="http://www.springframework.org/schema/util"
-       xmlns:http="http://cxf.apache.org/transports/http/configuration"
-       xmlns:context="http://www.springframework.org/schema/context"
-       xsi:schemaLocation="http://www.springframework.org/schema/beans
-        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
-        http://www.springframework.org/schema/context
-        http://www.springframework.org/schema/context/spring-context-4.3.xsd
-        http://www.springframework.org/schema/util
-        http://www.springframework.org/schema/util/spring-util-4.3.xsd
-        http://cxf.apache.org/transports/http/configuration
-        http://cxf.apache.org/schemas/configuration/http-conf.xsd">
-
-    <context:property-placeholder location="classpath:realm.properties" />
-
-    <bean id="config"
-        class="org.apache.cxf.fediz.service.idp.service.ConfigServiceSpring">
-        <property name="idpConfigs">
-            <util:list>
-                <ref bean="idp-realmA" />
-            </util:list>
-        </property>
-        <property name="serviceConfigs">
-            <util:list>
-                <ref bean="srv-fedizhelloworld" />
-            </util:list>
-        </property>
-    </bean>
-
-    <bean id="idp-realmA" class="org.apache.cxf.fediz.service.idp.model.IDPConfig">
-        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-A" />
-        <property name="uri" value="realma" />
-        <!--<property name="hrds" value="" /> --> <!-- TBD, not defined, provide list if enabled -->
-        <property name="provideIdpList" value="true" />
-        <property name="useCurrentIdp" value="true" />
-        <!-- <property name="certificate" value="realma.cert" /> -->   <!-- STS will sign token, IDP signs Metadata -->
-        <property name="certificate" value="stsKeystoreA.properties" />
-        <property name="certificatePassword" value="realma" />
-        <property name="stsUrl"
-            value="https://localhost:0/fediz-idp-sts/REALMA" />
-        <property name="idpUrl"
-            value="https://localhost:${realmA.port}/fediz-idp/federation" />
-        <property name="supportedProtocols">
-            <util:list>
-                <value>http://docs.oasis-open.org/wsfed/federation/200706
-                </value>
-                <value>http://docs.oasis-open.org/ws-sx/ws-trust/200512
-                </value>
-            </util:list>
-        </property>
-        <property name="services">
-            <util:map>
-                <entry key="urn:org:apache:cxf:fediz:fedizhelloworld"
-                    value-ref="srv-fedizhelloworld" />
-            </util:map>
-        </property>
-        <property name="authenticationURIs">
-            <util:map>
-                <entry key="default" value="/login/default" />
-            </util:map>
-        </property>
-        <property name="trustedIdps">
-            <util:map>
-                <entry key="urn:org:apache:cxf:fediz:idp:realm-B"
-                    value-ref="trusted-idp-realmB" />
-            </util:map>
-        </property>
-        <property name="serviceDisplayName" value="REALM A" />
-        <property name="serviceDescription" value="IDP of Realm A" />
-    </bean>
-
-    <bean id="trusted-idp-realmB"
-        class="org.apache.cxf.fediz.service.idp.model.TrustedIDPConfig">
-        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-B" />
-        <property name="cacheTokens" value="true" />
-        <property name="url"
-            value="https://localhost:${realmB.port}/fediz-idp-remote/federation" />
-        <property name="certificate" value="realmb.cert" />
-        <property name="trustType" value="PEER_TRUST" />  <!-- Required for Fediz Core, Process SignInResponse -->
-        <property name="protocol"
-            value="http://docs.oasis-open.org/wsfed/federation/200706" />
-        <property name="federationType" value="FEDERATE_IDENTITY" /> <!-- Required for STS Relationship -->
-        <property name="name" value="REALM B" />
-        <property name="description" value="IDP of Realm B" />
-        <!--<property name="logo" value="true" /> -->
-    </bean>
-
-    <bean id="srv-fedizhelloworld" class="org.apache.cxf.fediz.service.idp.model.ServiceConfig">
-        <property name="realm"
-            value="urn:org:apache:cxf:fediz:fedizhelloworld" />
-        <property name="protocol"
-            value="http://docs.oasis-open.org/wsfed/federation/200706" />
-        <property name="serviceDisplayName" value="Fedizhelloworld" />
-        <property name="serviceDescription"
-            value="Web Application to illustrate WS-Federation" />
-        <property name="role" value="ApplicationServiceType" />
-        <property name="tokenType"
-            value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
-        <property name="lifeTime" value="3600" />
-        <!-- <property name="encryptionCertificate" value="" /> -->
-        <property name="requestedClaims">
-            <util:list>
-                <bean
-                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
-                    <property name="claimType"
-                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" />
-                    <property name="optional" value="false" />
-                </bean>
-                <bean
-                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
-                    <property name="claimType"
-                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" />
-                    <property name="optional" value="false" />
-                </bean>
-                <bean
-                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
-                    <property name="claimType"
-                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" />
-                    <property name="optional" value="false" />
-                </bean>
-                <bean
-                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
-                    <property name="claimType"
-                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role" />
-                    <property name="optional" value="true" />
-                </bean>
-            </util:list>
-        </property>
-    </bean>
-
-</beans>
-

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/resources/persistence.properties
----------------------------------------------------------------------
diff --git a/services/idp/src/test/resources/persistence.properties b/services/idp/src/test/resources/persistence.properties
deleted file mode 100644
index b4e0320..0000000
--- a/services/idp/src/test/resources/persistence.properties
+++ /dev/null
@@ -1,14 +0,0 @@
-#jpa.driverClassName=org.apache.derby.jdbc.ClientDriver
-#jpa.url=jdbc:derby://localhost:1527/Fediz
-#jpa.username=admin
-#jpa.password=admin
-#jpa.defaultData=true
-#jpa.platform=DerbyDictionary
-
-
-jpa.driverClassName=org.hsqldb.jdbcDriver
-jpa.url=jdbc:hsqldb:target/db/unit/myDB;shutdown=true
-jpa.username=sa
-jpa.password=
-jpa.defaultData=true
-jpa.platform=HSQLDictionary

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/resources/realm.properties
----------------------------------------------------------------------
diff --git a/services/idp/src/test/resources/realm.properties b/services/idp/src/test/resources/realm.properties
deleted file mode 100644
index 9414fc0..0000000
--- a/services/idp/src/test/resources/realm.properties
+++ /dev/null
@@ -1,4 +0,0 @@
-realm.STS_URI=REALMA
-realmA.port=8443
-realmB.port=12443
-db-load-config=entities-realma.xml

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/resources/realma.cert
----------------------------------------------------------------------
diff --git a/services/idp/src/test/resources/realma.cert b/services/idp/src/test/resources/realma.cert
deleted file mode 100644
index ff97f79..0000000
--- a/services/idp/src/test/resources/realma.cert
+++ /dev/null
@@ -1,15 +0,0 @@
------BEGIN CERTIFICATE-----
-MIICwTCCAamgAwIBAgIEINqJ9TANBgkqhkiG9w0BAQsFADARMQ8wDQYDVQQDEwZSRUFMTUEwHhcN
-MTUwNjEwMTU0NDE3WhcNMjUwNDE4MTU0NDE3WjARMQ8wDQYDVQQDEwZSRUFMTUEwggEiMA0GCSqG
-SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCJDSXn2lDR+JM+AsJarFG3/XGH7K+9AfAbQIz2IgB9MCpO
-KVWTUPCvuo1I+Fp5nEGreuHYLEwgIiam3o+C9tvpLgtDDaDkmXjDzkWpk8z6+im72HZ/ODF93Rqw
-jIiY5ZCzgDumFyPzdKiGwChThamidy+rd6oheSoi6qRVSMMcnwiEUmvkfFvV3izXRqeT5nGQwsin
-y9mCEiGx8jkfxP++H0RQjVjhOwzfQ7epsR7dTQNf2ZhkBR3o6wKV9QnF2IBWHZpA9EK58rWU9H6j
-G7b631rYvwsbOUF9HcZ8DI2BFh+4p18jDN/fnjNGSLr9rYOExpsIiF1cHBK7Tr7WwCmDAgMBAAGj
-ITAfMB0GA1UdDgQWBBRHy0qYoLm9jx/1L6r61NznHKun2jANBgkqhkiG9w0BAQsFAAOCAQEAR9rU
-5Sp1FsOErdvKNFqeaKl0oq6Fuz7BWcGm2kK6+1ZbWE8IOv6Vh+BlLuOe5hF7aLUbm8UIjhKsmg0M
-Ey5MBwkBZktT1qhQteMuiKgYR7CxayCxO0f125RYvvwntJa5rI7bUrzOqX29VQD1qQ/Tb+08fULT
-L7oURP+g88Ff99dn3IpO4VZxZdsbl4+KZRtqQvPAdXNYjOajJtPzS489+/DtfWJ6wPm/7YZ4did4
-1fYcrdwyEZ15L0/5i931z7sztNickm5WhO40qEVDKN6KrlV2Eyea0+933v2Pwe4resTlko9G2T5h
-dEaSbvht2Q/JOMMmT91daeto2oS8HTKhTA==
------END CERTIFICATE-----

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/resources/stsKeystoreA.properties
----------------------------------------------------------------------
diff --git a/services/idp/src/test/resources/stsKeystoreA.properties b/services/idp/src/test/resources/stsKeystoreA.properties
deleted file mode 100644
index bd9fb1b..0000000
--- a/services/idp/src/test/resources/stsKeystoreA.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
-org.apache.ws.security.crypto.merlin.keystore.type=jks
-org.apache.ws.security.crypto.merlin.keystore.password=storepass
-org.apache.ws.security.crypto.merlin.keystore.alias=realma
-org.apache.ws.security.crypto.merlin.keystore.file=stsrealm_a.jks
-

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/resources/stsrealm_a.jks
----------------------------------------------------------------------
diff --git a/services/idp/src/test/resources/stsrealm_a.jks b/services/idp/src/test/resources/stsrealm_a.jks
deleted file mode 100644
index fde2928..0000000
Binary files a/services/idp/src/test/resources/stsrealm_a.jks and /dev/null differ

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/test/resources/testContext.xml
----------------------------------------------------------------------
diff --git a/services/idp/src/test/resources/testContext.xml b/services/idp/src/test/resources/testContext.xml
deleted file mode 100644
index bd015f0..0000000
--- a/services/idp/src/test/resources/testContext.xml
+++ /dev/null
@@ -1,54 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  Licensed to the Apache Software Foundation (ASF) under one
-  or more contributor license agreements. See the NOTICE file
-  distributed with this work for additional information
-  regarding copyright ownership. The ASF licenses this file
-  to you 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.
--->
-<beans xmlns="http://www.springframework.org/schema/beans"
-    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-    xmlns:util="http://www.springframework.org/schema/util"
-    xmlns:context="http://www.springframework.org/schema/context"
-    xsi:schemaLocation="
-        http://www.springframework.org/schema/beans
-        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
-        http://www.springframework.org/schema/util
-        http://www.springframework.org/schema/util/spring-util-4.3.xsd
-        http://www.springframework.org/schema/context
-        http://www.springframework.org/schema/context/spring-context-4.3.xsd">
-
-    <context:component-scan base-package="org.apache.cxf.fediz.service.idp.service" />
-    <context:component-scan base-package="org.apache.cxf.fediz.service.idp.protocols" />
-
-    <import resource="classpath:persistenceContext.xml" />
-
-    <!-- Use http://www.baeldung.com/2012/02/06/properties-with-spring/ instead -->
-    <bean
-        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
-        <property name="locations">
-            <list>
-                <value>classpath:persistence.properties</value>
-                <value>classpath:realm.properties</value>
-            </list>
-        </property>
-        <property name="ignoreResourceNotFound" value="true" />
-        <property name="ignoreUnresolvablePlaceholders" value="true" />
-    </bean>
-
-    <bean id="dbLoadertest"
-        class="org.apache.cxf.fediz.service.idp.service.jpa.TestDBLoader" />
-
-</beans>
-

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/pom.xml
----------------------------------------------------------------------
diff --git a/services/pom.xml b/services/pom.xml
index 2a7f925..e8bb9dd 100644
--- a/services/pom.xml
+++ b/services/pom.xml
@@ -32,6 +32,7 @@
 
    <modules>
       <module>sts</module>
+      <module>idp-core</module>
       <module>idp</module>
       <module>oidc</module>
    </modules>


[18/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR


Project: http://git-wip-us.apache.org/repos/asf/cxf-fediz/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf-fediz/commit/bf309400
Tree: http://git-wip-us.apache.org/repos/asf/cxf-fediz/tree/bf309400
Diff: http://git-wip-us.apache.org/repos/asf/cxf-fediz/diff/bf309400

Branch: refs/heads/master
Commit: bf30940024fdde9390f654094a047e4b17fce878
Parents: f9c0026
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Fri Jan 27 10:50:48 2017 +0000
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Fri Jan 27 10:50:48 2017 +0000

----------------------------------------------------------------------
 services/idp-core/README.txt                    |  57 ++
 services/idp-core/pom.xml                       | 356 ++++++++++
 .../src/main/filters/realm-a/env.properties     |   6 +
 .../src/main/filters/realm-b/env.properties     |   6 +
 .../cxf/fediz/service/idp/FedizEntryPoint.java  | 172 +++++
 .../cxf/fediz/service/idp/IdpConstants.java     |  60 ++
 .../cxf/fediz/service/idp/IdpSTSClient.java     |  52 ++
 .../cxf/fediz/service/idp/MetadataServlet.java  | 111 ++++
 .../service/idp/STSAuthenticationProvider.java  | 307 +++++++++
 .../idp/STSKrbAuthenticationProvider.java       | 259 ++++++++
 .../cxf/fediz/service/idp/STSPortFilter.java    |  95 +++
 .../idp/STSPreAuthAuthenticationProvider.java   | 130 ++++
 .../idp/STSUPAuthenticationProvider.java        | 131 ++++
 .../cxf/fediz/service/idp/STSUserDetails.java   |  73 +++
 .../service/idp/beans/CacheSecurityToken.java   |  56 ++
 .../service/idp/beans/CommonsURLValidator.java  |  52 ++
 .../service/idp/beans/HomeRealmReminder.java    |  43 ++
 .../idp/beans/IdpTokenExpiredAction.java        |  69 ++
 .../fediz/service/idp/beans/LogoutAction.java   |  45 ++
 .../idp/beans/PassiveRequestorValidator.java    |  76 +++
 .../idp/beans/ProcessHRDSExpressionAction.java  |  72 ++
 .../service/idp/beans/STSClientAction.java      | 439 +++++++++++++
 .../idp/beans/SigninParametersCacheAction.java  | 185 ++++++
 .../service/idp/beans/TokenSerializer.java      |  62 ++
 .../idp/beans/TrustedIdpProtocolAction.java     | 100 +++
 .../idp/beans/samlsso/AuthnRequestParser.java   | 388 +++++++++++
 .../idp/beans/samlsso/LocalRedirectCreator.java |  54 ++
 .../idp/beans/samlsso/SamlResponseCreator.java  | 187 ++++++
 .../beans/samlsso/SamlResponseErrorCreator.java |  97 +++
 .../service/idp/beans/wsfed/WfreshParser.java   |  84 +++
 .../fediz/service/idp/domain/Application.java   | 242 +++++++
 .../cxf/fediz/service/idp/domain/Claim.java     |  79 +++
 .../fediz/service/idp/domain/Entitlement.java   |  70 ++
 .../service/idp/domain/FederationType.java      |  40 ++
 .../cxf/fediz/service/idp/domain/Idp.java       | 304 +++++++++
 .../fediz/service/idp/domain/RequestClaim.java  |  49 ++
 .../cxf/fediz/service/idp/domain/Role.java      |  74 +++
 .../cxf/fediz/service/idp/domain/TrustType.java |  40 ++
 .../fediz/service/idp/domain/TrustedIdp.java    | 187 ++++++
 .../KerberosAuthenticationProcessingFilter.java | 199 ++++++
 .../idp/kerberos/KerberosEntryPoint.java        |  70 ++
 .../kerberos/KerberosServiceRequestToken.java   | 150 +++++
 .../idp/kerberos/KerberosTokenValidator.java    | 185 ++++++
 .../idp/kerberos/PassThroughKerberosClient.java |  80 +++
 .../service/idp/metadata/IdpMetadataWriter.java | 180 +++++
 .../idp/metadata/ServiceMetadataWriter.java     | 214 ++++++
 .../cxf/fediz/service/idp/model/IDPConfig.java  |  44 ++
 .../fediz/service/idp/model/RequestClaim.java   |  26 +
 .../fediz/service/idp/model/ServiceConfig.java  |  35 +
 .../service/idp/model/TrustedIDPConfig.java     |  30 +
 .../service/idp/model/TrustedIDPSelection.java  |  36 +
 ...AbstractTrustedIdpOAuth2ProtocolHandler.java | 207 ++++++
 .../AbstractTrustedIdpProtocolHandler.java      |  58 ++
 .../ApplicationProtocolControllerImpl.java      |  60 ++
 .../ApplicationSAMLSSOProtocolHandler.java      |  57 ++
 .../ApplicationWSFedProtocolHandler.java        |  57 ++
 .../idp/protocols/ProtocolController.java       |  32 +
 .../TrustedIdpFacebookProtocolHandler.java      | 226 +++++++
 .../TrustedIdpOIDCProtocolHandler.java          | 335 ++++++++++
 .../TrustedIdpProtocolControllerImpl.java       |  60 ++
 .../TrustedIdpSAMLProtocolHandler.java          | 415 ++++++++++++
 .../TrustedIdpWSFedProtocolHandler.java         | 231 +++++++
 .../service/idp/rest/ApplicationService.java    |  88 +++
 .../idp/rest/ApplicationServiceImpl.java        | 151 +++++
 .../fediz/service/idp/rest/Applications.java    |  49 ++
 .../fediz/service/idp/rest/ClaimService.java    |  72 ++
 .../service/idp/rest/ClaimServiceImpl.java      | 106 +++
 .../cxf/fediz/service/idp/rest/Claims.java      |  50 ++
 .../service/idp/rest/EntitlementService.java    |  73 +++
 .../idp/rest/EntitlementServiceImpl.java        |  98 +++
 .../fediz/service/idp/rest/Entitlements.java    |  49 ++
 .../cxf/fediz/service/idp/rest/IdpService.java  | 114 ++++
 .../fediz/service/idp/rest/IdpServiceImpl.java  | 240 +++++++
 .../apache/cxf/fediz/service/idp/rest/Idps.java |  49 ++
 .../idp/rest/QueryResourceInfoComparator.java   | 114 ++++
 .../idp/rest/RestServiceExceptionMapper.java    |  83 +++
 .../cxf/fediz/service/idp/rest/RoleService.java |  88 +++
 .../fediz/service/idp/rest/RoleServiceImpl.java | 134 ++++
 .../cxf/fediz/service/idp/rest/Roles.java       |  49 ++
 .../cxf/fediz/service/idp/rest/RootService.java |  39 ++
 .../fediz/service/idp/rest/RootServiceImpl.java |  60 ++
 .../service/idp/rest/TrustedIdpService.java     |  71 ++
 .../service/idp/rest/TrustedIdpServiceImpl.java |  93 +++
 .../cxf/fediz/service/idp/rest/TrustedIdps.java |  49 ++
 .../idp/samlsso/SAML2CallbackHandler.java       | 148 +++++
 .../samlsso/SAML2PResponseComponentBuilder.java | 127 ++++
 .../service/idp/samlsso/SAMLAuthnRequest.java   |  74 +++
 .../service/idp/service/ApplicationDAO.java     |  43 ++
 .../cxf/fediz/service/idp/service/ClaimDAO.java |  38 ++
 .../service/idp/service/ConfigService.java      |  32 +
 .../idp/service/ConfigServiceSpring.java        |  76 +++
 .../service/idp/service/EntitlementDAO.java     |  38 ++
 .../cxf/fediz/service/idp/service/IdpDAO.java   |  53 ++
 .../cxf/fediz/service/idp/service/RoleDAO.java  |  43 ++
 .../service/idp/service/TrustedIdpDAO.java      |  38 ++
 .../idp/service/jpa/ApplicationClaimEntity.java |  83 +++
 .../idp/service/jpa/ApplicationDAOJPAImpl.java  | 254 ++++++++
 .../idp/service/jpa/ApplicationEntity.java      | 214 ++++++
 .../ApplicationIdpProtocolSupportValidator.java |  54 ++
 .../jpa/ApplicationProtocolSupported.java       |  47 ++
 .../idp/service/jpa/ClaimDAOJPAImpl.java        | 143 ++++
 .../service/idp/service/jpa/ClaimEntity.java    |  71 ++
 .../idp/service/jpa/ConfigServiceJPA.java       |  96 +++
 .../service/jpa/DBInitApplicationListener.java  |  73 +++
 .../fediz/service/idp/service/jpa/DBLoader.java |  28 +
 .../service/idp/service/jpa/DBLoaderImpl.java   | 163 +++++
 .../service/idp/service/jpa/DBLoaderSpring.java | 129 ++++
 .../idp/service/jpa/EntitlementDAOJPAImpl.java  | 142 ++++
 .../idp/service/jpa/EntitlementEntity.java      |  72 ++
 .../service/idp/service/jpa/IdpDAOJPAImpl.java  | 367 +++++++++++
 .../service/idp/service/jpa/IdpEntity.java      | 301 +++++++++
 .../service/idp/service/jpa/RoleDAOJPAImpl.java | 206 ++++++
 .../service/idp/service/jpa/RoleEntity.java     |  77 +++
 .../idp/service/jpa/TrustedIdpDAOJPAImpl.java   | 154 +++++
 .../idp/service/jpa/TrustedIdpEntity.java       | 201 ++++++
 .../jpa/TrustedIdpProtocolSupportValidator.java |  54 ++
 .../jpa/TrustedIdpProtocolSupported.java        |  47 ++
 .../security/GrantedAuthorityEntitlements.java  | 100 +++
 .../idp/spi/ApplicationProtocolHandler.java     |  33 +
 .../fediz/service/idp/spi/ProtocolHandler.java  |  25 +
 .../idp/spi/TrustedIdpProtocolHandler.java      |  40 ++
 .../cxf/fediz/service/idp/util/WebUtils.java    | 209 ++++++
 .../src/main/resources/META-INF/orm.xml         | 183 ++++++
 .../resources/META-INF/spring-persistence.xml   |  30 +
 .../main/webapp/WEB-INF/applicationContext.xml  |  61 ++
 .../webapp/WEB-INF/config/idp-core-servlet.xml  | 105 +++
 .../config/security-clientcert-config.xml       |  75 +++
 .../WEB-INF/config/security-krb-config.xml      |  84 +++
 .../WEB-INF/config/security-rs-config.xml       |  64 ++
 .../WEB-INF/config/security-up-config.xml       |  94 +++
 .../flows/federation-validate-request.xml       | 283 ++++++++
 .../WEB-INF/flows/saml-validate-request.xml     | 259 ++++++++
 .../webapp/WEB-INF/flows/signin-request.xml     | 171 +++++
 .../webapp/WEB-INF/flows/signin-response.xml    |  85 +++
 .../main/webapp/WEB-INF/idp-config-realma.xml   | 158 +++++
 .../main/webapp/WEB-INF/idp-config-realmb.xml   | 133 ++++
 .../src/main/webapp/WEB-INF/idp-servlet.xml     |  39 ++
 .../src/main/webapp/WEB-INF/security-config.xml |  76 +++
 .../main/webapp/WEB-INF/views/genericerror.jsp  |  11 +
 .../src/main/webapp/WEB-INF/views/idplist.jsp   |  33 +
 .../src/main/webapp/WEB-INF/views/index.jsp     |  25 +
 .../WEB-INF/views/samlsigninresponseform.jsp    |  20 +
 .../main/webapp/WEB-INF/views/signinform.jsp    |  72 ++
 .../webapp/WEB-INF/views/signinresponseform.jsp |  25 +
 .../views/signoutconfirmationresponse.jsp       |  65 ++
 .../webapp/WEB-INF/views/signoutresponse.jsp    |  56 ++
 .../idp-core/src/main/webapp/WEB-INF/web.xml    | 131 ++++
 .../webapp/resources/images/apache-logo.png     | Bin 0 -> 20928 bytes
 .../main/webapp/resources/swagger/index.html    | 156 +++++
 .../idp/service/jpa/ApplicationDAOJPATest.java  | 348 ++++++++++
 .../idp/service/jpa/ClaimDAOJPATest.java        | 115 ++++
 .../idp/service/jpa/EntitlementDAOJPATest.java  | 115 ++++
 .../service/idp/service/jpa/IdpDAOJPATest.java  | 653 +++++++++++++++++++
 .../service/idp/service/jpa/TestDBLoader.java   |  93 +++
 .../idp/service/jpa/TrustedIdpDAOJPATest.java   | 202 ++++++
 .../service/idp/util/MetadataWriterTest.java    |  57 ++
 .../src/test/resources/entities-realma.xml      | 504 ++++++++++++++
 .../idp-core/src/test/resources/idp-config.xml  | 152 +++++
 .../src/test/resources/persistence.properties   |  14 +
 .../src/test/resources/persistenceContext.xml   | 107 +++
 .../src/test/resources/realm.properties         |   4 +
 .../idp-core/src/test/resources/realma.cert     |  15 +
 .../src/test/resources/stsKeystoreA.properties  |   6 +
 .../idp-core/src/test/resources/stsrealm_a.jks  | Bin 0 -> 2061 bytes
 .../idp-core/src/test/resources/testContext.xml |  54 ++
 services/idp/pom.xml                            | 308 +--------
 .../cxf/fediz/service/idp/FedizEntryPoint.java  | 172 -----
 .../cxf/fediz/service/idp/IdpConstants.java     |  60 --
 .../cxf/fediz/service/idp/IdpSTSClient.java     |  52 --
 .../cxf/fediz/service/idp/MetadataServlet.java  | 111 ----
 .../service/idp/STSAuthenticationProvider.java  | 307 ---------
 .../idp/STSKrbAuthenticationProvider.java       | 259 --------
 .../cxf/fediz/service/idp/STSPortFilter.java    |  95 ---
 .../idp/STSPreAuthAuthenticationProvider.java   | 130 ----
 .../idp/STSUPAuthenticationProvider.java        | 131 ----
 .../cxf/fediz/service/idp/STSUserDetails.java   |  73 ---
 .../service/idp/beans/CacheSecurityToken.java   |  56 --
 .../service/idp/beans/CommonsURLValidator.java  |  52 --
 .../service/idp/beans/HomeRealmReminder.java    |  43 --
 .../idp/beans/IdpTokenExpiredAction.java        |  69 --
 .../fediz/service/idp/beans/LogoutAction.java   |  45 --
 .../idp/beans/PassiveRequestorValidator.java    |  76 ---
 .../idp/beans/ProcessHRDSExpressionAction.java  |  72 --
 .../service/idp/beans/STSClientAction.java      | 439 -------------
 .../idp/beans/SigninParametersCacheAction.java  | 185 ------
 .../service/idp/beans/TokenSerializer.java      |  62 --
 .../idp/beans/TrustedIdpProtocolAction.java     | 100 ---
 .../idp/beans/samlsso/AuthnRequestParser.java   | 388 -----------
 .../idp/beans/samlsso/LocalRedirectCreator.java |  54 --
 .../idp/beans/samlsso/SamlResponseCreator.java  | 187 ------
 .../beans/samlsso/SamlResponseErrorCreator.java |  97 ---
 .../service/idp/beans/wsfed/WfreshParser.java   |  84 ---
 .../fediz/service/idp/domain/Application.java   | 242 -------
 .../cxf/fediz/service/idp/domain/Claim.java     |  79 ---
 .../fediz/service/idp/domain/Entitlement.java   |  70 --
 .../service/idp/domain/FederationType.java      |  40 --
 .../cxf/fediz/service/idp/domain/Idp.java       | 304 ---------
 .../fediz/service/idp/domain/RequestClaim.java  |  49 --
 .../cxf/fediz/service/idp/domain/Role.java      |  74 ---
 .../cxf/fediz/service/idp/domain/TrustType.java |  40 --
 .../fediz/service/idp/domain/TrustedIdp.java    | 187 ------
 .../KerberosAuthenticationProcessingFilter.java | 199 ------
 .../idp/kerberos/KerberosEntryPoint.java        |  70 --
 .../kerberos/KerberosServiceRequestToken.java   | 150 -----
 .../idp/kerberos/KerberosTokenValidator.java    | 185 ------
 .../idp/kerberos/PassThroughKerberosClient.java |  80 ---
 .../service/idp/metadata/IdpMetadataWriter.java | 180 -----
 .../idp/metadata/ServiceMetadataWriter.java     | 214 ------
 .../cxf/fediz/service/idp/model/IDPConfig.java  |  44 --
 .../fediz/service/idp/model/RequestClaim.java   |  26 -
 .../fediz/service/idp/model/ServiceConfig.java  |  35 -
 .../service/idp/model/TrustedIDPConfig.java     |  30 -
 .../service/idp/model/TrustedIDPSelection.java  |  36 -
 ...AbstractTrustedIdpOAuth2ProtocolHandler.java | 207 ------
 .../AbstractTrustedIdpProtocolHandler.java      |  58 --
 .../ApplicationProtocolControllerImpl.java      |  60 --
 .../ApplicationSAMLSSOProtocolHandler.java      |  57 --
 .../ApplicationWSFedProtocolHandler.java        |  57 --
 .../idp/protocols/ProtocolController.java       |  32 -
 .../TrustedIdpFacebookProtocolHandler.java      | 226 -------
 .../TrustedIdpOIDCProtocolHandler.java          | 335 ----------
 .../TrustedIdpProtocolControllerImpl.java       |  60 --
 .../TrustedIdpSAMLProtocolHandler.java          | 415 ------------
 .../TrustedIdpWSFedProtocolHandler.java         | 231 -------
 .../service/idp/rest/ApplicationService.java    |  88 ---
 .../idp/rest/ApplicationServiceImpl.java        | 151 -----
 .../fediz/service/idp/rest/Applications.java    |  49 --
 .../fediz/service/idp/rest/ClaimService.java    |  72 --
 .../service/idp/rest/ClaimServiceImpl.java      | 106 ---
 .../cxf/fediz/service/idp/rest/Claims.java      |  50 --
 .../service/idp/rest/EntitlementService.java    |  73 ---
 .../idp/rest/EntitlementServiceImpl.java        |  98 ---
 .../fediz/service/idp/rest/Entitlements.java    |  49 --
 .../cxf/fediz/service/idp/rest/IdpService.java  | 114 ----
 .../fediz/service/idp/rest/IdpServiceImpl.java  | 240 -------
 .../apache/cxf/fediz/service/idp/rest/Idps.java |  49 --
 .../idp/rest/QueryResourceInfoComparator.java   | 114 ----
 .../idp/rest/RestServiceExceptionMapper.java    |  83 ---
 .../cxf/fediz/service/idp/rest/RoleService.java |  88 ---
 .../fediz/service/idp/rest/RoleServiceImpl.java | 134 ----
 .../cxf/fediz/service/idp/rest/Roles.java       |  49 --
 .../cxf/fediz/service/idp/rest/RootService.java |  39 --
 .../fediz/service/idp/rest/RootServiceImpl.java |  60 --
 .../service/idp/rest/TrustedIdpService.java     |  71 --
 .../service/idp/rest/TrustedIdpServiceImpl.java |  93 ---
 .../cxf/fediz/service/idp/rest/TrustedIdps.java |  49 --
 .../idp/samlsso/SAML2CallbackHandler.java       | 148 -----
 .../samlsso/SAML2PResponseComponentBuilder.java | 127 ----
 .../service/idp/samlsso/SAMLAuthnRequest.java   |  74 ---
 .../service/idp/service/ApplicationDAO.java     |  43 --
 .../cxf/fediz/service/idp/service/ClaimDAO.java |  38 --
 .../service/idp/service/ConfigService.java      |  32 -
 .../idp/service/ConfigServiceSpring.java        |  76 ---
 .../service/idp/service/EntitlementDAO.java     |  38 --
 .../cxf/fediz/service/idp/service/IdpDAO.java   |  53 --
 .../cxf/fediz/service/idp/service/RoleDAO.java  |  43 --
 .../service/idp/service/TrustedIdpDAO.java      |  38 --
 .../idp/service/jpa/ApplicationClaimEntity.java |  83 ---
 .../idp/service/jpa/ApplicationDAOJPAImpl.java  | 254 --------
 .../idp/service/jpa/ApplicationEntity.java      | 214 ------
 .../ApplicationIdpProtocolSupportValidator.java |  54 --
 .../jpa/ApplicationProtocolSupported.java       |  47 --
 .../idp/service/jpa/ClaimDAOJPAImpl.java        | 143 ----
 .../service/idp/service/jpa/ClaimEntity.java    |  71 --
 .../idp/service/jpa/ConfigServiceJPA.java       |  96 ---
 .../service/jpa/DBInitApplicationListener.java  |  73 ---
 .../fediz/service/idp/service/jpa/DBLoader.java |  28 -
 .../service/idp/service/jpa/DBLoaderImpl.java   | 163 -----
 .../service/idp/service/jpa/DBLoaderSpring.java | 129 ----
 .../idp/service/jpa/EntitlementDAOJPAImpl.java  | 142 ----
 .../idp/service/jpa/EntitlementEntity.java      |  72 --
 .../service/idp/service/jpa/IdpDAOJPAImpl.java  | 367 -----------
 .../service/idp/service/jpa/IdpEntity.java      | 301 ---------
 .../service/idp/service/jpa/RoleDAOJPAImpl.java | 206 ------
 .../service/idp/service/jpa/RoleEntity.java     |  77 ---
 .../idp/service/jpa/TrustedIdpDAOJPAImpl.java   | 154 -----
 .../idp/service/jpa/TrustedIdpEntity.java       | 201 ------
 .../jpa/TrustedIdpProtocolSupportValidator.java |  54 --
 .../jpa/TrustedIdpProtocolSupported.java        |  47 --
 .../security/GrantedAuthorityEntitlements.java  | 100 ---
 .../idp/spi/ApplicationProtocolHandler.java     |  33 -
 .../fediz/service/idp/spi/ProtocolHandler.java  |  25 -
 .../idp/spi/TrustedIdpProtocolHandler.java      |  40 --
 .../cxf/fediz/service/idp/util/WebUtils.java    | 209 ------
 .../idp/src/main/resources/META-INF/orm.xml     | 183 ------
 .../resources/META-INF/spring-persistence.xml   |  30 -
 .../idp/service/jpa/ApplicationDAOJPATest.java  | 348 ----------
 .../idp/service/jpa/ClaimDAOJPATest.java        | 115 ----
 .../idp/service/jpa/EntitlementDAOJPATest.java  | 115 ----
 .../service/idp/service/jpa/IdpDAOJPATest.java  | 653 -------------------
 .../service/idp/service/jpa/TestDBLoader.java   |  93 ---
 .../idp/service/jpa/TrustedIdpDAOJPATest.java   | 202 ------
 .../service/idp/util/MetadataWriterTest.java    |  57 --
 services/idp/src/test/resources/idp-config.xml  | 152 -----
 .../src/test/resources/persistence.properties   |  14 -
 .../idp/src/test/resources/realm.properties     |   4 -
 services/idp/src/test/resources/realma.cert     |  15 -
 .../src/test/resources/stsKeystoreA.properties  |   6 -
 services/idp/src/test/resources/stsrealm_a.jks  | Bin 2061 -> 0 bytes
 services/idp/src/test/resources/testContext.xml |  54 --
 services/pom.xml                                |   1 +
 301 files changed, 18843 insertions(+), 15831 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/README.txt
----------------------------------------------------------------------
diff --git a/services/idp-core/README.txt b/services/idp-core/README.txt
new file mode 100644
index 0000000..55ed9a5
--- /dev/null
+++ b/services/idp-core/README.txt
@@ -0,0 +1,57 @@
+Building and Installating the IDP
+=================================
+
+IPD Realm A
+-----------
+
+Build the IDP:
+mvn clean install -Prealm-a
+
+Deploy the war target/fediz-idp.war to <tomcat-base-dir>/webapps (default https port: 9443)
+
+IPD Realm B
+-----------
+
+Build the IDP:
+mvn clean install -Prealm-b
+
+Deploy the war target/fediz-idp-remote.war to <tomcat-base-dir>/webapps (default https port: 12443)
+
+Hint: Servlet Context name different for Remote IDP to get different Cookies.
+      Cookies are bound to hostname (default: localhost) and path whereas port is not relevant.
+
+
+IDP WARs deployed in Servlet Container with different HTTPS ports
+-----------------------------------------------------------------
+
+1) update src/main/filters/realm-a/env.properties
+...
+realmA.port=9443
+realmB.port=12443
+...
+
+2) update src/main/filters/realm-b/env.properties
+...
+realmA.port=9443
+realmB.port=12443
+...
+
+
+Building and launching the IDP embedded
+=======================================
+
+You can launch the IDP from Maven to reduce time in setting up an separate Serlvet Container. The Maven Jetty plugin can be used to deploy the idp and optionally the sts component.
+
+The IDP can be started with:
+
+mvn -Pstandalone,realm-a,sts
+
+If you test the REST/JPA layer, you don't have to start the sts as well (profile 'sts').
+If you test WS-Federation with the IDP, you must start the sts as well.
+The profile 'standalone' means to start jetty embedded. You can launch both profiles in two different shells (but you MUST NOT run 'clean') otherwise you remove the war, db files of the other IDP.
+
+The following properties are supported idp.https.port, idp.http.port
+
+Default port for profile 'realm-a': 9443, 9080
+Default port for profile 'realm-b': 12443, 12080
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/pom.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/pom.xml b/services/idp-core/pom.xml
new file mode 100644
index 0000000..1b09751
--- /dev/null
+++ b/services/idp-core/pom.xml
@@ -0,0 +1,356 @@
+<?xml version="1.0"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.apache.cxf.fediz</groupId>
+        <artifactId>fediz</artifactId>
+        <version>1.4.0-SNAPSHOT</version>
+        <relativePath>../../pom.xml</relativePath>
+    </parent>
+    <artifactId>fediz-idp-core</artifactId>
+    <name>Apache Fediz IDP Core</name>
+    <packaging>jar</packaging>
+    
+    <properties>
+        <swagger-ui.version>2.2.6</swagger-ui.version>
+    </properties>
+    
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-jdbc</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-tx</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+            <dependency>
+                <groupId>org.springframework</groupId>
+                <artifactId>spring-aop</artifactId>
+                <version>${spring.version}</version>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+    <dependencies>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>${junit.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.servlet</groupId>
+            <artifactId>servlet-api</artifactId>
+            <version>${servlet.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf.fediz</groupId>
+            <artifactId>fediz-core</artifactId>
+            <version>${project.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-webmvc</artifactId>
+            <version>${spring.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-tx</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-orm</artifactId>
+            <version>${spring.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-web</artifactId>
+            <version>${spring.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework</groupId>
+            <artifactId>spring-test</artifactId>
+            <version>${spring.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.webflow</groupId>
+            <artifactId>spring-webflow</artifactId>
+            <version>2.4.4.RELEASE</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-web</artifactId>
+            <version>${spring.security.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.security</groupId>
+            <artifactId>spring-security-config</artifactId>
+            <version>${spring.security.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.javassist</groupId>
+            <artifactId>javassist</artifactId>
+            <version>${javassist.version}</version>
+            <scope>runtime</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-log4j12</artifactId>
+            <version>${slf4j.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-ws-security</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-rs-security-sso-saml</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-rs-security-sso-oidc</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-transports-http</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-ws-policy</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-ws-addr</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-rs-service-description-swagger</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.commons</groupId>
+            <artifactId>commons-lang3</artifactId>
+            <version>${commons.lang.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-rs-service-description</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-rs-extension-providers</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>com.fasterxml.jackson.jaxrs</groupId>
+            <artifactId>jackson-jaxrs-json-provider</artifactId>
+            <version>2.8.6</version>
+        </dependency>
+        <dependency>
+            <groupId>org.hsqldb</groupId>
+            <artifactId>hsqldb</artifactId>
+            <version>${hsqldb.version}</version>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>cglib</groupId>
+            <artifactId>cglib-nodep</artifactId>
+            <version>3.2.4</version>
+        </dependency>
+        <!-- 
+        <dependency>
+            <groupId>org.apache.openjpa</groupId>
+            <artifactId>openjpa-all</artifactId>
+            <version>${openjpa.version}</version>
+        </dependency>
+        -->
+        <dependency>
+            <groupId>org.apache.commons</groupId> 
+            <artifactId>commons-dbcp2</artifactId>
+            <version>${dbcp.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.openjpa</groupId>
+            <artifactId>openjpa-jdbc</artifactId>
+            <version>${openjpa.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.openjpa</groupId>
+            <artifactId>openjpa-persistence-jdbc</artifactId>
+            <version>${openjpa.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.cxf</groupId>
+            <artifactId>cxf-rt-rs-client</artifactId>
+            <version>${cxf.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>javax.validation</groupId>
+            <artifactId>validation-api</artifactId>
+            <version>${javax.validation.version}</version>
+        </dependency>
+        <dependency>
+            <groupId>jstl</groupId>
+            <artifactId>jstl</artifactId>
+            <version>1.2</version>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.bval</groupId>
+            <artifactId>bval-jsr</artifactId>
+            <version>${bval.version}</version>
+            <exclusions>
+                <exclusion>
+                    <groupId>com.sun.xml.bind</groupId>
+                    <artifactId>jaxb-impl</artifactId>
+                </exclusion>
+                <!-- 
+                dependency to newer version (commons-beanutils)
+                imported from commons-validator
+                -->
+                <exclusion>
+                    <groupId>commons-beanutils</groupId>
+                    <artifactId>commons-beanutils-core</artifactId>
+                </exclusion>
+            </exclusions>
+        </dependency>
+        <dependency>
+            <groupId>commons-validator</groupId>
+            <artifactId>commons-validator</artifactId>
+            <version>${commons.validator.version}</version>
+        </dependency>
+    </dependencies>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.apache.openjpa</groupId>
+                <artifactId>openjpa-maven-plugin</artifactId>
+                <version>${openjpa.version}</version>
+                <inherited>true</inherited>
+                <configuration>
+                    <persistenceXmlFile>${project.basedir}/src/main/resources/META-INF/spring-persistence.xml</persistenceXmlFile>
+                    <includes>org/apache/cxf/fediz/service/idp/service/jpa/**/*.class</includes>
+                </configuration>
+                <executions>
+                    <execution>
+                        <id>enhancer</id>
+                        <phase>process-classes</phase>
+                        <goals>
+                            <goal>enhance</goal>
+                        </goals>
+                    </execution>
+                </executions>
+                <dependencies>
+                    <dependency>
+                        <groupId>xerces</groupId>
+                        <artifactId>xercesImpl</artifactId>
+                        <version>2.11.0</version>
+                    </dependency>
+                </dependencies>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-dependency-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <phase>generate-resources</phase>
+                        <goals>
+                            <goal>unpack</goal>
+                        </goals>
+                        <configuration>
+                            <artifactItems>
+                                <artifactItem>
+                                    <groupId>org.webjars</groupId>
+                                    <artifactId>swagger-ui</artifactId>
+                                    <version>${swagger-ui.version}</version>
+                                    <overWrite>true</overWrite>
+                                    <outputDirectory>${project.build.directory}/swagger-ui</outputDirectory>
+                                    <excludes>**/*.gz</excludes>
+                                </artifactItem>
+                            </artifactItems>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-resources-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <id>copy-swagger-resources-in-place</id>
+                        <phase>process-resources</phase>
+                        <goals>
+                            <goal>copy-resources</goal>
+                        </goals>
+                        <configuration>
+                            <outputDirectory>${project.build.directory}/${project.build.finalName}/resources/swagger</outputDirectory>
+                            <resources>
+                                <resource>
+                                    <directory>${project.build.directory}/swagger-ui/META-INF/resources/webjars/swagger-ui/${swagger-ui.version}</directory>
+                                    <excludes>
+                                        <exclude>index.html</exclude>
+                                        <exclude>swagger-ui.min.js</exclude>
+                                    </excludes>
+                                </resource>
+                            </resources>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-antrun-plugin</artifactId>
+                <inherited>true</inherited>
+                <executions>
+                    <execution>
+                        <id>addMatrixParamSupport</id>
+                        <phase>process-resources</phase>
+                        <goals>
+                            <goal>run</goal>
+                        </goals>
+                        <configuration>
+                            <target>
+                                <replace file="${project.build.directory}/swagger-ui/META-INF/resources/webjars/swagger-ui/${swagger-ui.version}/swagger-ui.js" token="return url + requestUrl + querystring;" value="&#xA;var matrixstring = '';&#xA; for (var i = 0; i &lt; this.parameters.length; i++) {&#xA; var param = this.parameters[i];&#xA; &#xA; if (param.in === 'matrix') {&#xA; matrixstring += ';' + this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);&#xA;     }&#xA;   }&#xA; &#xA;   var url = this.scheme + '://' + this.host;&#xA; &#xA;   if (this.basePath !== '/') {&#xA;     url += this.basePath;&#xA;   }&#xA;   return url + requestUrl + matrixstring + querystring;" />
+                            </target>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+
+</project>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/filters/realm-a/env.properties
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/filters/realm-a/env.properties b/services/idp-core/src/main/filters/realm-a/env.properties
new file mode 100644
index 0000000..dd59a8b
--- /dev/null
+++ b/services/idp-core/src/main/filters/realm-a/env.properties
@@ -0,0 +1,6 @@
+realm.STS_URI=REALMA
+realmA.port=9443
+realmB.port=12443
+idp-config=idp-config-realma.xml
+db-load-config=entities-realma.xml
+realm-uri=urn:org:apache:cxf:fediz:idp:realm-A
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/filters/realm-b/env.properties
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/filters/realm-b/env.properties b/services/idp-core/src/main/filters/realm-b/env.properties
new file mode 100644
index 0000000..d3134fd
--- /dev/null
+++ b/services/idp-core/src/main/filters/realm-b/env.properties
@@ -0,0 +1,6 @@
+realm.STS_URI=REALMB
+realmA.port=9443
+realmB.port=12443
+idp-config=idp-config-realmb.xml
+db-load-config=entities-realmb.xml
+realm-uri=urn:org:apache:cxf:fediz:idp:realm-B
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/FedizEntryPoint.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/FedizEntryPoint.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/FedizEntryPoint.java
new file mode 100644
index 0000000..dd121fb
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/FedizEntryPoint.java
@@ -0,0 +1,172 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.Enumeration;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.cxf.fediz.core.FederationConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.service.ConfigService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.springframework.beans.BeansException;
+import org.springframework.beans.factory.InitializingBean;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.AuthenticationEntryPoint;
+import org.springframework.util.Assert;
+
+
+/**
+ * Used by the <code>ExceptionTranslationFilter</code> to commence authentication
+ * <p>
+ * The user's browser will be redirected to the IDP.
+ *
+ */
+public class FedizEntryPoint implements AuthenticationEntryPoint,
+    InitializingBean, ApplicationContextAware {
+
+    private static final Logger LOG = LoggerFactory.getLogger(FedizEntryPoint.class);
+
+    private ApplicationContext appContext;
+    private ConfigService configService;
+    private String realm;
+    private Idp idpConfig;
+
+    public ConfigService getConfigService() {
+        return configService;
+    }
+
+    public void setConfigService(ConfigService configService) {
+        this.configService = configService;
+    }
+
+    public String getRealm() {
+        return realm;
+    }
+
+    public void setRealm(String realm) {
+        this.realm = realm;
+    }
+
+    public void afterPropertiesSet() throws Exception {
+        Assert.notNull(this.appContext, "ApplicationContext cannot be null.");
+        Assert.notNull(this.configService, "ConfigService cannot be null.");
+        Assert.notNull(this.realm, "realm cannot be null.");
+    }
+
+    public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response,
+            final AuthenticationException authenticationException) throws IOException, ServletException {
+
+        idpConfig = configService.getIDP(realm);
+        Assert.notNull(this.idpConfig, "idpConfig cannot be null. Check realm and config service implementation");
+
+        String wauth = servletRequest.getParameter(FederationConstants.PARAM_AUTH_TYPE);
+        if (wauth == null) {
+            wauth = "default";
+        }
+        String loginUri = idpConfig.getAuthenticationURIs().get(wauth);
+        if (loginUri == null) {
+            LOG.warn("wauth value '" + wauth + "' not supported");
+            response.sendError(
+                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The wauth value that was supplied is not supported");
+            return;
+        }
+
+        StringBuilder builder = new StringBuilder(extractFullContextPath(servletRequest))
+            .append(loginUri).append("?");
+
+        // Add the query parameters - URL encoding them for safety
+        @SuppressWarnings("unchecked")
+        Enumeration<String> names = servletRequest.getParameterNames();
+        while (names.hasMoreElements()) {
+            String name = names.nextElement();
+            String[] values = servletRequest.getParameterValues(name);
+            if (values != null && values.length > 0) {
+                builder.append(name).append("=");
+                builder.append(URLEncoder.encode(values[0], "UTF-8"));
+                builder.append("&");
+            }
+        }
+        // Remove trailing ampersand
+        if (builder.charAt(builder.length() - 1) == '&') {
+            builder.deleteCharAt(builder.length() - 1);
+        }
+
+        String redirectUrl = builder.toString();
+        preCommence(servletRequest, response);
+        if (LOG.isInfoEnabled()) {
+            LOG.info("Redirect to " + redirectUrl);
+        }
+        response.sendRedirect(redirectUrl);
+    }
+
+
+    /**
+     * Template method for you to do your own pre-processing before the redirect occurs.
+     *
+     * @param request the HttpServletRequest
+     * @param response the HttpServletResponse
+     */
+    protected void preCommence(final HttpServletRequest request, final HttpServletResponse response) {
+
+    }
+
+    @Override
+    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
+        this.appContext = applicationContext;
+    }
+
+    protected String extractFullContextPath(HttpServletRequest request) throws MalformedURLException {
+        String result = null;
+        String contextPath = request.getContextPath();
+        String requestUrl = request.getRequestURL().toString();
+
+        String requestPath = new URL(requestUrl).getPath();
+        // Cut request path of request url and add context path if not ROOT
+        if (requestPath != null && requestPath.length() > 0) {
+            int lastIndex = requestUrl.lastIndexOf(requestPath);
+            result = requestUrl.substring(0, lastIndex);
+        } else {
+            result = requestUrl;
+        }
+        if (contextPath != null && contextPath.length() > 0) {
+            // contextPath contains starting slash
+            result = result + contextPath;
+        }
+        if (result.charAt(result.length() - 1) != '/') {
+            result = result + "/";
+        }
+        return result;
+    }
+
+
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/IdpConstants.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/IdpConstants.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/IdpConstants.java
new file mode 100644
index 0000000..1e2969b
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/IdpConstants.java
@@ -0,0 +1,60 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+public final class IdpConstants {
+
+    public static final String IDP_CONFIG = "idpConfig";
+
+    /**
+     * A key used to store context/state when communicating with a trusted third party IdP.
+     */
+    public static final String TRUSTED_IDP_CONTEXT = "trusted_idp_context";
+
+    /**
+     * A key used to store the application realm for the given request.
+     */
+    public static final String REALM = "realm";
+
+    /**
+     * A key used to store the home realm for the given request.
+     */
+    public static final String HOME_REALM = "home_realm";
+
+    /**
+     * The SAML Authn Request
+     */
+    public static final String SAML_AUTHN_REQUEST = "saml_authn_request";
+
+    /**
+     * A Context variable associated with the request (independent of protocol)
+     */
+    public static final String CONTEXT = "request_context";
+
+    /**
+     * A key used to store the return address for the given request
+     */
+    public static final String RETURN_ADDRESS = "return_address";
+
+
+    private IdpConstants() {
+        // complete
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/IdpSTSClient.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/IdpSTSClient.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/IdpSTSClient.java
new file mode 100644
index 0000000..b8450b4
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/IdpSTSClient.java
@@ -0,0 +1,52 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+import org.w3c.dom.Element;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.trust.STSClient;
+
+public class IdpSTSClient extends STSClient {
+
+    public IdpSTSClient(Bus b) {
+        super(b);
+    }
+
+    public Element requestSecurityTokenResponse() throws Exception {
+        return requestSecurityTokenResponse(null);
+    }
+
+    public Element requestSecurityTokenResponse(String appliesTo) throws Exception {
+        String action = null;
+        if (isSecureConv) {
+            action = namespace + "/RST/SCT";
+        }
+        return requestSecurityTokenResponse(appliesTo, action, "/Issue", null);
+    }
+
+    public Element requestSecurityTokenResponse(String appliesTo, String action,
+            String requestType, SecurityToken target) throws Exception {
+        STSResponse response = issue(appliesTo, null, "/Issue", null);
+
+        return getDocumentElement(response.getResponse());
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/MetadataServlet.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/MetadataServlet.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/MetadataServlet.java
new file mode 100644
index 0000000..0aab857
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/MetadataServlet.java
@@ -0,0 +1,111 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.w3c.dom.Document;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.metadata.IdpMetadataWriter;
+import org.apache.cxf.fediz.service.idp.metadata.ServiceMetadataWriter;
+import org.apache.cxf.fediz.service.idp.service.ConfigService;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.ApplicationContext;
+import org.springframework.web.context.support.WebApplicationContextUtils;
+
+
+public class MetadataServlet extends HttpServlet {
+
+    public static final String PARAM_REALM = "realm";
+    
+    private static final Logger LOG = LoggerFactory
+        .getLogger(MetadataServlet.class);
+    private static final long serialVersionUID = 1L;
+    
+    private ApplicationContext applicationContext;
+    private String realm;
+    
+    
+    @Override
+    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
+        IOException {
+        response.setContentType("text/xml; charset=utf-8");
+        PrintWriter out = response.getWriter();
+        
+        ConfigService cs = (ConfigService)getApplicationContext().getBean("config");
+        Idp idpConfig = cs.getIDP(realm);
+        try {
+            if (request.getServletPath() != null && request.getServletPath().startsWith("/metadata")) {
+                String serviceRealm = 
+                    request.getRequestURI().substring(request.getRequestURI().indexOf("/metadata")
+                                                      + "/metadata".length());
+                if (serviceRealm != null && serviceRealm.charAt(0) == '/') {
+                    serviceRealm = serviceRealm.substring(1);
+                }
+                TrustedIdp trustedIdp = idpConfig.findTrustedIdp(serviceRealm);
+                if (trustedIdp == null) {
+                    LOG.error("No TrustedIdp found for desired realm: " + serviceRealm);
+                    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
+                    return;
+                }
+                ServiceMetadataWriter mw = new ServiceMetadataWriter();
+                Document metadata = mw.getMetaData(idpConfig, trustedIdp);
+                out.write(DOM2Writer.nodeToString(metadata));
+            } else {
+                // Otherwise return the Metadata for the Idp
+                LOG.debug(idpConfig.toString());
+                IdpMetadataWriter mw = new IdpMetadataWriter();
+                Document metadata = mw.getMetaData(idpConfig);
+                out.write(DOM2Writer.nodeToString(metadata));
+            }
+        } catch (Exception ex) {
+            LOG.error("Failed to get metadata document: ", ex);
+            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+        }
+    }
+
+    @Override
+    public void init(ServletConfig config) throws ServletException {
+        super.init(config);
+        realm = config.getInitParameter(PARAM_REALM);
+        if (realm == null || realm.length() == 0) {
+            throw new ServletException("Servlet parameter '" + PARAM_REALM + "' not defined");
+        }
+    }
+
+    public ApplicationContext getApplicationContext() {
+        if (applicationContext == null) {
+            LOG.debug(this.getServletContext().toString());
+            applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
+        }
+        return applicationContext;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSAuthenticationProvider.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSAuthenticationProvider.java
new file mode 100644
index 0000000..4e8ed11
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSAuthenticationProvider.java
@@ -0,0 +1,307 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.w3c.dom.Element;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.BusFactory;
+//import org.apache.cxf.endpoint.Client;
+import org.apache.cxf.fediz.core.Claim;
+import org.apache.cxf.fediz.core.ClaimTypes;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.opensaml.core.xml.XMLObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.authentication.AuthenticationProvider;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+//import org.apache.cxf.transport.http.HTTPConduit;
+//import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
+
+/**
+ * A base class for authenticating credentials to the STS
+ */
+public abstract class STSAuthenticationProvider implements AuthenticationProvider {
+
+    public static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER = 
+        "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
+    
+    public static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512 = 
+        "http://docs.oasis-open.org/ws-sx/ws-trust/200512/";
+    
+    public static final String HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST =
+        "http://schemas.xmlsoap.org/ws/2005/02/trust";
+    
+    private static final Logger LOG = LoggerFactory.getLogger(STSAuthenticationProvider.class);
+
+    protected String wsdlLocation;
+    
+    protected String namespace = HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512;
+    
+    protected String wsdlService;
+
+    protected String wsdlEndpoint;
+
+    protected String appliesTo;
+    
+    protected boolean use200502Namespace;
+    
+    protected String tokenType;
+    
+    protected Bus bus;
+    
+    protected Integer lifetime;
+    
+    //Required to get IDP roles to use the IDP application, used in future release
+    protected String roleURI;
+    
+    protected Map<String, Object> properties = new HashMap<>();
+    
+    private String customSTSParameter;
+    
+    protected List<GrantedAuthority> createAuthorities(SecurityToken token) throws WSSecurityException {
+        List<GrantedAuthority> authorities = new ArrayList<>();
+        //authorities.add(new SimpleGrantedAuthority("ROLE_AUTHENTICATED"));
+        //Not needed because AuthenticatedVoter has been added for SecurityFlowExecutionListener
+        if (roleURI != null) {
+            SamlAssertionWrapper assertion = new SamlAssertionWrapper(token.getToken());
+            
+            List<Claim> claims = parseClaimsInAssertion(assertion.getSaml2());
+            for (Claim c : claims) {
+                if (c.getClaimType() != null && roleURI.equals(c.getClaimType().toString())) {
+                    Object oValue = c.getValue();
+                    if ((oValue instanceof List<?>) && !((List<?>)oValue).isEmpty()) {
+                        List<?> values = (List<?>)oValue;
+                        for (Object role: values) {
+                            if (role instanceof String) {
+                                authorities.add(new SimpleGrantedAuthority((String)role));
+                            }
+                        }
+                    } else {
+                        LOG.error("Unsupported value type of Claim value");
+                        throw new IllegalStateException("Unsupported value type of Claim value");
+                    }
+                    claims.remove(c);
+                    break;
+                }
+            }
+        }
+        
+        //Add IDP_LOGIN role to be able to access resource Idp, TrustedIdp, etc.
+        authorities.add(new SimpleGrantedAuthority("ROLE_IDP_LOGIN"));
+        
+        return authorities;
+    }
+    
+    public String getWsdlLocation() {
+        return wsdlLocation;
+    }
+
+    public void setWsdlLocation(String wsdlLocation) {
+        this.wsdlLocation = wsdlLocation;
+    }
+
+    public String getWsdlService() {
+        return wsdlService;
+    }
+
+    public void setWsdlService(String wsdlService) {
+        this.wsdlService = wsdlService;
+    }
+
+    public String getWsdlEndpoint() {
+        return wsdlEndpoint;
+    }
+
+    public void setWsdlEndpoint(String wsdlEndpoint) {
+        this.wsdlEndpoint = wsdlEndpoint;
+    }
+    
+    public String getNamespace() {
+        return namespace;
+    }
+
+    public void setNamespace(String namespace) {
+        this.namespace = namespace;
+    }
+
+    public String getAppliesTo() {
+        return appliesTo;
+    }
+
+    public void setAppliesTo(String appliesTo) {
+        this.appliesTo = appliesTo;
+    }
+    
+    public void setBus(Bus bus) {
+        this.bus = bus;
+    }
+
+    public Bus getBus() {
+        // do not store a referance to the default bus
+        return (bus != null) ? bus : BusFactory.getDefaultBus();
+    }
+
+    public String getTokenType() {
+        return tokenType;
+    }
+
+    public void setTokenType(String tokenType) {
+        this.tokenType = tokenType;
+    }
+    
+    public Integer getLifetime() {
+        return lifetime;
+    }
+
+    public void setLifetime(Integer lifetime) {
+        this.lifetime = lifetime;
+    }
+
+    protected List<Claim> parseClaimsInAssertion(org.opensaml.saml.saml2.core.Assertion assertion) {
+        List<org.opensaml.saml.saml2.core.AttributeStatement> attributeStatements = assertion
+        .getAttributeStatements();
+        if (attributeStatements == null || attributeStatements.isEmpty()) {
+            LOG.debug("No attribute statements found");
+            return Collections.emptyList();
+        }
+
+        List<Claim> collection = new ArrayList<>();
+        Map<String, Claim> claimsMap = new HashMap<>();
+
+        for (org.opensaml.saml.saml2.core.AttributeStatement statement : attributeStatements) {
+            LOG.debug("parsing statement: {}", statement.getElementQName());
+            List<org.opensaml.saml.saml2.core.Attribute> attributes = statement
+            .getAttributes();
+            for (org.opensaml.saml.saml2.core.Attribute attribute : attributes) {
+                LOG.debug("parsing attribute: {}", attribute.getName());
+                Claim c = new Claim();
+                // Workaround for CXF-4484 
+                // Value of Attribute Name not fully qualified
+                // if NameFormat is http://schemas.xmlsoap.org/ws/2005/05/identity/claims
+                // but ClaimType value must be fully qualified as Namespace attribute goes away
+                URI attrName = URI.create(attribute.getName());
+                if (ClaimTypes.URI_BASE.toString().equals(attribute.getNameFormat())
+                    && !attrName.isAbsolute()) {
+                    c.setClaimType(URI.create(ClaimTypes.URI_BASE + "/" + attribute.getName()));
+                } else {
+                    c.setClaimType(URI.create(attribute.getName()));
+                }
+                c.setIssuer(assertion.getIssuer().getNameQualifier());
+
+                List<String> valueList = new ArrayList<>();
+                for (XMLObject attributeValue : attribute.getAttributeValues()) {
+                    Element attributeValueElement = attributeValue.getDOM();
+                    String value = attributeValueElement.getTextContent();
+                    LOG.debug(" [{}]", value);
+                    valueList.add(value);
+                }
+                mergeClaimToMap(claimsMap, c, valueList);
+            }
+        }
+        collection.addAll(claimsMap.values());
+        return collection;
+
+    }
+    
+    protected void mergeClaimToMap(Map<String, Claim> claimsMap, Claim c,
+                                   List<String> valueList) {
+        Claim t = claimsMap.get(c.getClaimType().toString());
+        if (t != null) {
+            //same SAML attribute already processed. Thus Claim object already created.
+            Object oValue = t.getValue();
+            if (oValue instanceof String) {
+                //one child element AttributeValue only
+                List<String> values = new ArrayList<>();
+                values.add((String)oValue); //add existing value
+                values.addAll(valueList);
+                t.setValue(values);
+            } else if (oValue instanceof List<?>) {
+                //more than one child element AttributeValue
+                @SuppressWarnings("unchecked")
+                List<String> values = (List<String>)oValue;
+                values.addAll(valueList);
+                t.setValue(values);
+            } else {
+                LOG.error("Unsupported value type of Claim value");
+                throw new IllegalStateException("Unsupported value type of Claim value");
+            }
+        } else {
+            if (valueList.size() == 1) {
+                c.setValue(valueList.get(0));
+            } else {
+                c.setValue(valueList);
+            }
+            // Add claim to map
+            claimsMap.put(c.getClaimType().toString(), c);
+        }
+    }
+
+    public String getRoleURI() {
+        return roleURI;
+    }
+
+    public void setRoleURI(String roleURI) {
+        this.roleURI = roleURI;
+    }
+    
+    public void setProperties(Map<String, Object> p) {
+        properties.putAll(p);
+    }
+
+    public Map<String, Object> getProperties() {
+        return properties;
+    }
+
+    public boolean isUse200502Namespace() {
+        return use200502Namespace;
+    }
+
+    public void setUse200502Namespace(boolean use200502Namespace) {
+        this.use200502Namespace = use200502Namespace;
+    }
+
+    public String getCustomSTSParameter() {
+        return customSTSParameter;
+    }
+
+    public void setCustomSTSParameter(String customSTSParameter) {
+        this.customSTSParameter = customSTSParameter;
+    }
+
+//May be uncommented for debugging    
+//    private void setTimeout(Client client, Long timeout) {
+//        HTTPConduit conduit = (HTTPConduit) client.getConduit();
+//        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
+//        httpClientPolicy.setConnectionTimeout(timeout);
+//        httpClientPolicy.setReceiveTimeout(timeout);
+//        conduit.setClient(httpClientPolicy);
+//    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSKrbAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSKrbAuthenticationProvider.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSKrbAuthenticationProvider.java
new file mode 100644
index 0000000..62f4817
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSKrbAuthenticationProvider.java
@@ -0,0 +1,259 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.util.List;
+
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginException;
+import javax.xml.namespace.QName;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.fediz.service.idp.kerberos.KerberosServiceRequestToken;
+import org.apache.cxf.fediz.service.idp.kerberos.KerberosTokenValidator;
+import org.apache.cxf.fediz.service.idp.kerberos.PassThroughKerberosClient;
+import org.apache.cxf.ws.security.SecurityConstants;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.common.kerberos.KerberosServiceContext;
+import org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.wss4j.dom.WSConstants;
+import org.ietf.jgss.GSSContext;
+import org.ietf.jgss.GSSCredential;
+import org.ietf.jgss.GSSException;
+import org.ietf.jgss.GSSManager;
+import org.ietf.jgss.GSSName;
+import org.ietf.jgss.Oid;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.GrantedAuthority;
+
+/**
+ * An authentication provider to authenticate a Kerberos token to the STS
+ */
+public class STSKrbAuthenticationProvider extends STSAuthenticationProvider {
+
+    private static final Logger LOG = LoggerFactory.getLogger(STSKrbAuthenticationProvider.class);
+
+    private KerberosTokenValidator kerberosTokenValidator;
+    
+    private CallbackHandler kerberosCallbackHandler;
+    
+    private boolean kerberosUsernameServiceNameForm;
+    
+    private boolean requireDelegation;
+    
+    
+    @Override
+    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+        // We only handle KerberosServiceRequestTokens
+        if (!(authentication instanceof KerberosServiceRequestToken)) {
+            return null;
+        }
+        
+        Bus cxfBus = getBus();
+        IdpSTSClient sts = new IdpSTSClient(cxfBus);
+        sts.setAddressingNamespace("http://www.w3.org/2005/08/addressing");
+        if (tokenType != null && tokenType.length() > 0) {
+            sts.setTokenType(tokenType);
+        } else {
+            sts.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
+        }
+        sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
+        sts.setWsdlLocation(wsdlLocation);
+        sts.setServiceQName(new QName(namespace, wsdlService));
+        sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
+        
+        sts.getProperties().putAll(properties);
+        if (use200502Namespace) {
+            sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
+        }
+        
+        if (lifetime != null) {
+            sts.setEnableLifetime(true);
+            sts.setTtl(lifetime.intValue());
+        }
+        
+        return handleKerberos((KerberosServiceRequestToken)authentication, sts);
+    }
+    
+    private Authentication handleKerberos(
+        KerberosServiceRequestToken kerberosRequestToken,
+        IdpSTSClient sts
+    ) {
+        Principal kerberosPrincipal = null;
+        // 
+        // If delegation is required then validate the received token + store the
+        // Delegated Credential so that we can retrieve a new kerberos token for the
+        // STS with it. If delegation is not required, then we just get the received
+        // token + pass it to the STS
+        //
+        if (requireDelegation) {
+            kerberosPrincipal = validateKerberosToken(kerberosRequestToken, sts);
+            if (kerberosPrincipal == null) {
+                return null;
+            }
+        } else {
+            PassThroughKerberosClient kerberosClient = new PassThroughKerberosClient();
+            kerberosClient.setToken(kerberosRequestToken.getToken());
+            sts.getProperties().put(SecurityConstants.KERBEROS_CLIENT, kerberosClient);
+        }
+        
+        try {
+            // Line below may be uncommented for debugging    
+            // setTimeout(sts.getClient(), 3600000L);
+
+            SecurityToken token = sts.requestSecurityToken(this.appliesTo);
+            
+            if (kerberosPrincipal == null && token.getToken() != null
+                && "Assertion".equals(token.getToken().getLocalName())) {
+                // For the pass-through Kerberos case, we don't know the Principal name...
+                kerberosPrincipal = 
+                    new SAMLTokenPrincipalImpl(new SamlAssertionWrapper(token.getToken()));
+            }
+            
+            if (kerberosPrincipal == null) {
+                LOG.info("Failed to authenticate user '" + kerberosRequestToken.getName());
+                return null;
+            }
+            
+            List<GrantedAuthority> authorities = createAuthorities(token);
+            
+            KerberosServiceRequestToken ksrt = 
+                new KerberosServiceRequestToken(kerberosPrincipal, authorities, kerberosRequestToken.getToken());
+            
+            STSUserDetails details = new STSUserDetails(kerberosPrincipal.getName(),
+                                                        "",
+                                                        authorities,
+                                                        token);
+            ksrt.setDetails(details);
+            
+            LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), kerberosPrincipal.getName());
+            return ksrt;
+        } catch (Exception ex) {
+            LOG.info("Failed to authenticate user '" + kerberosRequestToken.getName() + "'", ex);
+            return null;
+        }
+    }
+    
+    private Principal validateKerberosToken(
+        KerberosServiceRequestToken token,
+        IdpSTSClient sts
+    ) {
+        if (kerberosTokenValidator == null) {
+            LOG.error("KerberosTokenValidator must be configured to support kerberos "
+                + "credential delegation");
+            return null;
+        }
+        KerberosServiceContext kerberosContext;
+        Principal kerberosPrincipal = null;
+        try {
+            kerberosContext = kerberosTokenValidator.validate(token);
+            if (kerberosContext == null || kerberosContext.getDelegationCredential() == null) {
+                LOG.info("Kerberos Validation failure");
+                return null;
+            }
+            GSSCredential delegatedCredential = kerberosContext.getDelegationCredential();
+            sts.getProperties().put(SecurityConstants.DELEGATED_CREDENTIAL, 
+                                    delegatedCredential);
+            sts.getProperties().put(SecurityConstants.KERBEROS_USE_CREDENTIAL_DELEGATION, "true");
+            kerberosPrincipal = kerberosContext.getPrincipal();
+        } catch (LoginException ex) {
+            LOG.info("Failed to authenticate user", ex);
+            return null;
+        } catch (PrivilegedActionException ex) {
+            LOG.info("Failed to authenticate user", ex);
+            return null;
+        }
+
+        if (kerberosTokenValidator.getContextName() != null) {
+            sts.getProperties().put(SecurityConstants.KERBEROS_JAAS_CONTEXT_NAME, 
+                                    kerberosTokenValidator.getContextName());
+        }
+        if (kerberosTokenValidator.getServiceName() != null) {
+            sts.getProperties().put(SecurityConstants.KERBEROS_SPN,
+                                    kerberosTokenValidator.getServiceName());
+        }
+        if (kerberosCallbackHandler != null) {
+            sts.getProperties().put(SecurityConstants.CALLBACK_HANDLER, 
+                                    kerberosCallbackHandler);
+        }
+        if (kerberosUsernameServiceNameForm) {
+            sts.getProperties().put(SecurityConstants.KERBEROS_IS_USERNAME_IN_SERVICENAME_FORM, 
+                                    "true");
+        }
+        
+        return kerberosPrincipal;
+    }
+    
+    protected GSSContext createGSSContext() throws GSSException {
+        Oid oid = new Oid("1.2.840.113554.1.2.2");
+
+        GSSManager gssManager = GSSManager.getInstance();
+
+        String spn = "bob@service.ws.apache.org";
+        GSSName gssService = gssManager.createName(spn, null);
+
+        return gssManager.createContext(gssService.canonicalize(oid),
+                                        oid, null, GSSContext.DEFAULT_LIFETIME);
+
+    }
+
+    @Override
+    public boolean supports(Class<?> authentication) {
+        return authentication.equals(KerberosServiceRequestToken.class);
+    }
+    
+    public KerberosTokenValidator getKerberosTokenValidator() {
+        return kerberosTokenValidator;
+    }
+
+    public void setKerberosTokenValidator(KerberosTokenValidator kerberosTokenValidator) {
+        this.kerberosTokenValidator = kerberosTokenValidator;
+    }
+
+    public CallbackHandler getKerberosCallbackHandler() {
+        return kerberosCallbackHandler;
+    }
+
+    public void setKerberosCallbackHandler(CallbackHandler kerberosCallbackHandler) {
+        this.kerberosCallbackHandler = kerberosCallbackHandler;
+    }
+
+    public boolean isKerberosUsernameServiceNameForm() {
+        return kerberosUsernameServiceNameForm;
+    }
+
+    public void setKerberosUsernameServiceNameForm(boolean kerberosUsernameServiceNameForm) {
+        this.kerberosUsernameServiceNameForm = kerberosUsernameServiceNameForm;
+    }
+
+    public boolean isRequireDelegation() {
+        return requireDelegation;
+    }
+
+    public void setRequireDelegation(boolean requireDelegation) {
+        this.requireDelegation = requireDelegation;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSPortFilter.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSPortFilter.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSPortFilter.java
new file mode 100644
index 0000000..889dadd
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSPortFilter.java
@@ -0,0 +1,95 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.BeansException;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.ApplicationContextAware;
+import org.springframework.util.Assert;
+import org.springframework.web.filter.GenericFilterBean;
+
+public class STSPortFilter extends GenericFilterBean implements ApplicationContextAware {
+
+    private static final Logger LOG = LoggerFactory.getLogger(STSPortFilter.class);
+    
+    private ApplicationContext applicationContext;
+    private STSAuthenticationProvider authenticationProvider;
+    
+    private boolean isPortSet;
+    
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+        throws IOException, ServletException {
+        
+        Assert.isTrue(applicationContext != null, "Application context must not be null");
+        STSAuthenticationProvider authProvider = authenticationProvider;
+        if (authProvider == null) {
+            authProvider = applicationContext.getBean(STSAuthenticationProvider.class);
+        }
+        Assert.isTrue(authProvider != null, "STSAuthenticationProvider must be configured");
+        
+        //Only update the port if HTTPS is used, otherwise ignored (like retrieving the WADL over HTTP)
+        if (!isPortSet && request.isSecure()) {
+            try {
+                URL url = new URL(authProvider.getWsdlLocation());
+                if (url.getPort() == 0) {
+                    URL updatedUrl = new URL(url.getProtocol(), url.getHost(), request.getLocalPort(), url.getFile());
+                    setSTSWsdlUrl(authProvider, updatedUrl.toString());
+                    LOG.info("STSAuthenticationProvider.wsdlLocation set to " + updatedUrl.toString());
+                } else {
+                    setSTSWsdlUrl(authProvider, url.toString());
+                }
+            } catch (MalformedURLException e) {
+                LOG.error("Invalid Url '" + authProvider.getWsdlLocation() + "': "  + e.getMessage());
+            }
+        }
+        
+        chain.doFilter(request, response);
+    }
+
+    private synchronized void setSTSWsdlUrl(STSAuthenticationProvider authProvider, String wsdlUrl) {
+        authProvider.setWsdlLocation(wsdlUrl);
+        this.isPortSet = true;
+    }
+    
+    @Override
+    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
+        this.applicationContext = applicationContext;
+    }
+
+    public STSAuthenticationProvider getAuthenticationProvider() {
+        return authenticationProvider;
+    }
+
+    public void setAuthenticationProvider(STSAuthenticationProvider authenticationProvider) {
+        this.authenticationProvider = authenticationProvider;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSPreAuthAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSPreAuthAuthenticationProvider.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSPreAuthAuthenticationProvider.java
new file mode 100644
index 0000000..45ec0a3
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSPreAuthAuthenticationProvider.java
@@ -0,0 +1,130 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+import javax.xml.namespace.QName;
+
+import org.w3c.dom.Document;
+import org.apache.cxf.Bus;
+import org.apache.cxf.fediz.core.util.DOMUtils;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.dom.WSConstants;
+import org.apache.xml.security.exceptions.XMLSecurityException;
+import org.apache.xml.security.keys.content.X509Data;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
+
+/**
+ * An authentication provider to authenticate a preauthenticated token to the STS
+ */
+public class STSPreAuthAuthenticationProvider extends STSAuthenticationProvider {
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(STSPreAuthAuthenticationProvider.class);
+
+    @Override
+    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+        // We only handle PreAuthenticatedAuthenticationTokens
+        if (!(authentication instanceof PreAuthenticatedAuthenticationToken)) {
+            return null;
+        }
+        
+        Bus cxfBus = getBus();
+        IdpSTSClient sts = new IdpSTSClient(cxfBus);
+        sts.setAddressingNamespace("http://www.w3.org/2005/08/addressing");
+        if (tokenType != null && tokenType.length() > 0) {
+            sts.setTokenType(tokenType);
+        } else {
+            sts.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
+        }
+        sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
+        sts.setWsdlLocation(wsdlLocation);
+        sts.setServiceQName(new QName(namespace, wsdlService));
+        sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
+        
+        sts.getProperties().putAll(properties);
+        if (use200502Namespace) {
+            sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
+        }
+        
+        if (lifetime != null) {
+            sts.setEnableLifetime(true);
+            sts.setTtl(lifetime.intValue());
+        }
+        
+        return handlePreAuthenticated((PreAuthenticatedAuthenticationToken)authentication, sts);
+    }
+    
+    private Authentication handlePreAuthenticated(
+        PreAuthenticatedAuthenticationToken preauthenticatedToken,
+        IdpSTSClient sts
+    ) {
+        X509Certificate cert = (X509Certificate)preauthenticatedToken.getCredentials();
+        if (cert == null) {
+            return null;
+        }
+        
+        // Convert the received certificate to a DOM Element to write it out "OnBehalfOf"
+        Document doc = DOMUtils.createDocument();
+        X509Data certElem = new X509Data(doc);
+        try {
+            certElem.addCertificate(cert);
+            sts.setOnBehalfOf(certElem.getElement());
+        } catch (XMLSecurityException e) {
+            LOG.debug("Error parsing a client certificate", e);
+            return null;
+        }
+        
+        try {
+            // Line below may be uncommented for debugging    
+            // setTimeout(sts.getClient(), 3600000L);
+
+            SecurityToken token = sts.requestSecurityToken(this.appliesTo);
+            
+            List<GrantedAuthority> authorities = createAuthorities(token);
+            
+            STSUserDetails details = new STSUserDetails(preauthenticatedToken.getName(),
+                                                        "",
+                                                        authorities,
+                                                        token);
+            
+            preauthenticatedToken.setDetails(details);
+            
+            LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), preauthenticatedToken.getName());
+            return preauthenticatedToken;
+            
+        } catch (Exception ex) {
+            LOG.info("Failed to authenticate user '" + preauthenticatedToken.getName() + "'", ex);
+            return null;
+        }
+    }
+
+    @Override
+    public boolean supports(Class<?> authentication) {
+        return authentication.equals(PreAuthenticatedAuthenticationToken.class);
+    }
+    
+}


[02/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPAImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPAImpl.java
deleted file mode 100644
index 5603e39..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPAImpl.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-import org.apache.cxf.fediz.service.idp.service.EntitlementDAO;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Repository;
-import org.springframework.transaction.annotation.Transactional;
-
-
-@Repository
-@Transactional
-public class EntitlementDAOJPAImpl implements EntitlementDAO {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(EntitlementDAOJPAImpl.class);
-
-    private EntityManager em;
-    
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-    
-    @Override
-    public List<Entitlement> getEntitlements(int start, int size) {
-        List<Entitlement> list = new ArrayList<>();
-        
-        Query query = null;
-        query = em.createQuery("select e from Entitlement e");
-        
-        //@SuppressWarnings("rawtypes")
-        List<?> entitlementEntities = query
-            .setFirstResult(start)
-            .setMaxResults(size)
-            .getResultList();
-
-        for (Object obj : entitlementEntities) {
-            EntitlementEntity entity = (EntitlementEntity) obj;
-            list.add(entity2domain(entity));
-        }
-        
-        return list;
-    }
-    
-    @Override
-    public Entitlement addEntitlement(Entitlement entitlement) {
-        EntitlementEntity entity = new EntitlementEntity();
-        domain2entity(entitlement, entity);
-        em.persist(entity);
-        
-        LOG.debug("Entitlement '{}' added", entitlement.getName());
-        return entity2domain(entity);
-    }
-
-    @Override
-    public Entitlement getEntitlement(String name) {
-        return entity2domain(getEntitlementEntity(name, em));
-    }
-
-    @Override
-    public void updateEntitlement(String name, Entitlement entitlement) {
-        Query query = null;
-        query = em.createQuery("select e from Entitlement e where e.name=:name");
-        query.setParameter("name", name);
-        
-        //@SuppressWarnings("rawtypes")
-        EntitlementEntity entitlementEntity = (EntitlementEntity)query.getSingleResult();
-        
-        domain2entity(entitlement, entitlementEntity);
-        
-        LOG.debug("Entitlement '{}' added", entitlement.getName());
-        em.persist(entitlementEntity);
-    }
-
-    @Override
-    public void deleteEntitlement(String name) {
-        Query query = null;
-        query = em.createQuery("select e from Entitlement e where e.name=:name");
-        query.setParameter("name", name);
-        
-        //@SuppressWarnings("rawtypes")
-        Object entitlementObj = query.getSingleResult();
-        em.remove(entitlementObj);
-        
-        LOG.debug("Entitlement '{}' deleted", name);
-    }
-    
-    static EntitlementEntity getEntitlementEntity(String name, EntityManager em) {
-        Query query = null;
-        query = em.createQuery("select e from Entitlement e where e.name=:name");
-        query.setParameter("name", name);
-        
-        //@SuppressWarnings("rawtypes")
-        return (EntitlementEntity)query.getSingleResult();
-    }
-    
-    public static void domain2entity(Entitlement entitlement, EntitlementEntity entity) {
-        //The ID must not be updated if the entity has got an id already (update case)
-        if (entitlement.getId() > 0) {
-            entity.setId(entitlement.getId());
-        }
-        //property 'internal' can't be changed, default is false
-        entity.setName(entitlement.getName());
-        entity.setDescription(entitlement.getDescription());
-    }
-    
-    public static Entitlement entity2domain(EntitlementEntity entity) {
-        Entitlement entitlement = new Entitlement();
-        entitlement.setId(entity.getId());
-        entitlement.setName(entity.getName());
-        entitlement.setDescription(entity.getDescription());
-        entitlement.setInternal(entity.isInternal());
-        return entitlement;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementEntity.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementEntity.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementEntity.java
deleted file mode 100644
index aec6b91..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementEntity.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-
-import org.apache.openjpa.persistence.jdbc.Index;
-
-@Entity(name = "Entitlement")
-public class EntitlementEntity {
-    
-    @Id
-    private int id;
-    
-    @Index
-    private String name;
-    
-    private String description;
-    
-    //Internal entities can't be updated, changed and deleted
-    //Default: false
-    private boolean internal;
-        
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-
-    public boolean isInternal() {
-        return internal;
-    }
-
-    public void setInternal(boolean internal) {
-        this.internal = internal;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPAImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPAImpl.java
deleted file mode 100644
index 5025a25..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPAImpl.java
+++ /dev/null
@@ -1,367 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityNotFoundException;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.service.IdpDAO;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Repository;
-import org.springframework.transaction.annotation.Transactional;
-
-@Repository
-@Transactional
-public class IdpDAOJPAImpl implements IdpDAO {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(IdpDAOJPAImpl.class);
-
-    private EntityManager em;
-    
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-    
-    @Override
-    public List<Idp> getIdps(int start, int size, List<String> expandList) {
-        List<Idp> list = new ArrayList<>();
-        
-        Query query = null;
-        query = em.createQuery("select i from IDP i");
-        
-        /*List serviceEntities = query.setFirstResult(start)
-            .setMaxResults(size)
-            .getResultList();*/
-        
-        //@SuppressWarnings("rawtypes")
-        List<?> idpEntities = query
-            .setFirstResult(start)
-            .setMaxResults(size)
-            .getResultList();
-    
-        for (Object obj : idpEntities) {
-            IdpEntity entity = (IdpEntity) obj;
-            list.add(entity2domain(entity, expandList));
-        }
-        return list;
-    }
-    
-    @Override
-    public Idp getIdp(String realm, List<String> expandList) {
-        Query query = null;
-        query = em.createQuery("select i from IDP i where i.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        Object idpObj = query.getSingleResult();
-        return entity2domain((IdpEntity)idpObj, expandList);
-    }
-    
-    @Override
-    public Idp addIdp(Idp idp) {
-        IdpEntity entity = new IdpEntity();
-        domain2entity(idp, entity);
-        em.persist(entity);
-        
-        LOG.debug("IDP '{}' added", idp.getRealm());
-        return entity2domain(entity, Arrays.asList("all"));
-    }
-
-    @Override
-    public void updateIdp(String realm, Idp idp) {
-        Query query = null;
-        query = em.createQuery("select i from IDP i where i.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        IdpEntity idpEntity = (IdpEntity)query.getSingleResult();
-        
-        domain2entity(idp, idpEntity);
-        
-        em.persist(idpEntity);
-        
-        LOG.debug("IDP '{}' updated", idp.getRealm());
-    }
-
-    @Override
-    public void deleteIdp(String realm) {
-        Query query = null;
-        query = em.createQuery("select i from IDP i where i.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        Object idpObj = query.getSingleResult();
-        em.remove(idpObj);
-        
-        LOG.debug("IDP '{}' deleted", realm);
-    }
-    
-    @Override
-    public void addApplicationToIdp(Idp idp, Application application) {
-        IdpEntity idpEntity = null;
-        if (idp.getId() != 0) {
-            idpEntity = em.find(IdpEntity.class, idp.getId());
-        } else {
-            idpEntity = getIdpEntity(idp.getRealm(), em);
-        }
-        
-        ApplicationEntity applicationEntity = null;
-        if (application.getId() != 0) {
-            applicationEntity = em.find(ApplicationEntity.class, application.getId());
-        } else {
-            applicationEntity = ApplicationDAOJPAImpl.getApplicationEntity(application.getRealm(), em);
-        }
-        
-        idpEntity.getApplications().add(applicationEntity);
-        
-        LOG.debug("Application '{}' added to IDP '{}'", application.getRealm(), idp.getRealm());
-    }
-    
-    @Override
-    public void removeApplicationFromIdp(Idp idp, Application application) {
-        IdpEntity idpEntity = null;
-        if (idp.getId() != 0) {
-            idpEntity = em.find(IdpEntity.class, idp.getId());
-        } else {
-            idpEntity = getIdpEntity(idp.getRealm(), em);
-        }
-        
-        ApplicationEntity applicationEntity = null;
-        if (application.getId() != 0) {
-            applicationEntity = em.find(ApplicationEntity.class, application.getId());
-        } else {
-            applicationEntity = ApplicationDAOJPAImpl.getApplicationEntity(application.getRealm(), em);
-        }
-        
-        if (applicationEntity == null) {
-            throw new EntityNotFoundException("ApplicationEntity not found");
-        }
-        
-        if (!idpEntity.getApplications().remove(applicationEntity)) {
-            throw new EntityNotFoundException("ApplicationEntity not assigned to IdpEntity");
-        }
-                
-        LOG.debug("Application '{}' removed from IDP '{}'", application.getRealm(), idp.getRealm());
-    }
-    
-    @Override
-    public void addTrustedIdpToIdp(Idp idp, TrustedIdp trustedIdp) {
-        IdpEntity idpEntity = null;
-        if (idp.getId() != 0) {
-            idpEntity = em.find(IdpEntity.class, idp.getId());
-        } else {
-            idpEntity = getIdpEntity(idp.getRealm(), em);
-        }
-        
-        TrustedIdpEntity trustedIdpEntity = null;
-        if (trustedIdp.getId() != 0) {
-            trustedIdpEntity = em.find(TrustedIdpEntity.class, trustedIdp.getId());
-        } else {
-            trustedIdpEntity = TrustedIdpDAOJPAImpl.getTrustedIdpEntity(trustedIdp.getRealm(), em);
-        }
-        
-        idpEntity.getTrustedIdps().add(trustedIdpEntity);
-        
-        LOG.debug("Trusted IDP '{}' added to IDP '{}'", trustedIdp.getRealm(), idp.getRealm());
-    }
-    
-    @Override
-    public void removeTrustedIdpFromIdp(Idp idp, TrustedIdp trustedIdp) {
-        IdpEntity idpEntity = null;
-        if (idp.getId() != 0) {
-            idpEntity = em.find(IdpEntity.class, idp.getId());
-        } else {
-            idpEntity = getIdpEntity(idp.getRealm(), em);
-        }
-        
-        TrustedIdpEntity trustedIdpEntity = null;
-        if (trustedIdp.getId() != 0) {
-            trustedIdpEntity = em.find(TrustedIdpEntity.class, trustedIdp.getId());
-        } else {
-            trustedIdpEntity = TrustedIdpDAOJPAImpl.getTrustedIdpEntity(trustedIdp.getRealm(), em);
-        }
-        
-        idpEntity.getTrustedIdps().remove(trustedIdpEntity);
-        
-        LOG.debug("Trusted IDP '{}' removed from IDP '{}'", trustedIdp.getRealm(), idp.getRealm());
-    }
-        
-    @Override
-    public void addClaimToIdp(Idp idp, Claim claim) {
-        IdpEntity idpEntity = null;
-        if (idp.getId() != 0) {
-            idpEntity = em.find(IdpEntity.class, idp.getId());
-        } else {
-            idpEntity = getIdpEntity(idp.getRealm(), em);
-        }
-        
-        ClaimEntity claimEntity = null;
-        if (claim.getId() != 0) {
-            claimEntity = em.find(ClaimEntity.class, claim.getId());
-        } else {
-            claimEntity = ClaimDAOJPAImpl.getClaimEntity(claim.getClaimType().toString(), em);
-        }
-        
-        idpEntity.getClaimTypesOffered().add(claimEntity);
-        
-        LOG.debug("Claim '{}' added to IDP '{}'", claim.getClaimType(), idp.getRealm());
-    }
-    
-    @Override
-    public void removeClaimFromIdp(Idp idp, Claim claim) {
-        IdpEntity idpEntity = null;
-        if (idp.getId() != 0) {
-            idpEntity = em.find(IdpEntity.class, idp.getId());
-        } else {
-            idpEntity = getIdpEntity(idp.getRealm(), em);
-        }
-        if (idpEntity == null) {
-            throw new EntityNotFoundException("IdpEntity not found");
-        }
-        
-        ClaimEntity claimEntity = null;
-        if (claim.getId() != 0) {
-            claimEntity = em.find(ClaimEntity.class, claim.getId());
-        } else {
-            claimEntity = ClaimDAOJPAImpl.getClaimEntity(claim.getClaimType().toString(), em);
-        }
-        if (claimEntity == null) {
-            throw new EntityNotFoundException("ClaimEntity not found");
-        }
-        
-        if (!idpEntity.getClaimTypesOffered().remove(claimEntity)) {
-            throw new EntityNotFoundException("ClaimEntity not assigned to IdpEntity");
-        }
-        
-        LOG.debug("Claim '{}' removed from IDP '{}'", claim.getClaimType(), idp.getRealm());
-    }
-    
-    static IdpEntity getIdpEntity(String realm, EntityManager em) {
-        Query query = null;
-        query = em.createQuery("select i from IDP i where i.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        return (IdpEntity)query.getSingleResult();
-    }
-    
-    public static void domain2entity(Idp idp, IdpEntity entity) {
-        //The ID must not be updated if the entity has got an id already (update case)
-        if (idp.getId() > 0) {
-            entity.setId(idp.getId());
-        }
-        
-        entity.setCertificate(idp.getCertificate());
-        entity.setCertificatePassword(idp.getCertificatePassword());
-        entity.setRealm(idp.getRealm());
-        entity.setServiceDescription(idp.getServiceDescription());
-        entity.setServiceDisplayName(idp.getServiceDisplayName());
-        entity.setHrds(idp.getHrds());
-        entity.setIdpUrl(idp.getIdpUrl());
-        entity.setProvideIdpList(idp.isProvideIdpList());
-        entity.setStsUrl(idp.getStsUrl());
-        entity.setUri(idp.getUri());
-        entity.setUseCurrentIdp(idp.isUseCurrentIdp());
-        entity.setRpSingleSignOutConfirmation(idp.isRpSingleSignOutConfirmation());
-        entity.setRpSingleSignOutCleanupConfirmation(idp.isRpSingleSignOutCleanupConfirmation());
-        
-        entity.getAuthenticationURIs().clear();
-        for (Map.Entry<String, String> item : idp.getAuthenticationURIs().entrySet()) {
-            entity.getAuthenticationURIs().put(item.getKey(), item.getValue());
-        }
-        
-        entity.getTokenTypesOffered().clear();
-        for (String item : idp.getTokenTypesOffered()) {
-            entity.getTokenTypesOffered().add(item);
-        }
-        
-        entity.getSupportedProtocols().clear();
-        for (String item : idp.getSupportedProtocols()) {
-            entity.getSupportedProtocols().add(item);
-        }        
-    }
-
-    
-    public static Idp entity2domain(IdpEntity entity, List<String> expandList) {
-        Idp idp = new Idp();
-        idp.setId(entity.getId());
-        idp.setCertificate(entity.getCertificate());
-        idp.setCertificatePassword(entity.getCertificatePassword());
-        idp.setRealm(entity.getRealm());
-        idp.setServiceDescription(entity.getServiceDescription());
-        idp.setServiceDisplayName(entity.getServiceDisplayName());
-        idp.setHrds(entity.getHrds());
-        idp.setIdpUrl(entity.getIdpUrl());
-        idp.setProvideIdpList(entity.isProvideIdpList());
-        idp.setStsUrl(entity.getStsUrl());
-        idp.setUri(entity.getUri());
-        idp.setUseCurrentIdp(entity.isUseCurrentIdp());
-        idp.setRpSingleSignOutConfirmation(entity.isRpSingleSignOutConfirmation());
-        idp.setRpSingleSignOutCleanupConfirmation(entity.isRpSingleSignOutCleanupConfirmation());
-        
-        if (expandList != null && (expandList.contains("all") || expandList.contains("applications"))) {
-            for (ApplicationEntity item : entity.getApplications()) {
-                Application application = ApplicationDAOJPAImpl.entity2domain(item, expandList);
-                idp.getApplications().add(application);
-            }
-        }
-        
-        if (expandList != null && (expandList.contains("all") || expandList.contains("trusted-idps"))) {
-            for (TrustedIdpEntity item : entity.getTrustedIdps()) {
-                TrustedIdp trustedIdp = TrustedIdpDAOJPAImpl.entity2domain(item);
-                idp.getTrustedIdps().add(trustedIdp);
-            }
-        }
-        
-        for (Map.Entry<String, String> item : entity.getAuthenticationURIs().entrySet()) {
-            idp.getAuthenticationURIs().put(item.getKey(), item.getValue());
-        }
-        
-        for (String item : entity.getTokenTypesOffered()) {
-            idp.getTokenTypesOffered().add(item);
-        }
-        
-        for (String item : entity.getSupportedProtocols()) {
-            idp.getSupportedProtocols().add(item);
-        }
-        
-        if (expandList != null && (expandList.contains("all") || expandList.contains("claims"))) {
-            for (ClaimEntity item : entity.getClaimTypesOffered()) {
-                idp.getClaimTypesOffered().add(ClaimDAOJPAImpl.entity2domain(item));
-            }
-        }
-        
-        return idp;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpEntity.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpEntity.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpEntity.java
deleted file mode 100644
index 986b28d..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpEntity.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.persistence.CascadeType;
-import javax.persistence.CollectionTable;
-import javax.persistence.Column;
-import javax.persistence.ElementCollection;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToMany;
-import javax.persistence.MapKeyColumn;
-import javax.validation.constraints.NotNull;
-
-import org.apache.openjpa.persistence.jdbc.Index;
-
-@Entity(name = "IDP")
-public class IdpEntity {
-
-    @Id
-    private int id;
-
-    // Unique
-    // fed:TargetScope
-    @Index
-    @NotNull
-    private String realm; // wtrealm, whr
-
-    // Unique
-    // https://<host>:<port>/fediz-idp/<IDP uri>/
-    private String uri;
-
-    // Home Realm Discovery Service
-    // Spring EL
-    private String hrds;
-
-    // if HRDS can't determine the home realm, should
-    // the list of trusted IDPs be shown to make a choice
-    private boolean provideIdpList;
-
-    // If HRDS can't discover a home realm and displaying IDP list is not
-    // enabled
-    // it falls back to current IDP if an authentication domain is configured
-    private boolean useCurrentIdp;
-
-    // Store certificate in DB or filesystem, provide options?
-    // md:KeyDescriptor, use="signing"
-    private String certificate;
-
-    // Password to read the private key to sign metadata document
-    private String certificatePassword;
-
-    // fed:SecurityTokenSerivceEndpoint
-    @NotNull
-    private URL stsUrl;
-
-    // fedl:PassiveRequestorEndpoint
-    // published hostname, port must be configured
-    @NotNull
-    private URL idpUrl;
-    
-    private boolean rpSingleSignOutConfirmation;
-
-    // RoleDescriptor protocolSupportEnumeration=
-    // "http://docs.oasis-open.org/wsfed/federation/200706"
-    // "http://docs.oasis-open.org/ws-sx/ws-trust/200512"
-    // Could be more in the future
-    
-    @ElementCollection
-    @CollectionTable(name = "idp_protocols")
-    @Column(name = "protocol")
-    private List<String> supportedProtocols = new ArrayList<>();
-
-    // list of RPs and RP-IDPs from whom we accept SignInResponse
-    // which includes RP IDPs
-    // key: wtrealm
-    @ManyToMany(cascade = CascadeType.ALL)
-    private List<ApplicationEntity> applications = new ArrayList<>();
-
-    // list of trusted IDP from whom we accept SignInResponse
-    // key: whr
-    @ManyToMany(cascade = CascadeType.ALL)
-    private List<TrustedIdpEntity> trustedIdps = new ArrayList<>();
-
-    // which URI to redirect for authentication
-    // fediz-idp/<IDP uri>/login/auth/<auth URI>
-    // wauth to auth URI mapping
-    @ElementCollection
-    @MapKeyColumn(name = "name")
-    @Column(name = "value")
-    @CollectionTable(name = "idp_auth_uris", joinColumns = @JoinColumn(name = "idp_id"))
-    private Map<String, String> authenticationURIs = new HashMap<>();
-
-    // required to create Federation Metadata document
-    // fed:TokenTypesOffered
-    //[TODO] Tokens could be managed independently, but no real impact in IDP at runtime
-    //       Only informational purpose for metadata document, but required in STS
-    @ElementCollection
-    @CollectionTable(name = "idp_tokentypes")
-    @Column(name = "tokentype")
-    private List<String> tokenTypesOffered = new ArrayList<>();
-
-    // fed:ClaimTypesOffered
-    @ManyToMany(cascade = CascadeType.ALL)
-    private List<ClaimEntity> claimTypesOffered = new ArrayList<>();
-
-    // ServiceDisplayName
-    @NotNull
-    private String serviceDisplayName;
-
-    // ServiceDescription
-    private String serviceDescription;
-    
-    private boolean rpSingleSignOutCleanupConfirmation;
-
-
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    public String getRealm() {
-        return realm;
-    }
-
-    public void setRealm(String realm) {
-        this.realm = realm;
-    }
-
-    public String getUri() {
-        return uri;
-    }
-
-    public void setUri(String uri) {
-        this.uri = uri;
-    }
-
-    public String getHrds() {
-        return hrds;
-    }
-
-    public void setHrds(String hrds) {
-        this.hrds = hrds;
-    }
-
-    public boolean isProvideIdpList() {
-        return provideIdpList;
-    }
-
-    public void setProvideIdpList(boolean provideIdpList) {
-        this.provideIdpList = provideIdpList;
-    }
-
-    public boolean isUseCurrentIdp() {
-        return useCurrentIdp;
-    }
-
-    public void setUseCurrentIdp(boolean useCurrentIdp) {
-        this.useCurrentIdp = useCurrentIdp;
-    }
-
-    public String getCertificate() {
-        return certificate;
-    }
-
-    public void setCertificate(String certificate) {
-        this.certificate = certificate;
-    }
-
-    public String getCertificatePassword() {
-        return certificatePassword;
-    }
-
-    public void setCertificatePassword(String password) {
-        this.certificatePassword = password;
-    }
-
-    public URL getStsUrl() {
-        return stsUrl;
-    }
-
-    public void setStsUrl(URL stsUrl) {
-        this.stsUrl = stsUrl;
-    }
-
-    public URL getIdpUrl() {
-        return idpUrl;
-    }
-
-    public void setIdpUrl(URL idpUrl) {
-        this.idpUrl = idpUrl;
-    }
-
-    public List<String> getSupportedProtocols() {
-        return supportedProtocols;
-    }
-
-    public void setSupportedProtocols(List<String> supportedProtocols) {
-        this.supportedProtocols = supportedProtocols;
-    }
-
-    public List<ApplicationEntity> getApplications() {
-        return applications;
-    }
-
-    public void setApplications(List<ApplicationEntity> applications) {
-        this.applications = applications;
-    }
-
-    public List<TrustedIdpEntity> getTrustedIdps() {
-        return trustedIdps;
-    }
-
-    public void setTrustedIdps(List<TrustedIdpEntity> trustedIdps) {
-        this.trustedIdps = trustedIdps;
-    }
-
-    public Map<String, String> getAuthenticationURIs() {
-        return authenticationURIs;
-    }
-
-    public void setAuthenticationURIs(Map<String, String> authenticationURIs) {
-        this.authenticationURIs = authenticationURIs;
-    }
-
-    public List<String> getTokenTypesOffered() {
-        return tokenTypesOffered;
-    }
-
-    public void setTokenTypesOffered(List<String> tokenTypesOffered) {
-        this.tokenTypesOffered = tokenTypesOffered;
-    }
-
-    public List<ClaimEntity> getClaimTypesOffered() {
-        return claimTypesOffered;
-    }
-
-    public void setClaimTypesOffered(List<ClaimEntity> claimTypesOffered) {
-        this.claimTypesOffered = claimTypesOffered;
-    }
-
-    public String getServiceDisplayName() {
-        return serviceDisplayName;
-    }
-
-    public void setServiceDisplayName(String serviceDisplayName) {
-        this.serviceDisplayName = serviceDisplayName;
-    }
-
-    public String getServiceDescription() {
-        return serviceDescription;
-    }
-
-    public void setServiceDescription(String serviceDescription) {
-        this.serviceDescription = serviceDescription;
-    }
-    
-    public boolean isRpSingleSignOutConfirmation() {
-        return rpSingleSignOutConfirmation;
-    }
-
-    public void setRpSingleSignOutConfirmation(boolean rpSingleSignOutConfirmation) {
-        this.rpSingleSignOutConfirmation = rpSingleSignOutConfirmation;
-    }
-
-    public boolean isRpSingleSignOutCleanupConfirmation() {
-        return rpSingleSignOutCleanupConfirmation;
-    }
-
-    public void setRpSingleSignOutCleanupConfirmation(boolean rpSingleSignOutCleanupConfirmation) {
-        this.rpSingleSignOutCleanupConfirmation = rpSingleSignOutCleanupConfirmation;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleDAOJPAImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleDAOJPAImpl.java
deleted file mode 100644
index 0493bf9..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleDAOJPAImpl.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityNotFoundException;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-import org.apache.cxf.fediz.service.idp.domain.Role;
-import org.apache.cxf.fediz.service.idp.service.RoleDAO;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Repository;
-import org.springframework.transaction.annotation.Transactional;
-
-@Repository
-@Transactional
-public class RoleDAOJPAImpl implements RoleDAO {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(RoleDAOJPAImpl.class);
-
-    private EntityManager em;
-    
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-    
-    @Override
-    public List<Role> getRoles(int start, int size, List<String> expandList) {
-        List<Role> list = new ArrayList<>();
-        
-        Query query = null;
-        query = em.createQuery("select r from Role r");
-        
-        //@SuppressWarnings("rawtypes")
-        List<?> roleEntities = query
-            .setFirstResult(start)
-            .setMaxResults(size)
-            .getResultList();
-    
-        for (Object obj : roleEntities) {
-            RoleEntity entity = (RoleEntity) obj;
-            list.add(entity2domain(entity, expandList));
-        }
-        return list;
-    }
-    
-    @Override
-    public Role getRole(String name, List<String> expandList) {
-        Query query = null;
-        query = em.createQuery("select r from Role r where r.name=:name");
-        query.setParameter("name", name);
-        
-        //@SuppressWarnings("rawtypes")
-        Object roleObj = query.getSingleResult();
-        return entity2domain((RoleEntity)roleObj, expandList);
-    }
-    
-    @Override
-    public Role addRole(Role role) {
-        RoleEntity entity = new RoleEntity();
-        domain2entity(role, entity);
-        em.persist(entity);
-        
-        LOG.debug("Role '{}' added", role.getName());
-        return entity2domain(entity, Arrays.asList("all"));
-    }
-
-    @Override
-    public void updateRole(String name, Role role) {
-        Query query = null;
-        query = em.createQuery("select r from Role r where r.name=:name");
-        query.setParameter("name", name);
-        
-        //@SuppressWarnings("rawtypes")
-        RoleEntity roleEntity = (RoleEntity)query.getSingleResult();
-        
-        domain2entity(role, roleEntity);
-        
-        em.persist(roleEntity);
-        
-        LOG.debug("Role '{}' updated", role.getName());
-    }
-
-    @Override
-    public void deleteRole(String name) {
-        Query query = null;
-        query = em.createQuery("select r from Role r where r.name=:name");
-        query.setParameter("name", name);
-        
-        //@SuppressWarnings("rawtypes")
-        Object roleObj = query.getSingleResult();
-        em.remove(roleObj);
-        
-        LOG.debug("Role '{}' deleted", name);
-    }
-    
-    @Override
-    public void addEntitlementToRole(Role role, Entitlement entitlement) {
-        RoleEntity roleEntity = null;
-        if (role.getId() != 0) {
-            roleEntity = em.find(RoleEntity.class, role.getId());
-        } else {
-            roleEntity = getRoleEntity(role.getName(), em);
-        }
-        
-        EntitlementEntity entitlementEntity = null;
-        if (entitlement.getId() != 0) {
-            entitlementEntity = em.find(EntitlementEntity.class, entitlement.getId());
-        } else {
-            entitlementEntity = EntitlementDAOJPAImpl.getEntitlementEntity(entitlement.getName(), em);
-        }
-        
-        roleEntity.getEntitlements().add(entitlementEntity);
-        
-        LOG.debug("Entitlement '{}' added to Role '{}'", entitlement.getName(), role.getName());
-    }
-    
-    @Override
-    public void removeEntitlementFromRole(Role role, Entitlement entitlement) {
-        RoleEntity roleEntity = null;
-        if (role.getId() != 0) {
-            roleEntity = em.find(RoleEntity.class, role.getId());
-        } else {
-            roleEntity = getRoleEntity(role.getName(), em);
-        }
-        
-        EntitlementEntity entitlementEntity = null;
-        if (entitlement.getId() != 0) {
-            entitlementEntity = em.find(EntitlementEntity.class, entitlement.getId());
-        } else {
-            entitlementEntity = EntitlementDAOJPAImpl.getEntitlementEntity(entitlement.getName(), em);
-        }
-        
-        if (entitlementEntity == null) {
-            throw new EntityNotFoundException("EntitlementEntity not found");
-        }
-        
-        if (!roleEntity.getEntitlements().remove(entitlementEntity)) {
-            throw new EntityNotFoundException("EntitlementEntity not assigned to RoleEntity");
-        }
-        
-        LOG.debug("Entitlement '{}' removed from Role '{}'", entitlement.getName(), role.getName());
-    }
-    
-    static RoleEntity getRoleEntity(String realm, EntityManager em) {
-        Query query = null;
-        query = em.createQuery("select i from IDP i where i.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        return (RoleEntity)query.getSingleResult();
-    }
-    
-    public static void domain2entity(Role role, RoleEntity entity) {
-        //The ID must not be updated if the entity has got an id already (update case)
-        if (role.getId() > 0) {
-            entity.setId(role.getId());
-        }
-        
-        entity.setName(role.getName());
-        entity.setDescription(role.getDescription());
-    }
-
-    
-    public static Role entity2domain(RoleEntity entity, List<String> expandList) {
-        Role role = new Role();
-        role.setId(entity.getId());
-        role.setName(entity.getName());
-        role.setDescription(entity.getDescription());
-        
-        if (expandList != null && (expandList.contains("all") || expandList.contains("entitlements"))) {
-            for (EntitlementEntity item : entity.getEntitlements()) {
-                Entitlement entitlement = EntitlementDAOJPAImpl.entity2domain(item);
-                role.getEntitlements().add(entitlement);
-            }
-        }
-        
-        return role;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleEntity.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleEntity.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleEntity.java
deleted file mode 100644
index 3b515c3..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleEntity.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.ManyToMany;
-
-import org.apache.openjpa.persistence.jdbc.Index;
-
-@Entity(name = "Role")
-public class RoleEntity {
-    
-    @Id
-    private int id;
-    
-    @Index
-    private String name;
-    
-    private String description;
-    
-    @ManyToMany(cascade = CascadeType.ALL)
-    private List<EntitlementEntity> entitlements = new ArrayList<>();
-    
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-    
-    public List<EntitlementEntity> getEntitlements() {
-        return entitlements;
-    }
-
-    public void setEntitlements(List<EntitlementEntity> entitlements) {
-        this.entitlements = entitlements;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPAImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPAImpl.java
deleted file mode 100644
index 16d05f1..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPAImpl.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.service.TrustedIdpDAO;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Repository;
-import org.springframework.transaction.annotation.Transactional;
-
-
-@Transactional
-@Repository
-public class TrustedIdpDAOJPAImpl implements TrustedIdpDAO {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpDAOJPAImpl.class);
-
-    private EntityManager em;
-    
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-    
-    @Override
-    public List<TrustedIdp> getTrustedIDPs(int start, int size) {
-        List<TrustedIdp> list = new ArrayList<>();
-        
-        Query query = null;
-        query = em.createQuery("select t from TrustedIDP t");
-        
-        List<?> idpEntities = query
-            .setFirstResult(start)
-            .setMaxResults(size)
-            .getResultList();
-
-        for (Object obj : idpEntities) {
-            TrustedIdpEntity entity = (TrustedIdpEntity) obj;
-            list.add(entity2domain(entity));
-        }
-        
-        return list;
-    }
-
-    @Override
-    public TrustedIdp getTrustedIDP(String realm) {
-        return entity2domain(getTrustedIdpEntity(realm, em));
-    }
-    
-    @Override
-    public TrustedIdp addTrustedIDP(TrustedIdp trustedIdp) {
-        TrustedIdpEntity entity = new TrustedIdpEntity();
-        domain2entity(trustedIdp, entity);
-        em.persist(entity);
-        
-        LOG.debug("Trusted IDP '" + trustedIdp.getRealm() + "' added");
-        return entity2domain(entity);
-    }
-    
-    @Override
-    public void updateTrustedIDP(String realm, TrustedIdp trustedIdp) {
-        TrustedIdpEntity trustedIdpEntity = getTrustedIdpEntity(realm, em);
-        
-        domain2entity(trustedIdp, trustedIdpEntity);
-        em.persist(trustedIdpEntity);
-        
-        LOG.debug("Trusted IDP '" + trustedIdp.getRealm() + "' updated");
-    }
-
-    @Override
-    public void deleteTrustedIDP(String realm) {
-        Query query = null;
-        query = em.createQuery("select t from TrustedIDP t where t.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        Object trustedIdpObj = query.getSingleResult();
-        em.remove(trustedIdpObj);
-        
-        LOG.debug("Trusted IDP '" + realm + "' deleted");
-    }
-    
-    static TrustedIdpEntity getTrustedIdpEntity(String realm, EntityManager em) {
-        Query query = null;
-        query = em.createQuery("select t from TrustedIDP t where t.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        return (TrustedIdpEntity)query.getSingleResult();
-    }
-    
-    public static void domain2entity(TrustedIdp trustedIDP, TrustedIdpEntity entity) {
-        //The ID must not be updated if the entity has got an id already (update case)
-        if (trustedIDP.getId() > 0) {
-            entity.setId(trustedIDP.getId());
-        }
-        entity.setCacheTokens(trustedIDP.isCacheTokens());
-        entity.setCertificate(trustedIDP.getCertificate());
-        entity.setDescription(trustedIDP.getDescription());
-        entity.setFederationType(trustedIDP.getFederationType());
-        entity.setLogo(trustedIDP.getLogo());
-        entity.setName(trustedIDP.getName());
-        entity.setProtocol(trustedIDP.getProtocol());
-        entity.setRealm(trustedIDP.getRealm());
-        entity.setIssuer(trustedIDP.getIssuer());
-        entity.setTrustType(trustedIDP.getTrustType());
-        entity.setUrl(trustedIDP.getUrl());
-        entity.setParameters(trustedIDP.getParameters());
-    }
-    
-    public static TrustedIdp entity2domain(TrustedIdpEntity entity) {
-        TrustedIdp trustedIDP = new TrustedIdp();
-        trustedIDP.setId(entity.getId());
-        trustedIDP.setCacheTokens(entity.isCacheTokens());
-        trustedIDP.setCertificate(entity.getCertificate());
-        trustedIDP.setDescription(entity.getDescription());
-        trustedIDP.setFederationType(entity.getFederationType());
-        trustedIDP.setLogo(entity.getLogo());
-        trustedIDP.setName(entity.getName());
-        trustedIDP.setProtocol(entity.getProtocol());
-        trustedIDP.setRealm(entity.getRealm());
-        trustedIDP.setIssuer(entity.getIssuer());
-        trustedIDP.setTrustType(entity.getTrustType());
-        trustedIDP.setUrl(entity.getUrl());
-        trustedIDP.setParameters(entity.getParameters());
-        return trustedIDP;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpEntity.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpEntity.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpEntity.java
deleted file mode 100644
index a4c6592..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpEntity.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.persistence.CollectionTable;
-import javax.persistence.Column;
-import javax.persistence.ElementCollection;
-import javax.persistence.Entity;
-import javax.persistence.EnumType;
-import javax.persistence.Enumerated;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.MapKeyColumn;
-import javax.validation.constraints.NotNull;
-
-import org.apache.cxf.fediz.service.idp.domain.FederationType;
-import org.apache.cxf.fediz.service.idp.domain.TrustType;
-import org.apache.openjpa.persistence.jdbc.Index;
-
-
-@Entity(name = "TrustedIDP")
-public class TrustedIdpEntity {
-
-    @Id
-    private int id;
-
-    //@Column(name = "REALM", nullable = true, length = FIELD_LENGTH)
-    @Index
-    @NotNull
-    private String realm;  //wtrealm, whr
-    
-    private String issuer;  //Validation of issuer name in SAMLResponse
-
-    // Should tokens be cached from trusted IDPs
-    // to avoid redirection to the trusted IDP again for next SignIn request
-    private boolean cacheTokens;
-    
-    //Could be read from Metadata, PassiveRequestorEndpoint
-    @NotNull
-    private String url;
-    
-    //Could be read from Metadata, md:KeyDescriptor, use="signing"
-    //Store certificate in DB or filesystem, provide options?
-    private String certificate;
-    
-    //Direct trust (signing cert imported), Indirect trust (CA certs imported, subject configured)
-    @Enumerated(EnumType.STRING)
-    private TrustType trustType;
-    
-    //Could be read from Metadata, RoleDescriptor protocolSupportEnumeration=
-    // "http://docs.oasis-open.org/wsfed/federation/200706"
-    // Metadata could provide more than one but one must be chosen
-    @TrustedIdpProtocolSupported
-    private String protocol;
-    
-    //FederateIdentity, FederateClaims
-    @Enumerated(EnumType.STRING)
-    private FederationType federationType;
-    
-    //optional (to provide a list of IDPs)
-    @NotNull
-    private String name;
-    
-    //optional (to provide a list of IDPs)
-    private String description;
-    
-    //optional (to provide a list of IDPs)
-    private String logo;
-    
-    // Additional (possibly protocol specific parameters)
-    @ElementCollection
-    @MapKeyColumn(name = "name")
-    @Column(name = "value")
-    @CollectionTable(name = "trusted_idp_parameters", joinColumns = @JoinColumn(name = "trusted_idp_id"))
-    private Map<String, String> parameters = new HashMap<>();
-    
-
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-
-    public String getIssuer() {
-        return issuer;
-    }
-
-    public void setIssuer(String issuer) {
-        this.issuer = issuer;
-    }
-    
-    public String getRealm() {
-        return realm;
-    }
-
-    public void setRealm(String realm) {
-        this.realm = realm;
-    }
-
-    public boolean isCacheTokens() {
-        return cacheTokens;
-    }
-
-    public void setCacheTokens(boolean cacheTokens) {
-        this.cacheTokens = cacheTokens;
-    }
-
-    public String getUrl() {
-        return url;
-    }
-
-    public void setUrl(String url) {
-        this.url = url;
-    }
-
-    public String getCertificate() {
-        return certificate;
-    }
-
-    public void setCertificate(String certificate) {
-        this.certificate = certificate;
-    }
-
-    public String getProtocol() {
-        return protocol;
-    }
-
-    public void setProtocol(String protocol) {
-        this.protocol = protocol;
-    }
-
-    public FederationType getFederationType() {
-        return federationType;
-    }
-
-    public void setFederationType(FederationType federationType) {
-        this.federationType = federationType;
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-
-    public String getLogo() {
-        return logo;
-    }
-
-    public void setLogo(String logo) {
-        this.logo = logo;
-    }
-
-    public TrustType getTrustType() {
-        return trustType;
-    }
-
-    public void setTrustType(TrustType trustType) {
-        this.trustType = trustType;
-    }
-
-    public Map<String, String> getParameters() {
-        return parameters;
-    }
-
-    public void setParameters(Map<String, String> parameters) {
-        this.parameters = parameters;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupportValidator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupportValidator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupportValidator.java
deleted file mode 100644
index 75ac2ec..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupportValidator.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.List;
-
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
-
-import org.apache.cxf.fediz.service.idp.protocols.ProtocolController;
-import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.stereotype.Component;
-
-/**
- * Validate that the protocol is a valid IdP protocol
- */
-@Component
-public class TrustedIdpProtocolSupportValidator implements ConstraintValidator<TrustedIdpProtocolSupported, String> {
-
-    @Autowired
-    // Qualifier workaround. See http://www.jayway.com/2013/11/03/spring-and-autowiring-of-generic-types/
-    @Qualifier("trustedIdpProtocolControllerImpl")
-    private ProtocolController<TrustedIdpProtocolHandler> trustedIdpProtocolHandlers;
-    
-    @Override
-    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
-        
-        List<String> protocols = trustedIdpProtocolHandlers.getProtocols();
-        return protocols.contains(object);
-    }
-
-    @Override
-    public void initialize(TrustedIdpProtocolSupported constraintAnnotation) {
-    }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupported.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupported.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupported.java
deleted file mode 100644
index 9c32af3..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupported.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.lang.annotation.Documented;
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.METHOD;
-
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import javax.validation.Constraint;
-import javax.validation.Payload;
-
-@Target({ METHOD, FIELD, ANNOTATION_TYPE })
-@Retention(RUNTIME)
-@Constraint(validatedBy = TrustedIdpProtocolSupportValidator.class)
-@Documented
-public @interface TrustedIdpProtocolSupported {
-
-    String message() default "{Protocol not supported}";
-
-    Class<?>[] groups() default { };
-
-    Class<? extends Payload>[] payload() default { };
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/security/GrantedAuthorityEntitlements.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/security/GrantedAuthorityEntitlements.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/security/GrantedAuthorityEntitlements.java
deleted file mode 100644
index 475ccd7..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/security/GrantedAuthorityEntitlements.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.security;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-import org.apache.cxf.fediz.service.idp.domain.Role;
-import org.apache.cxf.fediz.service.idp.service.RoleDAO;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.web.filter.GenericFilterBean;
-
-public class GrantedAuthorityEntitlements extends GenericFilterBean {
-
-    private static final Logger LOG = LoggerFactory.getLogger(GrantedAuthorityEntitlements.class);
-    
-    @Autowired
-    private RoleDAO roleDAO;
-    
-    @Override
-    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
-        throws IOException, ServletException {
-        
-        try {
-            Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
-            if (currentAuth == null) {
-                chain.doFilter(request, response);
-                return;
-            }
-            
-            final Set<GrantedAuthority> authorities = new HashSet<>();
-            if (currentAuth.getAuthorities() != null) {
-                authorities.addAll(currentAuth.getAuthorities());
-            }
-            
-            Iterator<? extends GrantedAuthority> authIt = currentAuth.getAuthorities().iterator();
-            while (authIt.hasNext()) {
-                GrantedAuthority ga = authIt.next();
-                String roleName = ga.getAuthority();
-                
-                try {
-                    Role role = roleDAO.getRole(roleName.substring(5), Arrays.asList("all"));
-                    for (Entitlement e : role.getEntitlements()) {
-                        authorities.add(new SimpleGrantedAuthority(e.getName()));
-                    }
-                } catch (Exception ex) {
-                    LOG.error("Role '{}' not found", roleName);
-                }
-            }
-            LOG.debug("Granted Authorities: {}", authorities);
-            
-            UsernamePasswordAuthenticationToken enrichedAuthentication = new UsernamePasswordAuthenticationToken(
-                currentAuth.getName(), currentAuth.getCredentials(), authorities);
-            enrichedAuthentication.setDetails(currentAuth.getDetails());
-            
-            SecurityContextHolder.getContext().setAuthentication(enrichedAuthentication);
-            LOG.info("Enriched AuthenticationToken added");
-            
-        } catch (Exception ex) {
-            LOG.error("Failed to enrich security context with entitlements", ex);
-        }
-        
-        chain.doFilter(request, response);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/ApplicationProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/ApplicationProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/ApplicationProtocolHandler.java
deleted file mode 100644
index 1cd9dc1..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/ApplicationProtocolHandler.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.spi;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.springframework.webflow.execution.RequestContext;
-
-public interface ApplicationProtocolHandler extends ProtocolHandler {
-    
-    boolean canHandleRequest(HttpServletRequest request);
-
-    void mapSignInRequest(RequestContext context);
-    
-    void mapSignInResponse(RequestContext context);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/ProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/ProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/ProtocolHandler.java
deleted file mode 100644
index 2c1c8c9..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/ProtocolHandler.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.spi;
-
-public interface ProtocolHandler {
-
-    String getProtocol();
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/TrustedIdpProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/TrustedIdpProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/TrustedIdpProtocolHandler.java
deleted file mode 100644
index a33591b..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/spi/TrustedIdpProtocolHandler.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.spi;
-
-import java.net.URL;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.springframework.webflow.execution.RequestContext;
-
-public interface TrustedIdpProtocolHandler extends ProtocolHandler {
-    
-    boolean canHandleRequest(HttpServletRequest request);
-
-    // Only supports HTTP GET SignIn Requests
-    URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp);
-    
-    //Hook in <action-state id="validateToken"> of federation-signin-response.xml
-    SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/WebUtils.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/WebUtils.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/WebUtils.java
deleted file mode 100644
index 4484312..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/util/WebUtils.java
+++ /dev/null
@@ -1,209 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.util;
-
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-import org.springframework.util.Assert;
-import org.springframework.webflow.context.servlet.ServletExternalContext;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Utility class to bind with webflow artifacts
- */
-public final class WebUtils {
-    
-    private WebUtils() {
-        super();
-    }
-
-    public static HttpServletRequest getHttpServletRequest(
-            final RequestContext context) {
-        Assert.isInstanceOf(ServletExternalContext.class,
-                context.getExternalContext(),
-                "Cannot obtain HttpServletRequest from event of type: "
-                        + context.getExternalContext().getClass().getName());
-        return (HttpServletRequest) context.getExternalContext()
-                .getNativeRequest();
-    }
-
-    public static HttpSession getHttpSession(final RequestContext context) {
-        HttpServletRequest httpServletRequest = getHttpServletRequest(context);
-        return httpServletRequest.getSession();
-    }
-
-    public static HttpServletResponse getHttpServletResponse(
-            final RequestContext context) {
-        Assert.isInstanceOf(ServletExternalContext.class,
-                context.getExternalContext(),
-                "Cannot obtain HttpServletResponse from event of type: "
-                        + context.getExternalContext().getClass().getName());
-        return (HttpServletResponse) context.getExternalContext()
-                .getNativeResponse();
-    }
-
-    public static String getHttpHeader(RequestContext requestContext, String headerName) {
-        return getHttpServletRequest(requestContext).getHeader(headerName);
-    }
-
-    public static void putAttributeInRequestScope(final RequestContext context,
-            final String attributeKey, final Object attributeValue) {
-        context.getRequestScope().put(attributeKey, attributeValue);
-    }
-
-    public static void putAttributeInExternalContext(
-            final RequestContext context, final String attributeKey,
-            final Object attributeValue) {
-        context.getExternalContext().getSessionMap()
-                .put(attributeKey, attributeValue);
-    }
-
-    /**
-     * put attribute in request or in session depending on storeInSession.
-     * 
-     * @param context
-     * @param attributeKey
-     */
-    public static void putAttribute(final RequestContext context,
-            final String attributeKey, final Object attributeValue,
-            boolean storeInSession) {
-        if (storeInSession) {
-            putAttributeInExternalContext(context, attributeKey, attributeValue);
-        } else {
-            putAttributeInRequestScope(context, attributeKey, attributeValue);
-        }
-    }
-
-    public static Object getAttributeFromRequestScope(
-            final RequestContext context, final String attributeKey) {
-        return context.getRequestScope().get(attributeKey);
-    }
-
-    public static Object getAttributeFromExternalContext(
-            final RequestContext context, final String attributeKey) {
-        return context.getExternalContext().getSessionMap()
-                .get(attributeKey);
-    }
-
-    /**
-     * get attribute from request; if not found get it from session.
-     * 
-     * @param context
-     * @param attributeKey
-     * @return the attribute from the request or session
-     */
-    public static Object getAttribute(final RequestContext context,
-            final String attributeKey) {
-        Object value = getAttributeFromRequestScope(context, attributeKey);
-        if (value != null) {
-            return value;
-        }
-        return getAttributeFromExternalContext(context, attributeKey);
-    }
-
-    public static Object removeAttributeFromRequestScope(
-            final RequestContext context, final String attributeKey) {
-        return context.getRequestScope().remove(attributeKey);
-    }
-
-    public static Object removeAttributeFromExternalContext(
-            final RequestContext context, final String attributeKey) {
-        return context.getExternalContext().getSessionMap()
-                .remove(attributeKey);
-    }
-
-    /**
-     * remove attribute from request and session.
-     * 
-     * @param context
-     * @param attributeKey
-     * @return the removed attribute
-     */
-    public static Object removeAttribute(final RequestContext context,
-            final String attributeKey) {
-        Object valueReq = removeAttributeFromRequestScope(context, attributeKey);
-        Object valueSes = removeAttributeFromExternalContext(context,
-                attributeKey);
-        if (valueSes != null) {
-            return valueSes; // not clean if request has different value !
-        }
-        if (valueReq != null) {
-            return valueReq;
-        }
-        return null;
-    }
-
-    public static void putAttributeInFlowScope(final RequestContext context,
-            final String attributeKey, final Object attributeValue) {
-        context.getFlowScope().put(attributeKey, attributeValue);
-    }
-
-    public static Object getAttributeFromFlowScope(
-            final RequestContext context, final String attributeKey) {
-        return context.getFlowScope().get(attributeKey);
-    }
-
-    public static Object removeAttributeFromFlowScope(
-            final RequestContext context, final String attributeKey) {
-        return context.getFlowScope().remove(attributeKey);
-    }
-
-    public static String getParamFromRequestParameters(
-            final RequestContext context, final String attributeKey) {
-        return context.getRequestParameters().get(attributeKey);
-    }
-
-    public static Cookie readCookie(
-            final RequestContext context, final String cookieName) {
-        HttpServletRequest httpServletRequest = getHttpServletRequest(context);
-        Cookie[] cookies = httpServletRequest.getCookies();
-        if (cookies != null) {
-            for (int i = 0; i < cookies.length; i++) {
-                if (cookies[i].getName().equals(cookieName)) {
-                    return cookies[i];
-                }
-            }
-        }
-        return null;
-    }
-
-    public static void addCookie(
-            final RequestContext context, final String cookieName, final String cookieValue) {
-        HttpServletResponse httpServletResponse = getHttpServletResponse(context);
-        Cookie cookie = new Cookie(cookieName, cookieValue);
-        cookie.setSecure(true);
-        cookie.setMaxAge(-1);
-        httpServletResponse.addCookie(cookie);
-    }
-
-    public static void removeCookie(
-            final RequestContext context, final String cookieName) {
-        HttpServletResponse httpServletResponse = getHttpServletResponse(context);
-        Cookie cookie = readCookie(context, cookieName);
-        if (cookie != null) {
-            cookie.setMaxAge(0);
-            cookie.setValue("");
-            httpServletResponse.addCookie(cookie);
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/resources/META-INF/orm.xml
----------------------------------------------------------------------
diff --git a/services/idp/src/main/resources/META-INF/orm.xml b/services/idp/src/main/resources/META-INF/orm.xml
deleted file mode 100644
index e9c2bd6..0000000
--- a/services/idp/src/main/resources/META-INF/orm.xml
+++ /dev/null
@@ -1,183 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  Licensed to the Apache Software Foundation (ASF) under one
-  or more contributor license agreements. See the NOTICE file
-  distributed with this work for additional information
-  regarding copyright ownership. The ASF licenses this file
-  to you 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.
--->
-<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
-    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
-    version="2.0">
-
-    <entity class="org.apache.cxf.fediz.service.idp.service.jpa.ClaimEntity">
-        <table>
-            <unique-constraint>
-                <column-name>claimtype</column-name>
-            </unique-constraint>
-        </table>
-        <attributes>
-            <id name="id">
-                <generated-value generator="SEQ_Claim"
-                    strategy="TABLE" />
-                <table-generator name="SEQ_Claim"
-                    pk-column-value="SEQ_Claim" initial-value="100" />
-            </id>
-        </attributes>
-    </entity>
-
-    <entity class="org.apache.cxf.fediz.service.idp.service.jpa.IdpEntity">
-        <table>
-            <unique-constraint>
-                <column-name>realm</column-name>
-            </unique-constraint>
-        </table>
-        <attributes>
-            <id name="id">
-                <generated-value generator="SEQ_IDP"
-                    strategy="TABLE" />
-                <table-generator name="SEQ_IDP"
-                    pk-column-value="SEQ_IDP" initial-value="100" />
-            </id>
-            <many-to-many name="claimTypesOffered">
-                <join-table name="idp_claims">
-                    <join-column name="idp_id" />
-                    <inverse-join-column name="claim_id" />
-                    <unique-constraint>
-                        <column-name>idp_id</column-name>
-                        <column-name>claim_id</column-name>
-                    </unique-constraint>
-                </join-table>
-            </many-to-many>
-            <many-to-many name="trustedIdps">
-                <join-table name="idp_trustedidps">
-                    <join-column name="idp_id" />
-                    <inverse-join-column name="trustedidp_id" />
-                    <unique-constraint>
-                        <column-name>idp_id</column-name>
-                        <column-name>trustedidp_id</column-name>
-                    </unique-constraint>
-                </join-table>
-            </many-to-many>
-            <many-to-many name="applications">
-                <join-table name="idp_applications">
-                    <join-column name="idp_id" />
-                    <inverse-join-column name="application_id" />
-                    <unique-constraint>
-                        <column-name>idp_id</column-name>
-                        <column-name>application_id</column-name>
-                    </unique-constraint>
-                </join-table>
-            </many-to-many>
-
-        </attributes>
-    </entity>
-
-    <entity
-        class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationEntity">
-        <table>
-            <unique-constraint>
-                <column-name>realm</column-name>
-            </unique-constraint>
-        </table>
-        <attributes>
-            <id name="id">
-                <generated-value generator="SEQ_Application"
-                    strategy="TABLE" />
-                <table-generator name="SEQ_Application"
-                    pk-column-value="SEQ_Application" initial-value="100" />
-            </id>
-        </attributes>
-    </entity>
-
-    <entity
-        class="org.apache.cxf.fediz.service.idp.service.jpa.TrustedIdpEntity">
-        <table>
-            <unique-constraint>
-                <column-name>realm</column-name>
-            </unique-constraint>
-        </table>
-        <attributes>
-            <id name="id">
-                <generated-value generator="SEQ_TrustedIDP"
-                    strategy="TABLE" />
-                <table-generator name="SEQ_TrustedIDP"
-                    pk-column-value="SEQ_TrustedIDP" initial-value="100" />
-            </id>
-        </attributes>
-    </entity>
-
-    <entity
-        class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
-        <table>
-            <unique-constraint>
-                <column-name>claimid</column-name>
-                <column-name>applicationid</column-name>
-            </unique-constraint>
-        </table>
-        <attributes>
-            <id name="id">
-                <generated-value generator="SEQ_ApplicationClaim"
-                    strategy="TABLE" />
-                <table-generator name="SEQ_ApplicationClaim"
-                    pk-column-value="SEQ_ApplicationClaim"
-                    initial-value="100" />
-            </id>
-        </attributes>
-    </entity>
-    
-    <entity class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
-        <table>
-            <unique-constraint>
-                <column-name>name</column-name>
-            </unique-constraint>
-        </table>
-        <attributes>
-            <id name="id">
-                <generated-value generator="SEQ_Entitlement"
-                    strategy="TABLE" />
-                <table-generator name="SEQ_Entitlement"
-                    pk-column-value="SEQ_Entitlement" initial-value="100" />
-            </id>
-        </attributes>
-    </entity>
-    
-    <entity class="org.apache.cxf.fediz.service.idp.service.jpa.RoleEntity">
-        <table>
-            <unique-constraint>
-                <column-name>name</column-name>
-            </unique-constraint>
-        </table>
-        <attributes>
-            <id name="id">
-                <generated-value generator="SEQ_ROLE"
-                    strategy="TABLE" />
-                <table-generator name="SEQ_ROLE"
-                    pk-column-value="SEQ_ROLE" initial-value="100" />
-            </id>
-            <many-to-many name="entitlements">
-                <join-table name="role_entitlements">
-                    <join-column name="role_id" />
-                    <inverse-join-column name="entitlement_id" />
-                    <unique-constraint>
-                        <column-name>role_id</column-name>
-                        <column-name>entitlement_id</column-name>
-                    </unique-constraint>
-                </join-table>
-            </many-to-many>
-        </attributes>
-    </entity>
-    
-</entity-mappings>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/resources/META-INF/spring-persistence.xml
----------------------------------------------------------------------
diff --git a/services/idp/src/main/resources/META-INF/spring-persistence.xml b/services/idp/src/main/resources/META-INF/spring-persistence.xml
deleted file mode 100644
index bf34a76..0000000
--- a/services/idp/src/main/resources/META-INF/spring-persistence.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-  Licensed to the Apache Software Foundation (ASF) under one
-  or more contributor license agreements. See the NOTICE file
-  distributed with this work for additional information
-  regarding copyright ownership. The ASF licenses this file
-  to you 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.
--->
-<persistence
-    xmlns="http://java.sun.com/xml/ns/persistence"
-    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
-    version="2.0">
-
-    <persistence-unit name="fedizPersistenceUnit">
-        <mapping-file>META-INF/orm.xml</mapping-file>
-        <validation-mode>AUTO</validation-mode>
-    </persistence-unit>
-</persistence>
\ No newline at end of file


[05/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java
deleted file mode 100644
index 6fd3d05..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.model;
-
-//@XmlRootElement(name = "Claim", namespace = "http://org.apache.cxf.fediz")
-public class RequestClaim extends org.apache.cxf.fediz.service.idp.domain.RequestClaim {
-    
-    private static final long serialVersionUID = 2635896159019665467L;
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java
deleted file mode 100644
index fdae8f5..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.model;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-
-//import javax.persistence.Column;
-//import javax.persistence.Entity;
-//import javax.persistence.Id;
-//import javax.persistence.Table;
-
-//@Entity
-//@Table(name = "SERVICE")
-//@XmlRootElement(name = "Service", namespace = "http://org.apache.cxf.fediz")
-public class ServiceConfig extends Application {
-        
-    private static final long serialVersionUID = 585676715065240699L;       
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java
deleted file mode 100644
index 89c2bbb..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.model;
-
-
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-
-//@XmlRootElement(name = "TrustedIDP", namespace = "http://org.apache.cxf.fediz")
-public class TrustedIDPConfig extends TrustedIdp {
-
-    private static final long serialVersionUID = -1182000443945024801L;
-
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java
deleted file mode 100644
index 44cb3a2..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.model;
-
-import java.io.Serializable;
-
-public class TrustedIDPSelection implements Serializable {
-
-    private static final long serialVersionUID = 1L;
-    
-    private String homeRealm;
-
-    public String getHomeRealm() {
-        return homeRealm;
-    }
-
-    public void setHomeRealm(String homeRealm) {
-        this.homeRealm = homeRealm;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java
deleted file mode 100644
index 84a70ca..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.util.Date;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import org.apache.cxf.fediz.core.util.CertsUtils;
-import org.apache.cxf.fediz.service.idp.IdpConstants;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.wss4j.common.crypto.Crypto;
-import org.apache.wss4j.common.saml.SAMLCallback;
-import org.apache.wss4j.common.saml.SAMLUtil;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.apache.wss4j.common.saml.bean.ConditionsBean;
-import org.apache.wss4j.common.saml.bean.SubjectBean;
-import org.apache.wss4j.common.saml.bean.Version;
-import org.apache.wss4j.common.saml.builder.SAML2Constants;
-import org.joda.time.DateTime;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.webflow.execution.RequestContext;
-
-public abstract class AbstractTrustedIdpOAuth2ProtocolHandler extends AbstractTrustedIdpProtocolHandler {
-    
-    /**
-     * The client_id value to send to the IdP.
-     */
-    public static final String CLIENT_ID = "client.id";
-    
-    /**
-     * The secret associated with the client to authenticate to the IdP.
-     */
-    public static final String CLIENT_SECRET = "client.secret";
-    
-    /**
-     * The Token endpoint. The authorization endpoint is specified by TrustedIdp.url.
-     */
-    public static final String TOKEN_ENDPOINT = "token.endpoint";
-    
-    /**
-     * Additional (space-separated) parameters to be sent in the "scope" to the authorization endpoint.
-     * The default value depends on the subclass.
-     */
-    public static final String SCOPE = "scope";
-    
-    private static final Logger LOG = LoggerFactory.getLogger(AbstractTrustedIdpOAuth2ProtocolHandler.class);
-
-    @Override
-    public URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
-        
-        String clientId = getProperty(trustedIdp, CLIENT_ID);
-        if (clientId == null || clientId.isEmpty()) {
-            LOG.warn("A CLIENT_ID must be configured for OAuth 2.0");
-            throw new IllegalStateException("No CLIENT_ID specified");
-        }
-        
-        String scope = getScope(trustedIdp);
-        LOG.debug("Using scope: {}", scope);
-        
-        try {
-            StringBuilder sb = new StringBuilder();
-            sb.append(trustedIdp.getUrl());
-            sb.append("?");
-            sb.append("response_type").append('=');
-            sb.append("code");
-            sb.append("&");
-            sb.append("client_id").append('=');
-            sb.append(clientId);
-            sb.append("&");
-            sb.append("redirect_uri").append('=');
-            sb.append(URLEncoder.encode(idp.getIdpUrl().toString(), "UTF-8"));
-            sb.append("&");
-            sb.append("scope").append('=');
-            sb.append(URLEncoder.encode(scope, "UTF-8"));
-            
-            String state = context.getFlowScope().getString(IdpConstants.TRUSTED_IDP_CONTEXT);
-            sb.append("&").append("state").append('=');
-            sb.append(state);
-            
-            return new URL(sb.toString());
-        } catch (MalformedURLException ex) {
-            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
-            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
-        } catch (UnsupportedEncodingException ex) {
-            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
-            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
-        }
-    }
-    
-    protected SamlAssertionWrapper createSamlAssertion(Idp idp, TrustedIdp trustedIdp, String subjectName,
-                                                     Date notBefore,
-                                                     Date expires) throws Exception {
-        SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
-        String issuer = idp.getServiceDisplayName();
-        if (issuer == null) {
-            issuer = idp.getRealm();
-        }
-        if (issuer != null) {
-            callbackHandler.setIssuer(issuer);
-        }
-        
-        // Subject
-        SubjectBean subjectBean =
-            new SubjectBean(subjectName, SAML2Constants.NAMEID_FORMAT_UNSPECIFIED, SAML2Constants.CONF_BEARER);
-        callbackHandler.setSubjectBean(subjectBean);
-        
-        // Conditions
-        ConditionsBean conditionsBean = new ConditionsBean();
-        conditionsBean.setNotAfter(new DateTime(expires));
-        if (notBefore != null) {
-            DateTime notBeforeDT = new DateTime(notBefore);
-            conditionsBean.setNotBefore(notBeforeDT);
-        } else {
-            conditionsBean.setNotBefore(new DateTime());
-        }
-        callbackHandler.setConditionsBean(conditionsBean);
-        
-        SAMLCallback samlCallback = new SAMLCallback();
-        SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
-        
-        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
-        
-        Crypto crypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
-        assertion.signAssertion(crypto.getDefaultX509Identifier(), idp.getCertificatePassword(), 
-                                crypto, false);
-        
-        return assertion;
-    }
-    
-    private static class SamlCallbackHandler implements CallbackHandler {
-        private ConditionsBean conditionsBean;
-        private SubjectBean subjectBean;
-        private String issuer;
-        
-        /**
-         * Set the SubjectBean
-         */
-        public void setSubjectBean(SubjectBean subjectBean) {
-            this.subjectBean = subjectBean;
-        }
-        
-        /**
-         * Set the ConditionsBean
-         */
-        public void setConditionsBean(ConditionsBean conditionsBean) {
-            this.conditionsBean = conditionsBean;
-        }
-        
-        /**
-         * Set the issuer name
-         */
-        public void setIssuer(String issuerName) {
-            this.issuer = issuerName;
-        }
-        
-        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
-            for (Callback callback : callbacks) {
-                if (callback instanceof SAMLCallback) {
-                    SAMLCallback samlCallback = (SAMLCallback) callback;
-
-                    // Set the Subject
-                    if (subjectBean != null) {
-                        samlCallback.setSubject(subjectBean);
-                    }
-                    samlCallback.setSamlVersion(Version.SAML_20);
-                    
-                    // Set the issuer
-                    samlCallback.setIssuer(issuer);
-
-                    // Set the conditions
-                    samlCallback.setConditions(conditionsBean);
-                }
-            }
-        }
-        
-    }
-    
-    abstract String getScope(TrustedIdp trustedIdp);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
deleted file mode 100644
index 2329eb2..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
-
-public abstract class AbstractTrustedIdpProtocolHandler implements TrustedIdpProtocolHandler {
-    
-    @Override
-    public boolean canHandleRequest(HttpServletRequest request) {
-        // TODO Auto-generated method stub
-        return false;
-    }
-
-    protected String getProperty(TrustedIdp trustedIdp, String property) {
-        Map<String, String> parameters = trustedIdp.getParameters();
-        
-        if (parameters != null && parameters.containsKey(property)) {
-            return parameters.get(property);
-        }
-        
-        return null;
-    }
-    
-    // Is a property configured. Defaults to the boolean "defaultValue" if not
-    protected boolean isBooleanPropertyConfigured(TrustedIdp trustedIdp, String property, boolean defaultValue) {
-        Map<String, String> parameters = trustedIdp.getParameters();
-        
-        if (parameters != null && parameters.containsKey(property)) {
-            return Boolean.parseBoolean(parameters.get(property));
-        }
-        
-        return defaultValue;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java
deleted file mode 100644
index c2be3eb..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class ApplicationProtocolControllerImpl implements ProtocolController<ApplicationProtocolHandler> {
-
-    private static final Logger LOG = LoggerFactory.getLogger(ApplicationProtocolControllerImpl.class);
-    
-    @Autowired
-    private List<ApplicationProtocolHandler> protocolHandlers;
-    
-    @Override
-    public ApplicationProtocolHandler getProtocolHandler(String protocol) {
-        for (ApplicationProtocolHandler protocolHandler : protocolHandlers) {
-            if (protocolHandler.getProtocol() != null && protocolHandler.getProtocol().equals(protocol)) {
-                return protocolHandler;
-            }
-        }
-        LOG.warn("No protocol handler found for {}", protocol);
-        return null;
-    }
-    
-    @Override
-    public List<String> getProtocols() {
-        List<String> protocols = new ArrayList<>();
-        for (ApplicationProtocolHandler protocolHandler : protocolHandlers) {
-            protocols.add(protocolHandler.getProtocol());
-        }
-        return Collections.unmodifiableList(protocols);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java
deleted file mode 100644
index ebab362..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
-
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-@Component
-public class ApplicationSAMLSSOProtocolHandler implements ApplicationProtocolHandler {
-    
-    public static final String PROTOCOL = "urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser";
-
-    //private static final Logger LOG = LoggerFactory.getLogger(ApplicationWSFedProtocolHandler.class);
-
-    @Override
-    public boolean canHandleRequest(HttpServletRequest request) {
-        // TODO Auto-generated method stub
-        return false;
-    }
-
-    @Override
-    public String getProtocol() {
-        return PROTOCOL;
-    }
-
-    @Override
-    public void mapSignInRequest(RequestContext context) {
-        // TODO Auto-generated method stub
-    }
-
-    @Override
-    public void mapSignInResponse(RequestContext context) {
-        // TODO Auto-generated method stub
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java
deleted file mode 100644
index 2024e3d..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import javax.servlet.http.HttpServletRequest;
-
-import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
-
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-@Component
-public class ApplicationWSFedProtocolHandler implements ApplicationProtocolHandler {
-    
-    public static final String PROTOCOL = "http://docs.oasis-open.org/wsfed/federation/200706";
-
-    //private static final Logger LOG = LoggerFactory.getLogger(ApplicationWSFedProtocolHandler.class);
-
-    @Override
-    public boolean canHandleRequest(HttpServletRequest request) {
-        // TODO Auto-generated method stub
-        return false;
-    }
-
-    @Override
-    public String getProtocol() {
-        return PROTOCOL;
-    }
-
-    @Override
-    public void mapSignInRequest(RequestContext context) {
-        // TODO Auto-generated method stub
-    }
-
-    @Override
-    public void mapSignInResponse(RequestContext context) {
-        // TODO Auto-generated method stub
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java
deleted file mode 100644
index d4da6c2..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.spi.ProtocolHandler;
-
-public interface ProtocolController<T extends ProtocolHandler> {
-
-    T getProtocolHandler(String protocol);
-
-    List<String> getProtocols();
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
deleted file mode 100644
index 36db3ae..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.List;
-
-import javax.ws.rs.core.Form;
-import javax.ws.rs.core.Response;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import org.apache.cxf.fediz.service.idp.IdpConstants;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.helpers.DOMUtils;
-import org.apache.cxf.interceptor.LoggingInInterceptor;
-import org.apache.cxf.interceptor.LoggingOutInterceptor;
-import org.apache.cxf.jaxrs.client.ClientConfiguration;
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.cxf.jaxrs.json.basic.JsonMapObject;
-import org.apache.cxf.jaxrs.provider.json.JsonMapObjectProvider;
-import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken;
-import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider;
-import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.apache.xml.security.stax.impl.util.IDGenerator;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Extension of AbstractTrustedIdpOAuth2ProtocolHandler for Facebook Connect.
- * Default values:
- *  - scope: email
- *  - token.endpoint: https://graph.facebook.com/v2.6/oauth/access_token
- */
-@Component
-public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2ProtocolHandler {
-    
-    /**
-     * The facebook API endpoint for querying claims (such as email address). If not specified
-     * it defaults to "https://graph.facebook.com/v2.6".
-     */
-    public static final String API_ENDPOINT = "api.endpoint";
-    
-    /**
-     * The Claim to use for the subject username to insert into the SAML Token. It defaults to 
-     * "email".
-     */
-    public static final String SUBJECT_CLAIM = "subject.claim";
-    
-    public static final String PROTOCOL = "facebook-connect";
-
-    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpFacebookProtocolHandler.class);
-
-    @Override
-    public String getProtocol() {
-        return PROTOCOL;
-    }
-
-    @Override
-    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
-
-        String code = (String) WebUtils.getAttributeFromFlowScope(context,
-                                                                  OAuthConstants.CODE_RESPONSE_TYPE);
-        if (code != null && !code.isEmpty()) {
-            
-            String tokenEndpoint = getProperty(trustedIdp, TOKEN_ENDPOINT);
-            if (tokenEndpoint == null || tokenEndpoint.isEmpty()) {
-                tokenEndpoint = "https://graph.facebook.com/v2.6/oauth/access_token";
-            }
-            
-            String apiEndpoint = getProperty(trustedIdp, API_ENDPOINT);
-            if (apiEndpoint == null || apiEndpoint.isEmpty()) {
-                apiEndpoint = "https://graph.facebook.com/v2.6";
-            }
-            
-            String clientId = getProperty(trustedIdp, CLIENT_ID);
-            String clientSecret = getProperty(trustedIdp, CLIENT_SECRET);
-            if (clientSecret == null || clientSecret.isEmpty()) {
-                LOG.warn("A CLIENT_SECRET must be configured to use the TrustedIdpFacebookProtocolHandler");
-                throw new IllegalStateException("No CLIENT_SECRET specified");
-            }
-            
-            // Here we need to get the AccessToken using the authorization code
-            ClientAccessToken accessToken = getAccessTokenUsingCode(tokenEndpoint, code, clientId,
-                                                                    clientSecret, idp.getIdpUrl().toString());
-            if (accessToken == null || accessToken.getTokenKey() == null) {
-                LOG.warn("No Access Token received from the Facebook IdP");
-                return null;
-            }
-            
-            // Now we need to invoke on the API endpoint using the access token to get the 
-            // user's claims
-            String subjectName = getSubjectName(apiEndpoint, accessToken.getTokenKey(), trustedIdp);
-            try {
-                String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
-                if (whr == null) {
-                    LOG.warn("Home realm is null");
-                    throw new IllegalStateException("Home realm is null");
-                }
-        
-                // Convert into a SAML Token
-                Date expires = new Date();
-                expires.setTime(expires.getTime() + (accessToken.getExpiresIn() * 1000L));
-                SecurityToken idpToken = new SecurityToken(IDGenerator.generateID(null), null, expires);
-                SamlAssertionWrapper assertion = 
-                    createSamlAssertion(idp, trustedIdp, subjectName, null, expires);
-                Document doc = DOMUtils.createDocument();
-                Element token = assertion.toDOM(doc);
-        
-                // Create new Security token with new id. 
-                // Parameters for freshness computation are copied from original IDP_TOKEN
-                idpToken.setToken(token);
-        
-                LOG.info("[IDP_TOKEN={}] for user '{}' issued by home realm [{}]",
-                         assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(), 
-                         whr);
-                LOG.debug("Expired date={}", expires);
-                
-                return idpToken;
-            } catch (IllegalStateException ex) {
-                throw ex;
-            } catch (Exception ex) {
-                LOG.warn("Unexpected exception occured", ex);
-                throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
-            }
-        }
-        return null;
-    }
-    
-    private ClientAccessToken getAccessTokenUsingCode(String tokenEndpoint, String code, String clientId,
-                                                      String clientSecret, String redirectURI) {
-        // Here we need to get the AccessToken using the authorization code
-        List<Object> providers = new ArrayList<Object>();
-        providers.add(new OAuthJSONProvider());
-        
-        WebClient client = 
-            WebClient.create(tokenEndpoint, providers, "cxf-tls.xml");
-        
-        ClientConfiguration config = WebClient.getConfig(client);
-
-        if (LOG.isDebugEnabled()) {
-            config.getOutInterceptors().add(new LoggingOutInterceptor());
-            config.getInInterceptors().add(new LoggingInInterceptor());
-        }
-        
-        client.type("application/x-www-form-urlencoded");
-        client.accept("application/json");
-
-        Form form = new Form();
-        form.param("grant_type", "authorization_code");
-        form.param("code", code);
-        form.param("client_id", clientId);
-        form.param("redirect_uri", redirectURI);
-        form.param("client_secret", clientSecret);
-        Response response = client.post(form);
-
-        return response.readEntity(ClientAccessToken.class);
-    }
-    
-    private String getSubjectName(String apiEndpoint, String accessToken, TrustedIdp trustedIdp) {
-        WebClient client = WebClient.create(apiEndpoint, 
-                                  Collections.singletonList(new JsonMapObjectProvider()), 
-                                  "cxf-tls.xml");
-        client.path("/me");
-        ClientConfiguration config = WebClient.getConfig(client);
-
-        if (LOG.isDebugEnabled()) {
-            config.getOutInterceptors().add(new LoggingOutInterceptor());
-            config.getInInterceptors().add(new LoggingInInterceptor());
-        }
-
-        client.accept("application/json");
-        client.query("access_token", accessToken);
-        
-        String subjectName = getProperty(trustedIdp, SUBJECT_CLAIM);
-        if (subjectName == null || subjectName.isEmpty()) {
-            subjectName = "email";
-        }
-        client.query("fields", subjectName);
-        JsonMapObject mapObject = client.get(JsonMapObject.class);
-        
-        String parsedSubjectName = (String)mapObject.getProperty(subjectName);
-        if (subjectName.contains("email")) {
-            parsedSubjectName = parsedSubjectName.replace("\\u0040", "@");
-        }
-        return parsedSubjectName;
-    }
-    
-    protected String getScope(TrustedIdp trustedIdp) {
-        String scope = getProperty(trustedIdp, SCOPE);
-        if (scope != null) {
-            scope = scope.trim();
-        }
-        
-        if (scope == null || scope.isEmpty()) {
-            scope = "email";
-        }
-        return scope;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
deleted file mode 100644
index b45c763..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import java.io.IOException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-import javax.ws.rs.core.Form;
-import javax.ws.rs.core.Response;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import org.apache.cxf.fediz.core.exception.ProcessingException;
-import org.apache.cxf.fediz.core.util.CertsUtils;
-import org.apache.cxf.fediz.core.util.DOMUtils;
-import org.apache.cxf.fediz.service.idp.IdpConstants;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.interceptor.LoggingInInterceptor;
-import org.apache.cxf.interceptor.LoggingOutInterceptor;
-import org.apache.cxf.jaxrs.client.ClientConfiguration;
-import org.apache.cxf.jaxrs.client.WebClient;
-import org.apache.cxf.rs.security.jose.common.JoseConstants;
-import org.apache.cxf.rs.security.jose.jaxrs.JsonWebKeysProvider;
-import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm;
-import org.apache.cxf.rs.security.jose.jwk.JsonWebKey;
-import org.apache.cxf.rs.security.jose.jwk.JsonWebKeys;
-import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer;
-import org.apache.cxf.rs.security.jose.jwt.JwtConstants;
-import org.apache.cxf.rs.security.jose.jwt.JwtToken;
-import org.apache.cxf.rs.security.jose.jwt.JwtUtils;
-import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken;
-import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider;
-import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.apache.xml.security.exceptions.Base64DecodingException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Extension of AbstractTrustedIdpOAuth2ProtocolHandler for OpenId Connect.
- * Default values:
- *  - scope: openid
- */
-@Component
-public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2ProtocolHandler {
-    
-    /**
-     * The signature algorithm to use in verifying the IdToken. The default is "RS256".
-     */
-    public static final String SIGNATURE_ALGORITHM = "signature.algorithm";
-    
-    /**
-     * The Claim in which to extract the Subject username to insert into the generated SAML token. 
-     * It defaults to "preferred_username", otherwise it falls back to the "sub" claim.
-     */
-    public static final String SUBJECT_CLAIM = "subject.claim";
-    
-    /**
-     * Additional (space-separated) parameters to be sent in the "scope" to the authorization endpoint.
-     * Fediz will automatically use "openid" for this value. 
-     */
-    public static final String SCOPE = "scope";
-    
-    /**
-     * The URI from which to retrieve the JSON Web Keys to validate the signed IdToken.
-     */
-    public static final String JWKS_URI = "jwks.uri";
-    
-    public static final String PROTOCOL = "openid-connect-1.0";
-
-    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpOIDCProtocolHandler.class);
-
-    @Override
-    public String getProtocol() {
-        return PROTOCOL;
-    }
-
-    @Override
-    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
-
-        String code = (String) WebUtils.getAttributeFromFlowScope(context,
-                                                                  OAuthConstants.CODE_RESPONSE_TYPE);
-        if (code != null && !code.isEmpty()) {
-            
-            String tokenEndpoint = getProperty(trustedIdp, TOKEN_ENDPOINT);
-            if (tokenEndpoint == null || tokenEndpoint.isEmpty()) {
-                LOG.warn("A TOKEN_ENDPOINT must be configured to use the OIDCProtocolHandler");
-                throw new IllegalStateException("No TOKEN_ENDPOINT specified");
-            }
-            
-            String clientId = getProperty(trustedIdp, CLIENT_ID);
-            String clientSecret = getProperty(trustedIdp, CLIENT_SECRET);
-            if (clientSecret == null || clientSecret.isEmpty()) {
-                LOG.warn("A CLIENT_SECRET must be configured to use the OIDCProtocolHandler");
-                throw new IllegalStateException("No CLIENT_SECRET specified");
-            }
-            
-            // Here we need to get the IdToken using the authorization code
-            List<Object> providers = new ArrayList<Object>();
-            providers.add(new OAuthJSONProvider());
-            
-            WebClient client = 
-                WebClient.create(tokenEndpoint, providers, clientId, clientSecret, "cxf-tls.xml");
-            
-            ClientConfiguration config = WebClient.getConfig(client);
-
-            if (LOG.isDebugEnabled()) {
-                config.getOutInterceptors().add(new LoggingOutInterceptor());
-                config.getInInterceptors().add(new LoggingInInterceptor());
-            }
-            
-            client.type("application/x-www-form-urlencoded").accept("application/json");
-
-            Form form = new Form();
-            form.param("grant_type", "authorization_code");
-            form.param("code", code);
-            form.param("client_id", clientId);
-            form.param("redirect_uri", idp.getIdpUrl().toString());
-            Response response = client.post(form);
-
-            ClientAccessToken accessToken = response.readEntity(ClientAccessToken.class);
-            String idToken = accessToken.getParameters().get("id_token");
-            if (idToken == null) {
-                LOG.warn("No IdToken received from the OIDC IdP");
-                return null;
-            }
-            
-            client.close();
-            
-            try {
-                String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
-                if (whr == null) {
-                    LOG.warn("Home realm is null");
-                    throw new IllegalStateException("Home realm is null");
-                }
-        
-                // Parse the received Token
-                JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
-                JwtToken jwt = jwtConsumer.getJwtToken();
-                
-                if (jwt != null && jwt.getClaims() != null && LOG.isDebugEnabled()) {
-                    LOG.debug("Received Claims:");
-                    for (Map.Entry<String, Object> claim : jwt.getClaims().asMap().entrySet()) {
-                        LOG.debug(claim.getKey() + ": " + claim.getValue());
-                    }
-                }
-                
-                if (jwt != null && jwt.getJwsHeaders() != null && LOG.isDebugEnabled()) {
-                    LOG.debug("Received JWS Headers:");
-                    for (Map.Entry<String, Object> header : jwt.getJwsHeaders().asMap().entrySet()) {
-                        LOG.debug(header.getKey() + ": " + header.getValue());
-                    }
-                }
-                
-                if (!validateSignature(trustedIdp, jwtConsumer)) {
-                    LOG.warn("Signature does not validate");
-                    return null;
-                }
-                
-                // Make sure the received token is valid according to the spec
-                validateToken(jwt, clientId);
-                
-                Date created = new Date((long)jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT) * 1000L);
-                Date notBefore = null;
-                if (jwt.getClaim(JwtConstants.CLAIM_NOT_BEFORE) != null) {
-                    notBefore = new Date((long)jwt.getClaim(JwtConstants.CLAIM_NOT_BEFORE) * 1000L);
-                } 
-                
-                Date expires = new Date((long)jwt.getClaim(JwtConstants.CLAIM_EXPIRY) * 1000L);
-                
-                // Subject
-                String subjectName = getProperty(trustedIdp, SUBJECT_CLAIM);
-                LOG.debug("Trying to extract subject name using the claim name {}", subjectName);
-                if (subjectName == null || jwt.getClaim(subjectName) == null) {
-                    LOG.debug("No claim available in the token for {}", subjectName);
-                    subjectName = "preferred_username";
-                    LOG.debug("Falling back to use subject claim name {}", subjectName);
-                    if (subjectName == null || jwt.getClaim(subjectName) == null) {
-                        subjectName = JwtConstants.CLAIM_SUBJECT;
-                        LOG.debug("No claim available in the token for preferred_username. "
-                                  + "Falling back to use {}", subjectName);
-                    }
-                }
-                
-                // Convert into a SAML Token
-                SamlAssertionWrapper assertion = 
-                    createSamlAssertion(idp, trustedIdp, (String)jwt.getClaim(subjectName), notBefore, expires);
-                Document doc = DOMUtils.createDocument();
-                Element token = assertion.toDOM(doc);
-        
-                // Create new Security token with new id. 
-                // Parameters for freshness computation are copied from original IDP_TOKEN
-                SecurityToken idpToken = new SecurityToken(assertion.getId(), created, expires);
-                idpToken.setToken(token);
-        
-                LOG.info("[IDP_TOKEN={}] for user '{}' created from [RP_TOKEN={}] issued by home realm [{}/{}]",
-                         assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(), 
-                         jwt.getClaim(JwtConstants.CLAIM_JWT_ID), whr, jwt.getClaim(JwtConstants.CLAIM_ISSUER));
-                LOG.debug("Created date={}", created);
-                LOG.debug("Expired date={}", expires);
-                
-                return idpToken;
-            } catch (IllegalStateException ex) {
-                throw ex;
-            } catch (Exception ex) {
-                LOG.warn("Unexpected exception occured", ex);
-                throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
-            }
-        }
-        return null;
-    }
-    
-    protected void validateToken(JwtToken jwt, String clientId) {
-        // We must have the following claims
-        if (jwt.getClaim(JwtConstants.CLAIM_ISSUER) == null
-            || jwt.getClaim(JwtConstants.CLAIM_SUBJECT) == null
-            || jwt.getClaim(JwtConstants.CLAIM_AUDIENCE) == null
-            || jwt.getClaim(JwtConstants.CLAIM_EXPIRY) == null
-            || jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT) == null) {
-            LOG.warn("The IdToken is missing a required claim");
-            throw new IllegalStateException("The IdToken is missing a required claim");
-        }
-        
-        // The audience must match the client_id of this client
-        boolean match = false;
-        for (String audience : jwt.getClaims().getAudiences()) {
-            if (clientId.equals(audience)) {
-                match = true;
-                break;
-            }
-        }
-        if (!match) {
-            LOG.warn("The audience of the token does not match this client");
-            throw new IllegalStateException("The audience of the token does not match this client");
-        }
-        
-        JwtUtils.validateTokenClaims(jwt.getClaims(), 300, 0, false);
-    }
-    
-    private boolean validateSignature(TrustedIdp trustedIdp, JwsJwtCompactConsumer jwtConsumer) 
-        throws CertificateException, WSSecurityException, Base64DecodingException, 
-            ProcessingException, IOException {
-        
-        // Validate the Signature
-        String sigAlgo = getProperty(trustedIdp, SIGNATURE_ALGORITHM);
-        if (sigAlgo == null || sigAlgo.isEmpty()) {
-            sigAlgo = "RS256";
-        }
-        
-        JwtToken jwt = jwtConsumer.getJwtToken();
-        String jwksUri = getProperty(trustedIdp, JWKS_URI);
-        JsonWebKey verifyingKey = null;
-        
-        if (jwksUri != null && jwt.getJwsHeaders() != null 
-            && jwt.getJwsHeaders().containsHeader(JoseConstants.HEADER_KEY_ID)) {
-            String kid = (String)jwt.getJwsHeaders().getHeader(JoseConstants.HEADER_KEY_ID);
-            LOG.debug("Attemping to retrieve key id {} from uri {}", kid, jwksUri);
-            List<Object> jsonKeyProviders = new ArrayList<Object>();
-            jsonKeyProviders.add(new JsonWebKeysProvider());
-            
-            WebClient client = 
-                WebClient.create(jwksUri, jsonKeyProviders, "cxf-tls.xml");
-            client.accept("application/json");
-            
-            ClientConfiguration config = WebClient.getConfig(client);
-            if (LOG.isDebugEnabled()) {
-                config.getOutInterceptors().add(new LoggingOutInterceptor());
-                config.getInInterceptors().add(new LoggingInInterceptor());
-            }
-            
-            Response response = client.get();
-            JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);
-            if (jsonWebKeys != null) {
-                verifyingKey = jsonWebKeys.getKey(kid);
-            }
-        }
-        
-        if (verifyingKey != null) {
-            return jwtConsumer.verifySignatureWith(verifyingKey, SignatureAlgorithm.getAlgorithm(sigAlgo));
-        }
-        
-        X509Certificate validatingCert = CertsUtils.parseX509Certificate(trustedIdp.getCertificate());
-        if (validatingCert != null) {
-            return jwtConsumer.verifySignatureWith(validatingCert, SignatureAlgorithm.getAlgorithm(sigAlgo));
-        }
-        
-        LOG.warn("No key supplied to verify the signature of the IdToken");
-        return false;
-    }
-    
-    protected String getScope(TrustedIdp trustedIdp) {
-        String scope = getProperty(trustedIdp, SCOPE);
-        if (scope != null) {
-            scope = scope.trim();
-            if (!scope.contains("openid")) {
-                scope = "openid " + scope;
-            }
-        }
-        
-        if (scope == null || scope.isEmpty()) {
-            scope = "openid";
-        }
-        return scope;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
deleted file mode 100644
index 31bc572..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class TrustedIdpProtocolControllerImpl implements ProtocolController<TrustedIdpProtocolHandler> {
-
-    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpProtocolControllerImpl.class);
-    
-    @Autowired
-    private List<TrustedIdpProtocolHandler> protocolHandlers;
-    
-    @Override
-    public TrustedIdpProtocolHandler getProtocolHandler(String protocol) {
-        for (TrustedIdpProtocolHandler protocolHandler : protocolHandlers) {
-            if (protocolHandler.getProtocol().equals(protocol)) {
-                return protocolHandler;
-            }
-        }
-        LOG.warn("No protocol handler found for {}", protocol);
-        return null;
-    }
-    
-    @Override
-    public List<String> getProtocols() {
-        List<String> protocols = new ArrayList<>();
-        for (TrustedIdpProtocolHandler protocolHandler : protocolHandlers) {
-            protocols.add(protocolHandler.getProtocol());
-        }
-        return Collections.unmodifiableList(protocols);
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
deleted file mode 100644
index 7b8c3eb..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
+++ /dev/null
@@ -1,415 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.security.PrivateKey;
-import java.security.Signature;
-import java.security.cert.X509Certificate;
-import java.util.zip.DataFormatException;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.BadRequestException;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.UriBuilder;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.apache.cxf.common.util.Base64Exception;
-import org.apache.cxf.common.util.Base64Utility;
-import org.apache.cxf.common.util.StringUtils;
-import org.apache.cxf.fediz.core.util.CertsUtils;
-import org.apache.cxf.fediz.core.util.DOMUtils;
-import org.apache.cxf.fediz.service.idp.IdpConstants;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.jaxrs.utils.ExceptionUtils;
-import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
-import org.apache.cxf.rs.security.saml.sso.AuthnRequestBuilder;
-import org.apache.cxf.rs.security.saml.sso.DefaultAuthnRequestBuilder;
-import org.apache.cxf.rs.security.saml.sso.EHCacheTokenReplayCache;
-import org.apache.cxf.rs.security.saml.sso.SAMLProtocolResponseValidator;
-import org.apache.cxf.rs.security.saml.sso.SAMLSSOResponseValidator;
-import org.apache.cxf.rs.security.saml.sso.SSOConstants;
-import org.apache.cxf.rs.security.saml.sso.SSOValidatorResponse;
-import org.apache.cxf.rs.security.saml.sso.TokenReplayCache;
-import org.apache.cxf.staxutils.StaxUtils;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.wss4j.common.crypto.Crypto;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.common.saml.OpenSAMLUtil;
-import org.apache.wss4j.common.util.DOM2Writer;
-import org.apache.xml.security.stax.impl.util.IDGenerator;
-import org.apache.xml.security.utils.Base64;
-import org.opensaml.core.xml.XMLObject;
-import org.opensaml.saml.saml2.core.AuthnRequest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-@Component
-public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHandler {
-    /**
-     * Whether to sign the request or not. The default is "true".
-     */
-    public static final String SIGN_REQUEST = "sign.request";
-    
-    /**
-     * Whether to require a KeyInfo or not when processing a (signed) Response. The default is "true".
-     */
-    public static final String REQUIRE_KEYINFO = "require.keyinfo";
-    
-    /**
-     * Whether the assertions contained in the Response must be signed or not (if the response itself
-     * is not signed). The default is "true".
-     */
-    public static final String REQUIRE_SIGNED_ASSERTIONS = "require.signed.assertions";
-    
-    /**
-     * Whether we have to "know" the issuer of the SAML Response or not. The default is "true".
-     */
-    public static final String REQUIRE_KNOWN_ISSUER = "require.known.issuer";
-    
-    /**
-     * Whether we BASE-64 decode the response or not. The default is "true".
-     */
-    public static final String SUPPORT_BASE64_ENCODING = "support.base64.encoding";
-    
-    /**
-     * Whether we support Deflate encoding or not. The default is "false".
-     */
-    public static final String SUPPORT_DEFLATE_ENCODING = "support.deflate.encoding";
-
-    public static final String PROTOCOL = "urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser";
-
-    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpSAMLProtocolHandler.class);
-    private static final String SAML_SSO_REQUEST_ID = "saml-sso-request-id";
-
-    private AuthnRequestBuilder authnRequestBuilder = new DefaultAuthnRequestBuilder();
-    private TokenReplayCache<String> replayCache;
-
-    static {
-        OpenSAMLUtil.initSamlEngine();
-    }
-
-    @Override
-    public String getProtocol() {
-        return PROTOCOL;
-    }
-
-    @Override
-    public URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
-
-        try {
-            Document doc = DOMUtils.createDocument();
-            doc.appendChild(doc.createElement("root"));
-            // Create the AuthnRequest
-            AuthnRequest authnRequest = 
-                authnRequestBuilder.createAuthnRequest(
-                    null, idp.getRealm(), idp.getIdpUrl().toString()
-                );
-            
-            boolean signRequest = isBooleanPropertyConfigured(trustedIdp, SIGN_REQUEST, true);
-            if (signRequest) {
-                authnRequest.setDestination(trustedIdp.getUrl());
-            }
-            Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
-            String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);
-
-            String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");
-
-            UriBuilder ub = UriBuilder.fromUri(trustedIdp.getUrl());
-
-            ub.queryParam(SSOConstants.SAML_REQUEST, urlEncodedRequest);
-            
-            String wctx = context.getFlowScope().getString(IdpConstants.TRUSTED_IDP_CONTEXT);
-            ub.queryParam(SSOConstants.RELAY_STATE, wctx);
-            if (signRequest) {
-                signRequest(urlEncodedRequest, wctx, idp, ub);
-            }
-            
-            // Store the Request ID
-            String authnRequestId = authnRequest.getID();
-            WebUtils.putAttributeInExternalContext(context, SAML_SSO_REQUEST_ID, authnRequestId);
-
-            HttpServletResponse response = WebUtils.getHttpServletResponse(context);
-            response.addHeader("Cache-Control", "no-cache, no-store");
-            response.addHeader("Pragma", "no-cache");
-
-            return ub.build().toURL();
-        } catch (MalformedURLException ex) {
-            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
-            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
-        } catch (UnsupportedEncodingException ex) {
-            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
-            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
-        } catch (Exception ex) {
-            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
-            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
-        }
-    }
-
-    @Override
-    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
-
-        try {
-            String encodedSAMLResponse = (String) WebUtils.getAttributeFromFlowScope(context, 
-                                                                                     SSOConstants.SAML_RESPONSE);
-            
-            // Read the response + convert to an OpenSAML Response Object
-            org.opensaml.saml.saml2.core.Response samlResponse = 
-                readSAMLResponse(encodedSAMLResponse, trustedIdp);
-            
-            Crypto crypto = CertsUtils.getCryptoFromCertificate(trustedIdp.getCertificate());
-            validateSamlResponseProtocol(samlResponse, crypto, trustedIdp);
-            // Validate the Response
-            SSOValidatorResponse validatorResponse = 
-                validateSamlSSOResponse(samlResponse, idp, trustedIdp, context);
-
-            // Create new Security token with new id. 
-            // Parameters for freshness computation are copied from original IDP_TOKEN
-            String id = IDGenerator.generateID("_");
-            SecurityToken idpToken = 
-                new SecurityToken(id, validatorResponse.getCreated(), validatorResponse.getSessionNotOnOrAfter());
-
-            idpToken.setToken(validatorResponse.getAssertionElement());
-            String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
-            LOG.info("[IDP_TOKEN={}] created from [RP_TOKEN={}] issued by home realm [{}]",
-                     id, validatorResponse.getResponseId(), whr);
-            LOG.debug("Created date={}", validatorResponse.getCreated());
-            LOG.debug("Expired date={}", validatorResponse.getSessionNotOnOrAfter());
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Validated: "
-                    + System.getProperty("line.separator") + validatorResponse.getAssertion());
-            }
-            return idpToken;
-        } catch (BadRequestException ex) {
-            throw ex;
-        } catch (Exception ex) {
-            LOG.warn("Unexpected exception occured", ex);
-            throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
-        }
-    }
-    
-    private String encodeAuthnRequest(Element authnRequest) throws IOException {
-        String requestMessage = DOM2Writer.nodeToString(authnRequest);
-        
-        if (LOG.isDebugEnabled()) {
-            LOG.debug(requestMessage);
-        }
-
-        DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
-        byte[] deflatedBytes = encoder.deflateToken(requestMessage.getBytes("UTF-8"));
-
-        return Base64Utility.encode(deflatedBytes);
-    }
-    
-    /**
-     * Sign a request according to the redirect binding spec for Web SSO
-     */
-    private void signRequest(
-        String authnRequest,
-        String relayState,
-        Idp config,
-        UriBuilder ub
-    ) throws Exception {
-        Crypto crypto = CertsUtils.getCryptoFromCertificate(config.getCertificate());
-        if (crypto == null) {
-            LOG.error("No crypto instance of properties file configured for signature");
-            throw new IllegalStateException("Invalid IdP configuration");
-        }
-        
-        String alias = crypto.getDefaultX509Identifier();
-        X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, alias);
-        if (cert == null) {
-            LOG.error("No cert was found to sign the request using alias: " + alias);
-            throw new IllegalStateException("Invalid IdP configuration");
-        }
-
-        String sigAlgo = SSOConstants.RSA_SHA1;
-        String pubKeyAlgo = cert.getPublicKey().getAlgorithm();
-        String jceSigAlgo = "SHA1withRSA";
-        LOG.debug("automatic sig algo detection: " + pubKeyAlgo);
-        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
-            sigAlgo = SSOConstants.DSA_SHA1;
-            jceSigAlgo = "SHA1withDSA";
-        }
-        LOG.debug("Using Signature algorithm " + sigAlgo);
-        
-        ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, "UTF-8"));
-        
-        // Get the password
-        String password = config.getCertificatePassword();
-        
-        // Get the private key
-        PrivateKey privateKey = crypto.getPrivateKey(alias, password);
-        
-        // Sign the request
-        Signature signature = Signature.getInstance(jceSigAlgo);
-        signature.initSign(privateKey);
-       
-        String requestToSign = 
-            SSOConstants.SAML_REQUEST + "=" + authnRequest + "&"
-            + SSOConstants.RELAY_STATE + "=" + relayState + "&"
-            + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, "UTF-8");
-
-        signature.update(requestToSign.getBytes("UTF-8"));
-        byte[] signBytes = signature.sign();
-        
-        String encodedSignature = Base64.encode(signBytes);
-        
-        ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, "UTF-8"));
-    }
-
-    private org.opensaml.saml.saml2.core.Response readSAMLResponse(String samlResponse, TrustedIdp trustedIdp) {
-        if (StringUtils.isEmpty(samlResponse)) {
-            throw ExceptionUtils.toBadRequestException(null, null);
-        }
-
-        String samlResponseDecoded = samlResponse;
-        
-        InputStream tokenStream = null;
-        if (isBooleanPropertyConfigured(trustedIdp, SUPPORT_BASE64_ENCODING, true)) {
-            try {
-                byte[] deflatedToken = Base64Utility.decode(samlResponseDecoded);
-                tokenStream = isBooleanPropertyConfigured(trustedIdp, SUPPORT_DEFLATE_ENCODING, false)
-                    ? new DeflateEncoderDecoder().inflateToken(deflatedToken)
-                    : new ByteArrayInputStream(deflatedToken); 
-            } catch (Base64Exception ex) {
-                throw ExceptionUtils.toBadRequestException(ex, null);
-            } catch (DataFormatException ex) {
-                throw ExceptionUtils.toBadRequestException(ex, null);
-            }
-        } else {
-            try {
-                tokenStream = new ByteArrayInputStream(samlResponseDecoded.getBytes("UTF-8"));
-            } catch (UnsupportedEncodingException ex) {
-                throw ExceptionUtils.toBadRequestException(ex, null);
-            }
-        }
-
-        Document responseDoc = null;
-        try {
-            responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, "UTF-8"));
-        } catch (Exception ex) {
-            throw new WebApplicationException(400);
-        }
-        
-        LOG.debug("Received response: " + DOM2Writer.nodeToString(responseDoc.getDocumentElement()));
-        
-        XMLObject responseObject = null;
-        try {
-            responseObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
-        } catch (WSSecurityException ex) {
-            throw ExceptionUtils.toBadRequestException(ex, null);
-        }
-        if (!(responseObject instanceof org.opensaml.saml.saml2.core.Response)) {
-            throw ExceptionUtils.toBadRequestException(null, null);
-        }
-        return (org.opensaml.saml.saml2.core.Response)responseObject;
-
-    }
-    
-    /**
-     * Validate the received SAML Response as per the protocol
-     */
-    private void validateSamlResponseProtocol(
-        org.opensaml.saml.saml2.core.Response samlResponse, Crypto crypto, TrustedIdp trustedIdp
-    ) {
-        try {
-            SAMLProtocolResponseValidator protocolValidator = new SAMLProtocolResponseValidator();
-            protocolValidator.setKeyInfoMustBeAvailable(
-                isBooleanPropertyConfigured(trustedIdp, REQUIRE_KEYINFO, true));
-            protocolValidator.validateSamlResponse(samlResponse, crypto, null);
-        } catch (WSSecurityException ex) {
-            LOG.debug(ex.getMessage(), ex);
-            throw ExceptionUtils.toBadRequestException(null, null);
-        }
-    }
-    
-    /**
-     * Validate the received SAML Response as per the Web SSO profile
-     */
-    private SSOValidatorResponse validateSamlSSOResponse(
-        org.opensaml.saml.saml2.core.Response samlResponse,
-        Idp idp, 
-        TrustedIdp trustedIdp,
-        RequestContext requestContext
-    ) {
-        try {
-            SAMLSSOResponseValidator ssoResponseValidator = new SAMLSSOResponseValidator();
-            ssoResponseValidator.setAssertionConsumerURL(idp.getIdpUrl().toString());
-
-            HttpServletRequest servletRequest = WebUtils.getHttpServletRequest(requestContext);
-            ssoResponseValidator.setClientAddress(servletRequest.getRemoteAddr());
-
-            String issuer = trustedIdp.getIssuer();
-            if (issuer == null || issuer.isEmpty()) {
-                LOG.debug("Issuer name is not defined in trusted 3rd party configuration. "
-                    + "Using URL instead for issuer validation");
-                issuer = trustedIdp.getUrl();
-            }
-            LOG.debug("Using {} for issuer validation", issuer);
-            ssoResponseValidator.setIssuerIDP(issuer);
-            
-            // Get the stored request ID
-            String requestId = 
-                (String)WebUtils.getAttributeFromExternalContext(requestContext, SAML_SSO_REQUEST_ID);
-            ssoResponseValidator.setRequestId(requestId);
-            ssoResponseValidator.setSpIdentifier(idp.getRealm());
-            ssoResponseValidator.setEnforceAssertionsSigned(
-                isBooleanPropertyConfigured(trustedIdp, REQUIRE_SIGNED_ASSERTIONS, true));
-            ssoResponseValidator.setEnforceKnownIssuer(
-                isBooleanPropertyConfigured(trustedIdp, REQUIRE_KNOWN_ISSUER, true));
-            
-            HttpServletRequest httpServletRequest = WebUtils.getHttpServletRequest(requestContext);
-            boolean post = "POST".equals(httpServletRequest.getMethod());
-            if (post) {
-                ssoResponseValidator.setReplayCache(getReplayCache());
-            }
-
-            return ssoResponseValidator.validateSamlResponse(samlResponse, post);
-        } catch (WSSecurityException ex) {
-            LOG.debug(ex.getMessage(), ex);
-            throw ExceptionUtils.toBadRequestException(ex, null);
-        }
-    }
-    
-    public void setReplayCache(TokenReplayCache<String> replayCache) {
-        this.replayCache = replayCache;
-    }
-    
-    public TokenReplayCache<String> getReplayCache() {
-        if (replayCache == null) {
-            replayCache = new EHCacheTokenReplayCache();
-        }
-        return replayCache;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
deleted file mode 100644
index ea8feb4..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.protocols;
-
-import java.io.UnsupportedEncodingException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.security.cert.X509Certificate;
-import java.util.Collections;
-
-import org.w3c.dom.Element;
-import org.apache.cxf.fediz.core.FederationConstants;
-import org.apache.cxf.fediz.core.config.FedizContext;
-import org.apache.cxf.fediz.core.config.TrustManager;
-import org.apache.cxf.fediz.core.config.jaxb.AudienceUris;
-import org.apache.cxf.fediz.core.config.jaxb.CertificateStores;
-import org.apache.cxf.fediz.core.config.jaxb.ContextConfig;
-import org.apache.cxf.fediz.core.config.jaxb.FederationProtocolType;
-import org.apache.cxf.fediz.core.config.jaxb.KeyStoreType;
-import org.apache.cxf.fediz.core.config.jaxb.TrustManagersType;
-import org.apache.cxf.fediz.core.config.jaxb.TrustedIssuerType;
-import org.apache.cxf.fediz.core.config.jaxb.TrustedIssuers;
-import org.apache.cxf.fediz.core.config.jaxb.ValidationType;
-import org.apache.cxf.fediz.core.exception.ProcessingException;
-import org.apache.cxf.fediz.core.processor.FederationProcessorImpl;
-import org.apache.cxf.fediz.core.processor.FedizProcessor;
-import org.apache.cxf.fediz.core.processor.FedizRequest;
-import org.apache.cxf.fediz.core.processor.FedizResponse;
-import org.apache.cxf.fediz.core.util.CertsUtils;
-import org.apache.cxf.fediz.service.idp.IdpConstants;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.wss4j.common.crypto.CertificateStore;
-import org.apache.xml.security.stax.impl.util.IDGenerator;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-@Component
-public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHandler {
-    
-    /**
-     * Whether to add the home realm parameter to the URL for redirection or not. The default is "true".
-     */
-    public static final String HOME_REALM_PROPAGATION = "home.realm.propagation";
-    
-    public static final String PROTOCOL = "http://docs.oasis-open.org/wsfed/federation/200706";
-
-    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpWSFedProtocolHandler.class);
-
-    @Override
-    public String getProtocol() {
-        return PROTOCOL;
-    }
-    
-    @Override
-    public URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
-        
-        try {
-            StringBuilder sb = new StringBuilder();
-            sb.append(trustedIdp.getUrl());
-            sb.append("?").append(FederationConstants.PARAM_ACTION).append('=');
-            sb.append(FederationConstants.ACTION_SIGNIN);
-            sb.append("&").append(FederationConstants.PARAM_TREALM).append('=');
-            sb.append(URLEncoder.encode(idp.getRealm(), "UTF-8"));
-            sb.append("&").append(FederationConstants.PARAM_REPLY).append('=');
-            sb.append(URLEncoder.encode(idp.getIdpUrl().toString(), "UTF-8"));
-            
-            if (isBooleanPropertyConfigured(trustedIdp, HOME_REALM_PROPAGATION, true)) {
-                sb.append("&").append(FederationConstants.PARAM_HOME_REALM).append('=');
-                sb.append(trustedIdp.getRealm());
-            }
-            
-            String wfresh = context.getFlowScope().getString(FederationConstants.PARAM_FRESHNESS);
-            if (wfresh != null) {
-                sb.append("&").append(FederationConstants.PARAM_FRESHNESS).append('=');
-                sb.append(URLEncoder.encode(wfresh, "UTF-8"));
-            }
-            String wctx = context.getFlowScope().getString(IdpConstants.TRUSTED_IDP_CONTEXT);
-            sb.append("&").append(FederationConstants.PARAM_CONTEXT).append('=');
-            sb.append(wctx);
-        
-            return new URL(sb.toString());
-        } catch (MalformedURLException ex) {
-            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
-            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
-        } catch (UnsupportedEncodingException ex) {
-            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
-            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
-        }
-    }
-    
-    @Override
-    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
-
-        try {
-            String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
-    
-            if (whr == null) {
-                LOG.warn("Home realm is null");
-                throw new IllegalStateException("Home realm is null");
-            }
-    
-            String wresult = (String) WebUtils.getAttributeFromFlowScope(context,
-                                                                         FederationConstants.PARAM_RESULT);
-    
-            if (wresult == null) {
-                LOG.warn("Parameter wresult not found");
-                throw new IllegalStateException("No security token issued");
-            }
-    
-            FedizContext fedContext = getFedizContext(idp, trustedIdp);
-    
-            FedizRequest wfReq = new FedizRequest();
-            wfReq.setAction(FederationConstants.ACTION_SIGNIN);
-            wfReq.setResponseToken(wresult);
-    
-            FedizProcessor wfProc = new FederationProcessorImpl();
-            FedizResponse wfResp = wfProc.processRequest(wfReq, fedContext);
-    
-            fedContext.close();
-    
-            Element e = wfResp.getToken();
-    
-            // Create new Security token with new id. 
-            // Parameters for freshness computation are copied from original IDP_TOKEN
-            String id = IDGenerator.generateID("_");
-            SecurityToken idpToken = new SecurityToken(id,
-                                                       wfResp.getTokenCreated(), wfResp.getTokenExpires());
-    
-            idpToken.setToken(e);
-            LOG.info("[IDP_TOKEN={}] for user '{}' created from [RP_TOKEN={}] issued by home realm [{}/{}]",
-                     id, wfResp.getUsername(), wfResp.getUniqueTokenId(), whr, wfResp.getIssuer());
-            LOG.debug("Created date={}", wfResp.getTokenCreated());
-            LOG.debug("Expired date={}", wfResp.getTokenExpires());
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Validated 'wresult' : "
-                    + System.getProperty("line.separator") + wresult);
-            }
-            return idpToken;
-        } catch (IllegalStateException ex) {
-            throw ex;
-        } catch (Exception ex) {
-            LOG.warn("Unexpected exception occured", ex);
-            throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
-        }
-    }
-    
-    
-    private FedizContext getFedizContext(Idp idpConfig,
-            TrustedIdp trustedIdpConfig) throws ProcessingException {
-
-        ContextConfig config = new ContextConfig();
-
-        config.setName("whatever");
-
-        // Configure certificate store
-        String certificate = trustedIdpConfig.getCertificate();
-        boolean isCertificateLocation = !certificate.startsWith("-----BEGIN CERTIFICATE");
-        if (isCertificateLocation) {
-            CertificateStores certStores = new CertificateStores();
-            TrustManagersType tm0 = new TrustManagersType();
-            KeyStoreType ks0 = new KeyStoreType();
-            ks0.setType("PEM");
-            // ks0.setType("JKS");
-            // ks0.setPassword("changeit");
-            ks0.setFile(trustedIdpConfig.getCertificate());
-            tm0.setKeyStore(ks0);
-            certStores.getTrustManager().add(tm0);
-            config.setCertificateStores(certStores);
-        }
-        
-        // Configure trusted IDP
-        TrustedIssuers trustedIssuers = new TrustedIssuers();
-        TrustedIssuerType ti0 = new TrustedIssuerType();
-        ti0.setCertificateValidation(ValidationType.PEER_TRUST);
-        ti0.setName(trustedIdpConfig.getName());
-        // ti0.setSubject(".*CN=www.sts.com.*");
-        trustedIssuers.getIssuer().add(ti0);
-        config.setTrustedIssuers(trustedIssuers);
-
-        FederationProtocolType protocol = new FederationProtocolType();
-        config.setProtocol(protocol);
-
-        AudienceUris audienceUris = new AudienceUris();
-        audienceUris.getAudienceItem().add(idpConfig.getRealm());
-        config.setAudienceUris(audienceUris);
-
-        FedizContext fedContext = new FedizContext(config);
-        if (!isCertificateLocation) {
-            CertificateStore cs = null;
-            
-            X509Certificate cert;
-            try {
-                cert = CertsUtils.parseX509Certificate(trustedIdpConfig.getCertificate());
-            } catch (Exception ex) {
-                LOG.error("Failed to parse trusted certificate", ex);
-                throw new ProcessingException("Failed to parse trusted certificate");
-            }
-            cs = new CertificateStore(Collections.singletonList(cert).toArray(new X509Certificate[0]));
-            
-            TrustManager tm = new TrustManager(cs);
-            fedContext.getCertificateStores().add(tm);
-        }
-        
-        fedContext.init();
-        return fedContext;
-    }
-    
-}


[04/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
deleted file mode 100644
index 2034dca..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.List;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
-
-import org.springframework.security.access.prepost.PreAuthorize;
-
-
-@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Path("applications")
-public interface ApplicationService {
-
-    @GET
-    @PreAuthorize("hasRole('APPLICATION_LIST')")
-    Applications getApplications(@QueryParam("start") int start,
-                                 @QueryParam("size") @DefaultValue("2") int size,
-                                 @QueryParam("expand") @DefaultValue("all")  List<String> expand,
-                                 @Context UriInfo uriInfo);
-
-    @GET
-    @Path("{realm}")
-    @PreAuthorize("hasRole('APPLICATION_LIST')")
-    Application getApplication(@PathParam("realm") String realm,
-                               @QueryParam("expand") @DefaultValue("all")  List<String> expand);
-
-    @POST
-    @PreAuthorize("hasRole('APPLICATION_CREATE')")
-    Response addApplication(@Context UriInfo ui, Application service);
-    
-    @PUT
-    @Path("{realm}")
-    @PreAuthorize("hasRole('APPLICATION_UPDATE')")
-    Response updateApplication(@Context UriInfo ui, @PathParam("realm") String realm, Application application);
-    
-    @DELETE
-    @Path("{realm}")
-    @PreAuthorize("hasRole('APPLICATION_DELETE')")
-    Response deleteApplication(@PathParam("realm") String realm);
-    
-    @POST
-    @Path("{realm}/claims")
-    @PreAuthorize("hasRole('APPLICATION_UPDATE')")
-    Response addClaimToApplication(@Context UriInfo ui, @PathParam("realm") String realm, RequestClaim claim);
-    
-    @DELETE
-    @Path("{realm}/claims/{claimType}")
-    @PreAuthorize("hasRole('APPLICATION_UPDATE')")
-    Response removeClaimFromApplication(@Context UriInfo ui, @PathParam("realm") String realm,
-                                        @PathParam("claimType") String claimType);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
deleted file mode 100644
index 1b2f6ff..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.net.URI;
-import java.util.List;
-
-import javax.ws.rs.BadRequestException;
-import javax.ws.rs.NotFoundException;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
-import org.apache.cxf.fediz.service.idp.service.ApplicationDAO;
-import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class ApplicationServiceImpl implements ApplicationService {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(ApplicationServiceImpl.class);
-
-    @Autowired
-    private ApplicationDAO applicationDAO;
-    
-    @Autowired
-    private ClaimDAO claimDAO;
-           
-    @Override
-    public Applications getApplications(int start, int size, List<String> expand, UriInfo uriInfo) {
-        List<Application> applications = applicationDAO.getApplications(start, size, expand);
-        
-        for (Application a : applications) {
-            URI self = uriInfo.getAbsolutePathBuilder().path(a.getRealm()).build();
-            a.setHref(self);
-        }
-        
-        Applications list = new Applications();
-        list.setApplications(applications);
-        return list;
-    }
-    
-    @Override
-    public Application getApplication(String realm, List<String> expand) {
-        Application application = applicationDAO.getApplication(realm, expand);
-        if (application == null) {
-            throw new NotFoundException();
-        } else {
-            return application;
-        }
-    }
-    
-    @Override
-    public Response addApplication(UriInfo ui, Application application) {
-        LOG.info("add Service config");
-        if (application.getRequestedClaims() != null && application.getRequestedClaims().size() > 0) {
-            LOG.warn("Application resource contains sub resource 'claims'");
-            throw new WebApplicationException(Status.BAD_REQUEST);
-        }
-        Application createdApplication = applicationDAO.addApplication(application);
-        
-        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
-        uriBuilder.path("{index}");
-        URI location = uriBuilder.build(createdApplication.getRealm());
-        return Response.created(location).entity(application).build();
-    }
-    
-    @Override
-    public Response updateApplication(UriInfo ui, String realm, Application application) {
-        if (!realm.equals(application.getRealm().toString())) {
-            throw new BadRequestException();
-        }
-        if (application.getRequestedClaims() != null && application.getRequestedClaims().size() > 0) {
-            LOG.warn("Application resource contains sub resource 'claims'");
-            throw new WebApplicationException(Status.BAD_REQUEST);
-        }
-        applicationDAO.updateApplication(realm, application);
-        
-        return Response.noContent().build();
-    }
- 
-    @Override
-    public Response deleteApplication(String realm) {
-        applicationDAO.deleteApplication(realm);
-        
-        return Response.noContent().build();
-    }
-    
-    @Override
-    public Response addClaimToApplication(UriInfo ui, String realm, RequestClaim claim) {
-        Application application = applicationDAO.getApplication(realm, null);
-        if (application.getRequestedClaims().contains(claim)) {
-            LOG.warn("Claim '" + claim.getClaimType() + "' already added");
-            //[TODO] Status.CONFLICT correct if the relation to with Claim already exists
-            throw new WebApplicationException(Status.CONFLICT);
-        }
-        Claim foundClaim = claimDAO.getClaim(claim.getClaimType().toString());
-        RequestClaim rc = new RequestClaim(foundClaim);
-        application.getRequestedClaims().add(rc);
-        applicationDAO.addClaimToApplication(application, claim);
-        
-        return Response.noContent().build();
-    }
-    
-    @Override
-    public Response removeClaimFromApplication(UriInfo ui, String realm,  String claimType) {
-        Application application = applicationDAO.getApplication(realm, null);
-        
-        RequestClaim foundItem = null; 
-        for (RequestClaim item : application.getRequestedClaims()) {
-            if (item.getClaimType().toString().equals(claimType)) {
-                foundItem = item;
-                break;
-            }
-        }
-        if (foundItem == null) {
-            LOG.warn("Claim '" + claimType + "' not found");
-            throw new WebApplicationException(Status.NOT_FOUND);
-        }
-        application.getRequestedClaims().remove(foundItem);
-        applicationDAO.removeClaimFromApplication(application, foundItem);
-        
-        return Response.noContent().build();
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Applications.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Applications.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Applications.java
deleted file mode 100644
index 5773a07..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Applications.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.Collection;
-
-import javax.xml.bind.annotation.XmlElementRef;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-
-@XmlRootElement(name = "applications", namespace = "http://org.apache.cxf.fediz/")
-public class Applications {
-
-    private Collection<Application> applications;
-
-    public Applications() {
-    }
-
-    public Applications(Collection<Application> applications) {
-        this.applications = applications;
-    }
-
-    @XmlElementRef
-    public Collection<Application> getApplications() {
-        return applications;
-    }
-
-    public void setApplications(Collection<Application> applications) {
-        this.applications = applications;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
deleted file mode 100644
index 47dac60..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-
-import org.springframework.security.access.prepost.PreAuthorize;
-
-
-@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Path("claims")
-public interface ClaimService {
-
-    @GET
-    @PreAuthorize("hasRole('CLAIM_LIST')")
-    Response getClaims(@QueryParam("start") int start,
-                       @QueryParam("size") @DefaultValue("2") int size,
-                       @Context UriInfo uriInfo);
-    
-    @GET
-    @Path("{claimType}")
-    @PreAuthorize("hasRole('CLAIM_READ')")
-    Claim getClaim(@PathParam("claimType") String claimType);
-
-    @POST
-    @PreAuthorize("hasRole('CLAIM_CREATE')")
-    Response addClaim(@Context UriInfo ui, Claim claim);
-    
-    @PUT
-    @Path("{claimType}")
-    @PreAuthorize("hasRole('CLAIM_UPDATE')")
-    Response updateClaim(@Context UriInfo ui, @PathParam("claimType") String claimType, Claim claim);
-    
-    @DELETE
-    @Path("{claimType}")
-    @PreAuthorize("hasRole('CLAIM_DELETE')")
-    Response deleteClaim(@PathParam("claimType") String claimType);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
deleted file mode 100644
index 141bfab..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.net.URI;
-import java.util.List;
-
-import javax.ws.rs.BadRequestException;
-import javax.ws.rs.NotFoundException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class ClaimServiceImpl implements ClaimService {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(ClaimServiceImpl.class);
-
-    @Autowired
-    private ClaimDAO claimDAO;
-
-    @Override
-    public Response getClaims(int start, int size, UriInfo uriInfo) {
-        List<Claim> claims = claimDAO.getClaims(start, size);
-        
-        for (Claim c : claims) {
-            URI self = uriInfo.getAbsolutePathBuilder().path(c.getClaimType().toString()).build();
-            c.setHref(self);
-        }
-        
-        Claims list = new Claims();
-        list.setClaims(claims);
-        
-        
-        //return Response.ok(list).type(MediaType.APPLICATION_JSON_TYPE).build();
-        return Response.ok(list).build();
-    }
-    
-    @Override
-    public Response addClaim(UriInfo ui, Claim claim) {
-        LOG.info("add Claim config");
-        
-        Claim createdClaim = claimDAO.addClaim(claim);
-        
-        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
-        uriBuilder.path("{index}");
-        URI location = uriBuilder.build(createdClaim.getClaimType().toString());
-        return Response.created(location).entity(claim).build();
-    }
-    
-    @Override
-    public Claim getClaim(String claimType) {
-        Claim claim = claimDAO.getClaim(claimType);
-        if (claim == null) {
-            throw new NotFoundException();
-        } else {
-            return claim;
-        }
-    }
-
-    @Override
-    public Response updateClaim(UriInfo ui, String claimType, Claim claim) {
-        if (!claimType.equals(claim.getClaimType().toString())) {
-            throw new BadRequestException();
-        }
-        claimDAO.updateClaim(claimType, claim);
-        
-        return Response.noContent().build();
-    }
-
-    @Override
-    public Response deleteClaim(String claimType) {
-        claimDAO.deleteClaim(claimType);
-        
-        return Response.noContent().build();
-    }
-           
-    
-
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Claims.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Claims.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Claims.java
deleted file mode 100644
index 891effd..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Claims.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.Collection;
-
-import javax.xml.bind.annotation.XmlElementRef;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-
-@XmlRootElement(name = "claims", namespace = "http://org.apache.cxf.fediz/")
-public class Claims {
-
-    private Collection<Claim> claims;
-
-    public Claims() {
-    }
-
-    public Claims(Collection<Claim> claims) {
-        this.claims = claims;
-    }
-
-    @XmlElementRef
-    public Collection<Claim> getClaims() {
-        return claims;
-    }
-
-    public void setClaims(Collection<Claim> claims) {
-        this.claims = claims;
-    }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
deleted file mode 100644
index 4bc392c..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-
-import org.springframework.security.access.prepost.PreAuthorize;
-
-
-@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Path("entitlements")
-public interface EntitlementService {
-
-    @GET
-    @PreAuthorize("hasRole('ENTITLEMENT_LIST')")
-    Entitlements getEntitlements(@QueryParam("start") int start,
-                                 @QueryParam("size") @DefaultValue("5") int size,
-                                 @Context UriInfo uriInfo);
-
-    @GET
-    @Path("{name}")
-    @PreAuthorize("hasRole('ENTITLEMENT_READ')")
-    Entitlement getEntitlement(@PathParam("name") String name);
-
-    @POST
-    @PreAuthorize("hasRole('ENTITLEMENT_CREATE')")
-    Response addEntitlement(@Context UriInfo ui, Entitlement entitlement);
-    
-    @PUT
-    @Path("{name}")
-    @PreAuthorize("hasRole('ENTITLEMENT_UPDATE')")
-    Response updateEntitlement(@Context UriInfo ui, @PathParam("name") String name, Entitlement entitlement);
-    
-    @DELETE
-    @Path("{name}")
-    @PreAuthorize("hasRole('ENTITLEMENT_DELETE')")
-    Response deleteEntitlement(@PathParam("name") String name);
-    
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
deleted file mode 100644
index 9c89c04..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.net.URI;
-import java.util.List;
-
-import javax.ws.rs.BadRequestException;
-import javax.ws.rs.NotFoundException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-import org.apache.cxf.fediz.service.idp.service.EntitlementDAO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class EntitlementServiceImpl implements EntitlementService {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(EntitlementServiceImpl.class);
-
-    @Autowired
-    private EntitlementDAO entitlementDAO;
-
-    @Override
-    public Entitlements getEntitlements(int start, int size, UriInfo uriInfo) {
-        List<Entitlement> entitlements = entitlementDAO.getEntitlements(start, size);
-        
-        Entitlements list = new Entitlements();
-        list.setEntitlements(entitlements);
-        
-        return list;
-    }
-    
-    @Override
-    public Response addEntitlement(UriInfo ui, Entitlement entitlement) {
-        Entitlement createdEntitlement = entitlementDAO.addEntitlement(entitlement);
-        
-        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
-        uriBuilder.path("{index}");
-        URI location = uriBuilder.build(createdEntitlement.getName());
-        
-        LOG.debug("Entitlement '" + createdEntitlement.getName() + "' added");
-        return Response.created(location).entity(entitlement).build();
-    }
-    
-    @Override
-    public Entitlement getEntitlement(String name) {
-        Entitlement entitlement = entitlementDAO.getEntitlement(name);
-        if (entitlement == null) {
-            throw new NotFoundException();
-        } else {
-            return entitlement;
-        }
-    }
-
-    @Override
-    public Response updateEntitlement(UriInfo ui, String name, Entitlement entitlement) {
-        if (!name.equals(entitlement.getName())) {
-            throw new BadRequestException();
-        }
-        entitlementDAO.updateEntitlement(name, entitlement);
-        
-        LOG.debug("Entitlement '" + entitlement.getName() + "' updated");
-        return Response.noContent().build();
-    }
-
-    @Override
-    public Response deleteEntitlement(String name) {
-        entitlementDAO.deleteEntitlement(name);
-        
-        LOG.debug("Entitlement '" + name + "' deleted");
-        return Response.noContent().build();
-    }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Entitlements.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Entitlements.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Entitlements.java
deleted file mode 100644
index 8f2e91a..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Entitlements.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.Collection;
-
-import javax.xml.bind.annotation.XmlElementRef;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-
-@XmlRootElement(name = "entitlements", namespace = "http://org.apache.cxf.fediz/")
-public class Entitlements {
-
-    private Collection<Entitlement> entitlements;
-
-    public Entitlements() {
-    }
-
-    public Entitlements(Collection<Entitlement> entitlements) {
-        this.entitlements = entitlements;
-    }
-
-    @XmlElementRef
-    public Collection<Entitlement> getEntitlements() {
-        return entitlements;
-    }
-
-    public void setEntitlements(Collection<Entitlement> entitlements) {
-        this.entitlements = entitlements;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
deleted file mode 100644
index b4692e8..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.List;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-
-import org.springframework.security.access.prepost.PreAuthorize;
-
-@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Path("idps")
-public interface IdpService {
-
-    @GET
-    @PreAuthorize("hasRole('IDP_LIST')")
-    Idps getIdps(@QueryParam("start") int start,
-                 @QueryParam("size") @DefaultValue("2") int size,
-                 @QueryParam("expand") @DefaultValue("all")  List<String> expand,
-                 @Context UriInfo uriInfo);
-
-    @GET
-    @Path("{realm}")
-    @PreAuthorize("hasRole('IDP_READ')")
-    Idp getIdp(@PathParam("realm") String realm,
-               @QueryParam("expand") @DefaultValue("all")  List<String> expand);
-
-    @POST
-    @PreAuthorize("hasRole('IDP_CREATE')")
-    Response addIdp(@Context UriInfo ui, Idp idp);
-    
-    @PUT
-    @Path("{realm}")
-    @PreAuthorize("hasRole('IDP_UPDATE')")
-    Response updateIdp(@Context UriInfo ui, @PathParam("realm") String realm, Idp idp);
-    
-    @DELETE
-    @Path("{realm}")
-    @PreAuthorize("hasRole('IDP_DELETE')")
-    Response deleteIdp(@PathParam("realm") String realm);
-    
-    @POST
-    @Path("{realm}/applications")
-    @PreAuthorize("hasRole('IDP_UPDATE')")
-    Response addApplicationToIdp(@Context UriInfo ui, @PathParam("realm") String realm,
-                                 Application application);
-    
-    @DELETE
-    @Path("{realm}/applications/{realmApplication}")
-    @PreAuthorize("hasRole('IDP_UPDATE')")
-    Response removeApplicationFromIdp(@Context UriInfo ui, @PathParam("realm") String realm,
-                                      @PathParam("realmApplication") String applicationRealm);
-    
-    @POST
-    @Path("{realm}/trusted-idps")
-    @PreAuthorize("hasRole('IDP_UPDATE')")
-    Response addTrustedIdpToIdp(@Context UriInfo ui, @PathParam("realm") String realm,
-                                TrustedIdp trustedIdp);
-    
-    @DELETE
-    @Path("{realm}/trusted-idps/{realmTrustedIdp}")
-    @PreAuthorize("hasRole('IDP_UPDATE')")
-    Response removeTrustedIdpFromIdp(@Context UriInfo ui, @PathParam("realm") String realm,
-                                     @PathParam("realmTrustedIdp") String trustedIdpRealm);
-    
-    @POST
-    @Path("{realm}/claims")
-    @PreAuthorize("hasRole('IDP_UPDATE')")
-    Response addClaimToIdp(@Context UriInfo ui, @PathParam("realm") String realm,
-                           Claim claim);
-    
-    @DELETE
-    @Path("{realm}/claims/{claimType}")
-    @PreAuthorize("hasRole('IDP_UPDATE')")
-    Response removeClaimFromIdp(@Context UriInfo ui, @PathParam("realm") String realm,
-                                @PathParam("claimType") String claimType);    
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
deleted file mode 100644
index d4b5c40..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
+++ /dev/null
@@ -1,240 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.net.URI;
-import java.util.Arrays;
-import java.util.List;
-
-import javax.ws.rs.BadRequestException;
-import javax.ws.rs.NotFoundException;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.service.ApplicationDAO;
-import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
-import org.apache.cxf.fediz.service.idp.service.IdpDAO;
-import org.apache.cxf.fediz.service.idp.service.TrustedIdpDAO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class IdpServiceImpl implements IdpService {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(IdpServiceImpl.class);
-
-    @Autowired
-    private IdpDAO idpDAO;
-    
-    @Autowired
-    private ApplicationDAO applicationDAO;
-    
-    @Autowired
-    private TrustedIdpDAO trustedIdpDAO;
-    
-    @Autowired
-    private ClaimDAO claimDAO;
-           
-    @Override
-    public Idps getIdps(int start, int size, List<String> expand, UriInfo uriInfo) {
-        List<Idp> idps = idpDAO.getIdps(start, size, expand);
-        
-        Idps list = new Idps();
-        list.setIdps(idps);
-        return list;
-    }
-    
-    @Override
-    public Idp getIdp(String realm, List<String> expand) {
-        Idp idp = idpDAO.getIdp(realm, expand);
-        if (idp == null) {
-            LOG.warn("IdP not found for realm {}", realm);
-            throw new NotFoundException();
-        } else {
-            return idp;
-        }
-    }
-    
-    @Override
-    public Response addIdp(UriInfo ui, Idp idp) {
-        LOG.info("add IDP config");
-        if (idp.getApplications() != null && idp.getApplications().size() > 0) {
-            LOG.warn("IDP resource contains sub resource 'applications'");
-            throw new WebApplicationException(Status.BAD_REQUEST);
-        }
-        if (idp.getTrustedIdps() != null && idp.getTrustedIdps().size() > 0) {
-            LOG.warn("IDP resource contains sub resource 'trusted-idps'");
-            throw new WebApplicationException(Status.BAD_REQUEST);
-        }
-        Idp createdIdp = idpDAO.addIdp(idp);
-        
-        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
-        uriBuilder.path("{index}");
-        URI location = uriBuilder.build(createdIdp.getRealm());
-        return Response.created(location).entity(idp).build();
-    }
-    
-    @Override
-    public Response updateIdp(UriInfo ui, String realm, Idp idp) {
-        if (!realm.equals(idp.getRealm().toString())) {
-            throw new BadRequestException();
-        }
-        if (idp.getApplications() != null && idp.getApplications().size() > 0) {
-            LOG.warn("IDP resource contains sub resource 'applications'");
-            throw new WebApplicationException(Status.BAD_REQUEST);
-        }
-        if (idp.getTrustedIdps() != null && idp.getTrustedIdps().size() > 0) {
-            LOG.warn("IDP resource contains sub resource 'trusted-idps'");
-            throw new WebApplicationException(Status.BAD_REQUEST);
-        }
-        idpDAO.updateIdp(realm, idp);
-        
-        return Response.noContent().build();
-    }
-
-    @Override
-    public Response deleteIdp(String realm) {
-        idpDAO.deleteIdp(realm);
-        
-        return Response.noContent().build();
-    }
-
-    @Override
-    public Response addApplicationToIdp(UriInfo ui, String realm, Application application) {
-        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        for (Application idpApplication : idp.getApplications()) {
-            if (idpApplication.getRealm() != null && idpApplication.getRealm().equals(application.getRealm())) {
-                LOG.warn("Application '" + application.getRealm() + "' already added");
-                throw new WebApplicationException(Status.CONFLICT);
-            }
-        }
-        Application application2 = applicationDAO.getApplication(application.getRealm(), null);
-        idpDAO.addApplicationToIdp(idp, application2);
-        
-        return Response.noContent().build();
-    }
-    
-    @Override
-    public Response removeApplicationFromIdp(UriInfo ui, String realm,  String applicationRealm) {
-        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        
-        Application foundItem = null; 
-        for (Application item : idp.getApplications()) {
-            if (item.getRealm().equals(applicationRealm)) {
-                foundItem = item;
-                break;
-            }
-        }
-        if (foundItem == null) {
-            LOG.warn("Application '" + applicationRealm + "' not found");
-            throw new WebApplicationException(Status.NOT_FOUND);
-        }
-        idpDAO.removeApplicationFromIdp(idp, foundItem);
-        
-        return Response.noContent().build();
-    }
-    
-    
-    
-    
-    @Override
-    public Response addTrustedIdpToIdp(UriInfo ui, String realm, TrustedIdp trustedIdp) {
-        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        for (TrustedIdp idpTrustedIdp : idp.getTrustedIdps()) {
-            if (idpTrustedIdp.getRealm() != null && idpTrustedIdp.getRealm().equals(trustedIdp.getRealm())) {
-                LOG.warn("Trusted IDP '" + trustedIdp.getRealm() + "' already added");
-                throw new WebApplicationException(Status.CONFLICT);
-            }
-        }
-        TrustedIdp trustedIpd2 = trustedIdpDAO.getTrustedIDP(trustedIdp.getRealm());
-        
-        idpDAO.addTrustedIdpToIdp(idp, trustedIpd2);
-        
-        return Response.noContent().build();
-    }
-    
-    @Override
-    public Response removeTrustedIdpFromIdp(UriInfo ui, String realm, String trustedIdpRealm) {
-        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        
-        TrustedIdp foundItem = null; 
-        for (TrustedIdp item : idp.getTrustedIdps()) {
-            if (item.getRealm().equals(trustedIdpRealm)) {
-                foundItem = item;
-                break;
-            }
-        }
-        if (foundItem == null) {
-            LOG.warn("Trusted IDP '" + trustedIdpRealm + "' not found");
-            throw new WebApplicationException(Status.NOT_FOUND);
-        }
-        idpDAO.removeTrustedIdpFromIdp(idp, foundItem);
-        
-        return Response.noContent().build();
-    }   
-    
-    @Override
-    public Response addClaimToIdp(UriInfo ui, String realm, Claim claim) {
-        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        for (Claim idpClaim : idp.getClaimTypesOffered()) {
-            if (idpClaim.getClaimType() != null 
-                && idpClaim.getClaimType().toString().equals(claim.getClaimType().toString())) {
-                LOG.warn("Claim '" + claim.getClaimType() + "' already added");
-                throw new WebApplicationException(Status.CONFLICT);
-            }
-        }
-        Claim claim2 = claimDAO.getClaim(claim.getClaimType().toString());
-        idpDAO.addClaimToIdp(idp, claim2);
-        
-        return Response.noContent().build();
-    }
-    
-    @Override
-    public Response removeClaimFromIdp(UriInfo ui, String realm, String claimType) {
-        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
-        
-        Claim foundItem = null; 
-        for (Claim item : idp.getClaimTypesOffered()) {
-            if (item.getClaimType().toString().equals(claimType)) {
-                foundItem = item;
-                break;
-            }
-        }
-        if (foundItem == null) {
-            LOG.warn("Claim '" + claimType + "' not found");
-            throw new WebApplicationException(Status.NOT_FOUND);
-        }
-        idpDAO.removeClaimFromIdp(idp, foundItem);
-                
-        return Response.noContent().build();
-    }
-
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Idps.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Idps.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Idps.java
deleted file mode 100644
index 08d7f50..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Idps.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.Collection;
-
-import javax.xml.bind.annotation.XmlElementRef;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-
-@XmlRootElement(name = "idps", namespace = "http://org.apache.cxf.fediz/")
-public class Idps {
-
-    private Collection<Idp> idps;
-
-    public Idps() {
-    }
-
-    public Idps(Collection<Idp> idps) {
-        this.idps = idps;
-    }
-
-    @XmlElementRef
-    public Collection<Idp> getIdps() {
-        return idps;
-    }
-
-    public void setIdps(Collection<Idp> idps) {
-        this.idps = idps;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
deleted file mode 100644
index 1e87bfc..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.List;
-import java.util.Map;
-
-import org.apache.cxf.jaxrs.ext.ResourceComparator;
-import org.apache.cxf.jaxrs.model.ClassResourceInfo;
-import org.apache.cxf.jaxrs.model.OperationResourceInfo;
-import org.apache.cxf.jaxrs.model.OperationResourceInfoComparator;
-import org.apache.cxf.jaxrs.model.Parameter;
-import org.apache.cxf.jaxrs.utils.JAXRSUtils;
-import org.apache.cxf.message.Message;
-
-public class QueryResourceInfoComparator extends OperationResourceInfoComparator implements ResourceComparator {
-
-    public QueryResourceInfoComparator() {
-        super(null, null);
-    }
-
-    @Override
-    public int compare(final ClassResourceInfo cri1, final ClassResourceInfo cri2, final Message message) {
-        // Leave Class selection to CXF
-        return 0;
-    }
-
-    @Override
-    public int compare(final OperationResourceInfo oper1, final OperationResourceInfo oper2, final Message message) {
-        // Check if CXF can make a decision
-        int cxfResult = super.compare(oper1, oper2);
-        if (cxfResult != 0) {
-            return cxfResult;
-        }
-
-        int op1Counter = getMatchingRate(oper1, message);
-        int op2Counter = getMatchingRate(oper2, message);
-
-        return op1Counter == op2Counter
-                ? 0
-                : op1Counter < op2Counter
-                ? 1
-                : -1;
-    }
-
-    /**
-     * This method calculates a number indicating a good or bad match between values provided within the request and
-     * expected method parameters. A higher number means a better match.
-     *
-     * @param operation The operation to be rated, based on contained parameterInfo values.
-     * @param message A message containing query and header values from user request
-     * @return A positive or negative number, indicating a good match between query and method
-     */
-    protected int getMatchingRate(final OperationResourceInfo operation, final Message message) {
-        List<Parameter> params = operation.getParameters();
-        if (params == null || params.isEmpty()) {
-            return 0;
-        }
-
-        // Get Request QueryParams
-        String query = (String) message.get(Message.QUERY_STRING);
-        String path = (String) message.get(Message.REQUEST_URI);
-        Map<String, List<String>> qParams = JAXRSUtils.getStructuredParams(query, "&", true, false);
-        Map<String, List<String>> mParams = JAXRSUtils.getMatrixParams(path, true);
-        // Get Request Headers
-        Map<?, ?> qHeader = (java.util.Map<?, ?>) message.get(Message.PROTOCOL_HEADERS);
-
-        int rate = 0;
-        for (Parameter p : params) {
-            switch (p.getType()) {
-            case QUERY:
-                if (qParams.containsKey(p.getName())) {
-                    rate += 2;
-                } else if (p.getDefaultValue() == null) {
-                    rate -= 1;
-                }
-                break;
-            case MATRIX:
-                if (mParams.containsKey(p.getName())) {
-                    rate += 2;
-                } else if (p.getDefaultValue() == null) {
-                    rate -= 1;
-                }
-                break;
-            case HEADER:
-                if (qHeader.containsKey(p.getName())) {
-                    rate += 2;
-                } else if (p.getDefaultValue() == null) {
-                    rate -= 1;
-                }
-                break;
-            default:
-                break;
-            }
-        }
-        return rate;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
deleted file mode 100644
index c7a1e1e..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import javax.validation.ConstraintViolationException;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.ext.ExceptionMapper;
-import javax.ws.rs.ext.Provider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.dao.DataIntegrityViolationException;
-import org.springframework.dao.DataRetrievalFailureException;
-import org.springframework.dao.EmptyResultDataAccessException;
-import org.springframework.security.access.AccessDeniedException;
-
-@Provider
-public class RestServiceExceptionMapper implements ExceptionMapper<Exception> {
-
-    public static final String APPLICATION_ERROR_CODE = "X-Application-Error-Code";
-    
-    public static final String APPLICATION_ERROR_INFO = "X-Application-Error-Info";
-    
-    private static final String BASIC_REALM_UNAUTHORIZED = "Basic realm=\"Apache Fediz authentication\"";
-
-    private static final Logger LOG = LoggerFactory.getLogger(RestServiceExceptionMapper.class);
-
-    @Override
-    public Response toResponse(final Exception ex) {
-        LOG.warn("Exception occured processing REST request: " + ex.getMessage(), ex);
-
-        if (ex instanceof AccessDeniedException) {
-            return Response.status(Response.Status.UNAUTHORIZED).
-                    header(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM_UNAUTHORIZED).
-                    build();
-        }
-        if (ex instanceof ConstraintViolationException) {
-            ConstraintViolationException cve = (ConstraintViolationException)ex;
-            LOG.debug("{}\n{}", ex.getMessage(), cve.getConstraintViolations().toString());
-            return buildResponse(Response.Status.BAD_REQUEST, ex);
-        }
-        if (ex instanceof DataIntegrityViolationException) {
-            return buildResponse(Response.Status.CONFLICT, ex);
-        }
-        
-        if (ex instanceof EmptyResultDataAccessException) {
-            return buildResponse(Response.Status.NOT_FOUND, ex);
-        }
-        
-        if (ex instanceof DataRetrievalFailureException) {
-            return buildResponse(Response.Status.NOT_FOUND, ex);
-        }
-
-        // Rest is interpreted as InternalServerError
-        return buildResponse(Response.Status.INTERNAL_SERVER_ERROR, ex);
-    }
-
-    Response buildResponse(final Status status, final Exception ex) {
-        ResponseBuilder responseBuilder = Response.status(status);
-        return responseBuilder.header(APPLICATION_ERROR_CODE, ex.getClass().getName())
-                              .header(APPLICATION_ERROR_INFO, ex.getMessage())
-                              .status(status).build();
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
deleted file mode 100644
index 27d498c..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.List;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-import org.apache.cxf.fediz.service.idp.domain.Role;
-
-import org.springframework.security.access.prepost.PreAuthorize;
-
-
-@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Path("roles")
-public interface RoleService {
-
-    @GET
-    @PreAuthorize("hasRole('ROLE_LIST')")
-    Roles getRoles(@QueryParam("start") int start,
-                                 @QueryParam("size") @DefaultValue("2") int size,
-                                 @QueryParam("expand") @DefaultValue("all")  List<String> expand,
-                                 @Context UriInfo uriInfo);
-
-    @GET
-    @Path("{name}")
-    @PreAuthorize("hasRole('ROLE_CREATE')")
-    Role getRole(@PathParam("name") String realm,
-                               @QueryParam("expand") @DefaultValue("all")  List<String> expand);
-
-    @POST
-    @PreAuthorize("hasRole('ROLE_CREATE')")
-    Response addRole(@Context UriInfo ui, Role role);
-    
-    @PUT
-    @Path("{name}")
-    @PreAuthorize("hasRole('ROLE_UPDATE')")
-    Response updateRole(@Context UriInfo ui, @PathParam("name") String name, Role role);
-    
-    @DELETE
-    @Path("{name}")
-    @PreAuthorize("hasRole('ROLE_DELETE')")
-    Response deleteRole(@PathParam("name") String name);
-    
-    @POST
-    @Path("{name}/entitlements")
-    @PreAuthorize("hasRole('ROLE_UPDATE')")
-    Response addEntitlementToRole(@Context UriInfo ui, @PathParam("name") String name, Entitlement entitlement);
-    
-    @DELETE
-    @Path("{name}/entitlements/{entitlementName}")
-    @PreAuthorize("hasRole('ROLE_UPDATE')")
-    Response removeEntitlementFromRole(@Context UriInfo ui, @PathParam("name") String name,
-                                        @PathParam("entitlementName") String entitlementName);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
deleted file mode 100644
index 24ff339..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.net.URI;
-import java.util.List;
-
-import javax.ws.rs.BadRequestException;
-import javax.ws.rs.NotFoundException;
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-import org.apache.cxf.fediz.service.idp.domain.Role;
-import org.apache.cxf.fediz.service.idp.service.EntitlementDAO;
-import org.apache.cxf.fediz.service.idp.service.RoleDAO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class RoleServiceImpl implements RoleService {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(RoleServiceImpl.class);
-
-    @Autowired
-    private RoleDAO roleDAO;
-    
-    @Autowired
-    private EntitlementDAO entitlementDAO;
-           
-    @Override
-    public Roles getRoles(int start, int size, List<String> expand, UriInfo uriInfo) {
-        List<Role> roles = roleDAO.getRoles(start, size, expand);
-        
-        Roles list = new Roles();
-        list.setRoles(roles);
-        return list;
-    }
-    
-    @Override
-    public Role getRole(String name, List<String> expand) {
-        Role role = roleDAO.getRole(name, expand);
-        if (role == null) {
-            throw new NotFoundException();
-        } else {
-            return role;
-        }
-    }
-    
-    @Override
-    public Response addRole(UriInfo ui, Role role) {
-        if (role.getEntitlements() != null && role.getEntitlements().size() > 0) {
-            LOG.warn("Role resource contains sub resource 'entitlements'");
-            throw new WebApplicationException(Status.BAD_REQUEST);
-        }
-        Role createdRole = roleDAO.addRole(role);
-        
-        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
-        uriBuilder.path("{index}");
-        URI location = uriBuilder.build(createdRole.getName());
-        
-        LOG.debug("Role '" + role.getName() + "' added");
-        return Response.created(location).entity(role).build();
-    }
-    
-    @Override
-    public Response updateRole(UriInfo ui, String name, Role role) {
-        if (!name.equals(role.getName().toString())) {
-            throw new BadRequestException();
-        }
-        if (role.getEntitlements() != null && role.getEntitlements().size() > 0) {
-            LOG.warn("Role resource contains sub resource 'entitlements'");
-            throw new WebApplicationException(Status.BAD_REQUEST);
-        }
-        roleDAO.updateRole(name, role);
-        
-        LOG.debug("Role '" + role.getName() + "' updated");
-        return Response.noContent().build();
-    }
- 
-    @Override
-    public Response deleteRole(String name) {
-        roleDAO.deleteRole(name);
-        
-        LOG.debug("Role '" + name + "' deleted");
-        return Response.noContent().build();
-    }
-    
-    @Override
-    public Response addEntitlementToRole(UriInfo ui, String name, Entitlement entitlement) {
-        Role role = roleDAO.getRole(name, null);
-        
-        Entitlement foundEntitlement = entitlementDAO.getEntitlement(entitlement.getName());
-        roleDAO.addEntitlementToRole(role, foundEntitlement);
-        
-        LOG.debug("Entitlement '" + entitlement.getName() + "' added to Role '" + name + "'");
-        return Response.noContent().build();
-    }
-    
-    @Override
-    public Response removeEntitlementFromRole(UriInfo ui, String name, String entitlementName) {
-        Role role = roleDAO.getRole(name, null);
-        Entitlement entitlement = entitlementDAO.getEntitlement(entitlementName);
-        
-        roleDAO.removeEntitlementFromRole(role, entitlement);
-        
-        LOG.debug("Entitlement '" + entitlementName + "' removed from Role '" + name + "'");
-        return Response.noContent().build();
-    }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java
deleted file mode 100644
index 6ecd2f2..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.Collection;
-
-import javax.xml.bind.annotation.XmlElementRef;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.apache.cxf.fediz.service.idp.domain.Role;
-
-@XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/")
-public class Roles {
-
-    private Collection<Role> roles;
-
-    public Roles() {
-    }
-
-    public Roles(Collection<Role> roles) {
-        this.roles = roles;
-    }
-
-    @XmlElementRef
-    public Collection<Role> getRoles() {
-        return roles;
-    }
-
-    public void setRoles(Collection<Role> roles) {
-        this.roles = roles;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootService.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootService.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootService.java
deleted file mode 100644
index 86d8a3b..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootService.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.HEAD;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-
-@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-public interface RootService {
-
-    @HEAD
-    Response head(@Context UriInfo uriInfo);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
deleted file mode 100644
index 03eb6da..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.net.URI;
-
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
-
-public class RootServiceImpl implements RootService {
-
-    public RootServiceImpl() {
-    }
-    
-    public Response head(UriInfo uriInfo) {
-        UriBuilder absolute = uriInfo.getBaseUriBuilder();
-        URI claimUrl = absolute.clone().path("claims").build();
-        URI idpUrl = absolute.clone().path("idps").build();
-        URI applicationUrl = absolute.clone().path("applications").build();
-        URI trustedIdpUrl = absolute.clone().path("trusted-idps").build();
-        URI rolesUrl = absolute.clone().path("roles").build();
-        URI entitlementsUrl = absolute.clone().path("entitlements").build();
-        javax.ws.rs.core.Link claims = javax.ws.rs.core.Link.fromUri(claimUrl).rel("claims")
-            .type("application/xml").build();
-        javax.ws.rs.core.Link idps = javax.ws.rs.core.Link.fromUri(idpUrl).rel("idps")
-            .type("application/xml").build();
-        javax.ws.rs.core.Link applications = javax.ws.rs.core.Link.fromUri(applicationUrl).rel("applications")
-            .type("application/xml").build();
-        javax.ws.rs.core.Link trustedIdps = javax.ws.rs.core.Link.fromUri(trustedIdpUrl).rel("trusted-idps")
-            .type("application/xml").build();
-        javax.ws.rs.core.Link roles = javax.ws.rs.core.Link.fromUri(rolesUrl).rel("roles")
-            .type("application/xml").build();
-        javax.ws.rs.core.Link entitlements = javax.ws.rs.core.Link.fromUri(entitlementsUrl).rel("entitlements")
-            .type("application/xml").build();
-
-        Response.ResponseBuilder builder = Response.ok().links(
-            claims, idps, applications, trustedIdps, roles, entitlements);
-        return builder.build();
-    }
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
deleted file mode 100644
index b76d91d..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.DefaultValue;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-
-import org.springframework.security.access.prepost.PreAuthorize;
-
-@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
-@Path("trusted-idps")
-public interface TrustedIdpService {
-
-    @GET
-    @PreAuthorize("hasRole('TRUSTEDIDP_LIST')")
-    TrustedIdps getTrustedIDPs(@QueryParam("start") int start,
-                               @QueryParam("size") @DefaultValue("2") int size,
-                               @Context UriInfo uriInfo);
-
-    @GET
-    @Path("{realm}")
-    @PreAuthorize("hasRole('TRUSTEDIDP_READ')")
-    TrustedIdp getTrustedIDP(@PathParam("realm") String realm);
-
-    @POST
-    @PreAuthorize("hasRole('TRUSTEDIDP_CREATE')")
-    Response addTrustedIDP(@Context UriInfo ui, TrustedIdp trustedIdp);
-    
-    @PUT
-    @Path("{realm}")
-    @PreAuthorize("hasRole('TRUSTEDIDP_UPDATE')")
-    Response updateTrustedIDP(@Context UriInfo ui, @PathParam("realm") String realm, TrustedIdp trustedIdp);
-    
-    @DELETE
-    @Path("{realm}")
-    @PreAuthorize("hasRole('TRUSTEDIDP_DELETE')")
-    Response deleteTrustedIDP(@PathParam("realm") String realm);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpServiceImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpServiceImpl.java
deleted file mode 100644
index e01c80b..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpServiceImpl.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.net.URI;
-import java.util.List;
-
-import javax.ws.rs.BadRequestException;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriBuilder;
-import javax.ws.rs.core.UriInfo;
-
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.service.TrustedIdpDAO;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-
-@Component
-public class TrustedIdpServiceImpl implements TrustedIdpService {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(TrustedIdpServiceImpl.class);
-
-    @Autowired
-    private TrustedIdpDAO trustedIdpDAO;
-    
-    
-    @Override
-    public Response updateTrustedIDP(UriInfo ui, String realm, TrustedIdp trustedIdp) {
-        if (!realm.equals(trustedIdp.getRealm().toString())) {
-            throw new BadRequestException();
-        }
-        trustedIdpDAO.updateTrustedIDP(realm, trustedIdp);
-        
-        return Response.noContent().build();
-    }
-    
-    @Override
-    public TrustedIdps getTrustedIDPs(int start, int size, UriInfo uriInfo) {
-        List<TrustedIdp> trustedIdps = trustedIdpDAO.getTrustedIDPs(start, size);
-        
-        TrustedIdps list = new TrustedIdps();
-        list.setTrustedIDPs(trustedIdps);
-        return list;
-    }
-    
-    @Override
-    public TrustedIdp getTrustedIDP(String realm) {
-        return this.trustedIdpDAO.getTrustedIDP(realm);
-    }
-    
-    @Override
-    public Response addTrustedIDP(UriInfo ui, TrustedIdp trustedIDP) {
-        LOG.info("add Trusted IDP config");
-        
-        TrustedIdp createdTrustedIdp = trustedIdpDAO.addTrustedIDP(trustedIDP);
-        
-        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
-        uriBuilder.path("{index}");
-        URI location = uriBuilder.build(createdTrustedIdp.getRealm());
-        return Response.created(location).entity(trustedIDP).build();
-    }
-
-    @Override
-    public Response deleteTrustedIDP(String realm) {
-        trustedIdpDAO.deleteTrustedIDP(realm);
-        
-        return Response.noContent().build();
-    }
-           
-    
-
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdps.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdps.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdps.java
deleted file mode 100644
index ea57acd..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdps.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.rest;
-
-import java.util.Collection;
-
-import javax.xml.bind.annotation.XmlElementRef;
-import javax.xml.bind.annotation.XmlRootElement;
-
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-
-@XmlRootElement(name = "trustedIdps", namespace = "http://org.apache.cxf.fediz/")
-public class TrustedIdps {
-
-    private Collection<TrustedIdp> trustedIDPs;
-
-    public TrustedIdps() {
-    }
-
-    public TrustedIdps(Collection<TrustedIdp> trustedIDPs) {
-        this.trustedIDPs = trustedIDPs;
-    }
-
-    @XmlElementRef
-    public Collection<TrustedIdp> getTrustedIDPs() {
-        return trustedIDPs;
-    }
-
-    public void setTrustedIDPs(Collection<TrustedIdp> trustedIDPs) {
-        this.trustedIDPs = trustedIDPs;
-    }
-}
\ No newline at end of file


[12/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimEntity.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimEntity.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimEntity.java
new file mode 100644
index 0000000..54ee1eb
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimEntity.java
@@ -0,0 +1,71 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.validation.constraints.NotNull;
+
+import org.apache.openjpa.persistence.jdbc.Index;
+
+@Entity(name = "Claim")
+public class ClaimEntity {
+    
+    @Id
+    private int id;
+    
+    @Index
+    @NotNull
+    private String claimType;
+    
+    private String displayName;
+    private String description;
+        
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    public void setClaimType(String claimType) {
+        this.claimType = claimType;
+    }
+    
+    public String getClaimType() {
+        return claimType;
+    }
+
+    public String getDisplayName() {
+        return displayName;
+    }
+
+    public void setDisplayName(String displayName) {
+        this.displayName = displayName;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ConfigServiceJPA.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ConfigServiceJPA.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ConfigServiceJPA.java
new file mode 100644
index 0000000..03f70b9
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ConfigServiceJPA.java
@@ -0,0 +1,96 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.rest.IdpService;
+import org.apache.cxf.fediz.service.idp.service.ConfigService;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+
+public class ConfigServiceJPA implements ConfigService {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ConfigServiceJPA.class);
+    
+    IdpService idpService;
+
+    @Override
+    public Idp getIDP(String realm) {
+        Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
+        try {
+            final Set<GrantedAuthority> authorities = new HashSet<>();
+            
+            if (realm == null || realm.length() == 0) {
+                authorities.add(new SimpleGrantedAuthority("IDP_LIST"));
+                UsernamePasswordAuthenticationToken technicalUser =
+                    new UsernamePasswordAuthenticationToken("IDP_TEST", "N.A", authorities);
+                
+                SecurityContextHolder.getContext().setAuthentication(technicalUser);
+                
+                return idpService.getIdps(0, 1, Arrays.asList("all"), null).getIdps().iterator().next();
+            } else {
+                authorities.add(new SimpleGrantedAuthority("IDP_READ"));
+                UsernamePasswordAuthenticationToken technicalUser =
+                    new UsernamePasswordAuthenticationToken("IDP_TEST", "N.A", authorities);
+                
+                SecurityContextHolder.getContext().setAuthentication(technicalUser);
+                
+                return idpService.getIdp(realm, Arrays.asList("all"));
+            }
+        } finally {
+            SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
+            LOG.info("Old Spring security context restored");
+        }
+    }
+
+    @Override
+    public void setIDP(Idp config) {
+        // TODO Auto-generated method stub
+        
+    }
+
+    @Override
+    public void removeIDP(String realm) {
+        // TODO Auto-generated method stub
+        
+    }
+
+    public IdpService getIdpService() {
+        return idpService;
+    }
+
+    public void setIdpService(IdpService idpService) {
+        this.idpService = idpService;
+    }
+    
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBInitApplicationListener.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBInitApplicationListener.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBInitApplicationListener.java
new file mode 100644
index 0000000..eebb99a
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBInitApplicationListener.java
@@ -0,0 +1,73 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.criteria.CriteriaBuilder;
+import javax.persistence.criteria.CriteriaQuery;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.ApplicationListener;
+import org.springframework.context.event.ContextRefreshedEvent;
+import org.springframework.stereotype.Component;
+
+@Component
+public class DBInitApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(DBInitApplicationListener.class);
+    
+    private EntityManager em;
+    
+    @Autowired
+    private List<DBLoader> dbloader;
+    
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+        
+    @Override
+    public void onApplicationEvent(ContextRefreshedEvent arg0) {
+        if (!isDBEmpty()) {
+            LOG.info("Inital DB already loaded");
+            return;
+        }
+        
+        LOG.debug("Loading inital DB data...");
+        for (DBLoader loader : this.dbloader) {
+            loader.load();
+            LOG.info("Inital DB data loaded for " + loader.getName());
+        }
+    }
+    
+    protected boolean isDBEmpty() {
+        CriteriaBuilder cb = em.getCriteriaBuilder();
+        CriteriaQuery<Long> cq = cb.createQuery(Long.class);
+        cq.select(cb.count(cq.from(ClaimEntity.class)));
+
+        return em.createQuery(cq).getSingleResult() == 0;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoader.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoader.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoader.java
new file mode 100644
index 0000000..c79a79b
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoader.java
@@ -0,0 +1,28 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+public interface DBLoader {
+
+    void load();
+    
+    String getName();
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderImpl.java
new file mode 100644
index 0000000..2c6ab15
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderImpl.java
@@ -0,0 +1,163 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+
+import org.apache.cxf.fediz.service.idp.domain.FederationType;
+import org.apache.cxf.fediz.service.idp.domain.TrustType;
+import org.apache.wss4j.dom.WSConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional
+//CHECKSTYLE:OFF
+public class DBLoaderImpl implements DBLoader {
+    
+    public static final String NAME = "DEMODBLOADER";
+    
+    private static final Logger LOG = LoggerFactory.getLogger(DBLoaderImpl.class);
+    
+    private EntityManager em;
+
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+    
+    @Override
+    public String getName() {
+        return NAME;
+    }
+    
+    @Override
+    public void load() {
+
+        try {
+            ClaimEntity claimEntity1 = new ClaimEntity();
+            claimEntity1.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname");
+            claimEntity1.setDisplayName("firstname");
+            claimEntity1.setDescription("Description for firstname");
+            em.persist(claimEntity1);
+    
+            ClaimEntity claimEntity2 = new ClaimEntity();
+            claimEntity2.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname");
+            claimEntity2.setDisplayName("lastname");
+            claimEntity2.setDescription("Description for lastname");
+            em.persist(claimEntity2);
+    
+            ClaimEntity claimEntity3 = new ClaimEntity();
+            claimEntity3.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress");
+            claimEntity3.setDisplayName("email");
+            claimEntity3.setDescription("Description for email");
+            em.persist(claimEntity3);
+    
+            ClaimEntity claimEntity4 = new ClaimEntity();
+            claimEntity4.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");
+            claimEntity4.setDisplayName("role");
+            claimEntity4.setDescription("Description for role");
+            em.persist(claimEntity4);
+            
+            
+            ApplicationEntity entity = new ApplicationEntity();
+            entity.setEncryptionCertificate("");
+            entity.setLifeTime(3600);
+            entity.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+            entity.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
+            entity.setRole("ApplicationServiceType");
+            entity.setServiceDescription("Web Application to illustrate WS-Federation");
+            entity.setServiceDisplayName("Fedizhelloworld");
+            entity.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
+            // must be persistet here already as the ApplicationClaimEntity requires the Application Id
+            em.persist(entity);
+            ApplicationClaimEntity ace1 = new ApplicationClaimEntity(entity, claimEntity1);
+            ace1.setOptional(true);
+            em.persist(ace1);
+            entity.getRequestedClaims().add(ace1);
+            ApplicationClaimEntity ace2 = new ApplicationClaimEntity(entity, claimEntity2);
+            ace2.setOptional(true);
+            em.persist(ace2);
+            entity.getRequestedClaims().add(ace2);
+            ApplicationClaimEntity ace3 = new ApplicationClaimEntity(entity, claimEntity3);
+            ace3.setOptional(true);
+            em.persist(ace3);
+            entity.getRequestedClaims().add(ace3);
+            ApplicationClaimEntity ace4 = new ApplicationClaimEntity(entity, claimEntity4);
+            ace4.setOptional(false);
+            em.persist(ace4);
+            entity.getRequestedClaims().add(ace4);
+            em.persist(entity);
+            
+            
+            TrustedIdpEntity entity3 = new TrustedIdpEntity();
+            entity3.setCacheTokens(true);
+            entity3.setCertificate("trusted cert");
+            entity3.setDescription("Realm B description");
+            entity3.setFederationType(FederationType.FEDERATE_IDENTITY);
+            entity3.setName("Realm B");
+            entity3.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+            entity3.setRealm("urn:org:apache:cxf:fediz:idp:realm-B");
+            entity3.setTrustType(TrustType.PEER_TRUST);
+            entity3.setUrl("https://localhost:12443/fediz-idp-remote/federation");
+            em.persist(entity3);
+            
+            IdpEntity idpEntity = new IdpEntity();
+            idpEntity.getApplications().add(entity);
+            idpEntity.getTrustedIdps().add(entity3);
+            idpEntity.setCertificate("stsKeystoreA.properties");
+            idpEntity.setCertificatePassword("realma");
+            idpEntity.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federation"));
+            idpEntity.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+            idpEntity.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMA"));
+            idpEntity.setServiceDisplayName("REALM A");
+            idpEntity.setServiceDescription("IDP of Realm A");
+            idpEntity.setUri("realma");
+            idpEntity.setProvideIdpList(true);
+            Map<String, String> authUris = new HashMap<>();
+            authUris.put("default", "/login/default");
+            idpEntity.setAuthenticationURIs(authUris);
+            List<String> protocols = new ArrayList<>();
+            protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
+            protocols.add("http://docs.oasis-open.org/ws-sx/ws-trust/200512");
+            idpEntity.setSupportedProtocols(protocols);
+            idpEntity.getClaimTypesOffered().add(claimEntity1);
+            idpEntity.getClaimTypesOffered().add(claimEntity2);
+            idpEntity.getClaimTypesOffered().add(claimEntity3);
+            idpEntity.getClaimTypesOffered().add(claimEntity4);
+            List<String> tokenTypes = new ArrayList<>();
+            tokenTypes.add(WSConstants.SAML2_NS);
+            tokenTypes.add(WSConstants.SAML_NS);
+            idpEntity.setTokenTypesOffered(tokenTypes);
+            idpEntity.setUseCurrentIdp(true);
+            em.persist(idpEntity);
+            
+            em.flush();
+        } catch (Exception ex) {
+            LOG.warn("Failed to initialize DB with data", ex);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderSpring.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderSpring.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderSpring.java
new file mode 100644
index 0000000..eb0fa40
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderSpring.java
@@ -0,0 +1,129 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.Collection;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.support.GenericXmlApplicationContext;
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional
+public class DBLoaderSpring implements DBLoader {
+    
+    public static final String NAME = "SPRINGDBLOADER";
+    
+    private static final Logger LOG = LoggerFactory.getLogger(DBLoaderSpring.class);
+    
+    private EntityManager em;
+    private String resource;
+
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+    
+    @Override
+    public String getName() {
+        return NAME;
+    }
+    
+    public String getResource() {
+        return resource;
+    }
+
+    public void setResource(String resource) {
+        this.resource = resource;
+    }
+
+    @Override
+    public void load() {
+
+        GenericXmlApplicationContext ctx = null;
+        try {
+            
+            if (resource == null) {
+                LOG.warn("Resource null for DBLoaderSpring");
+            }
+            
+            ctx = new GenericXmlApplicationContext();
+            ctx.load(resource);
+            ctx.refresh();
+            ctx.start();
+            
+            Collection<EntitlementEntity> entitlements = ctx.
+                getBeansOfType(EntitlementEntity.class, true, true).values();
+            for (EntitlementEntity e : entitlements) {
+                em.persist(e);
+            }
+            LOG.info(entitlements.size() + " EntitlementEntity added");
+            
+            Collection<RoleEntity> roles = ctx.
+                getBeansOfType(RoleEntity.class, true, true).values();
+            for (RoleEntity r : roles) {
+                em.persist(r);
+            }
+            LOG.info(roles.size() + " RoleEntity added");
+            
+            Collection<ClaimEntity> claims = ctx.getBeansOfType(ClaimEntity.class, true, true).values();
+            for (ClaimEntity c : claims) {
+                em.persist(c);
+            }
+            LOG.info(claims.size() + " ClaimEntity added");
+            
+            Collection<TrustedIdpEntity> trustedIdps = ctx.getBeansOfType(TrustedIdpEntity.class).values();
+            for (TrustedIdpEntity t : trustedIdps) {
+                em.persist(t);
+            }
+            LOG.info(trustedIdps.size() + " TrustedIdpEntity added");
+            
+            Collection<ApplicationEntity> applications = ctx.getBeansOfType(ApplicationEntity.class).values();
+            for (ApplicationEntity a : applications) {
+                em.persist(a);
+            }
+            LOG.info(applications.size() + " ApplicationEntity added");
+            
+            Collection<IdpEntity> idps = ctx.getBeansOfType(IdpEntity.class).values();
+            for (IdpEntity i : idps) {
+                em.persist(i);
+            }
+            LOG.info(idps.size() + " IdpEntity added");
+            
+            Collection<ApplicationClaimEntity> applicationClaims =
+                ctx.getBeansOfType(ApplicationClaimEntity.class).values();
+            for (ApplicationClaimEntity ac : applicationClaims) {
+                em.persist(ac);
+            }
+            LOG.info(applicationClaims.size() + " ApplicationClaimEntity added");
+            
+            em.flush();
+        } catch (Exception ex) {
+            LOG.warn("Failed to initialize DB with data", ex);
+        } finally {
+            if (ctx != null) {
+                ctx.close();
+            }
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPAImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPAImpl.java
new file mode 100644
index 0000000..5603e39
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPAImpl.java
@@ -0,0 +1,142 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+import org.apache.cxf.fediz.service.idp.service.EntitlementDAO;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+
+@Repository
+@Transactional
+public class EntitlementDAOJPAImpl implements EntitlementDAO {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(EntitlementDAOJPAImpl.class);
+
+    private EntityManager em;
+    
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+    
+    @Override
+    public List<Entitlement> getEntitlements(int start, int size) {
+        List<Entitlement> list = new ArrayList<>();
+        
+        Query query = null;
+        query = em.createQuery("select e from Entitlement e");
+        
+        //@SuppressWarnings("rawtypes")
+        List<?> entitlementEntities = query
+            .setFirstResult(start)
+            .setMaxResults(size)
+            .getResultList();
+
+        for (Object obj : entitlementEntities) {
+            EntitlementEntity entity = (EntitlementEntity) obj;
+            list.add(entity2domain(entity));
+        }
+        
+        return list;
+    }
+    
+    @Override
+    public Entitlement addEntitlement(Entitlement entitlement) {
+        EntitlementEntity entity = new EntitlementEntity();
+        domain2entity(entitlement, entity);
+        em.persist(entity);
+        
+        LOG.debug("Entitlement '{}' added", entitlement.getName());
+        return entity2domain(entity);
+    }
+
+    @Override
+    public Entitlement getEntitlement(String name) {
+        return entity2domain(getEntitlementEntity(name, em));
+    }
+
+    @Override
+    public void updateEntitlement(String name, Entitlement entitlement) {
+        Query query = null;
+        query = em.createQuery("select e from Entitlement e where e.name=:name");
+        query.setParameter("name", name);
+        
+        //@SuppressWarnings("rawtypes")
+        EntitlementEntity entitlementEntity = (EntitlementEntity)query.getSingleResult();
+        
+        domain2entity(entitlement, entitlementEntity);
+        
+        LOG.debug("Entitlement '{}' added", entitlement.getName());
+        em.persist(entitlementEntity);
+    }
+
+    @Override
+    public void deleteEntitlement(String name) {
+        Query query = null;
+        query = em.createQuery("select e from Entitlement e where e.name=:name");
+        query.setParameter("name", name);
+        
+        //@SuppressWarnings("rawtypes")
+        Object entitlementObj = query.getSingleResult();
+        em.remove(entitlementObj);
+        
+        LOG.debug("Entitlement '{}' deleted", name);
+    }
+    
+    static EntitlementEntity getEntitlementEntity(String name, EntityManager em) {
+        Query query = null;
+        query = em.createQuery("select e from Entitlement e where e.name=:name");
+        query.setParameter("name", name);
+        
+        //@SuppressWarnings("rawtypes")
+        return (EntitlementEntity)query.getSingleResult();
+    }
+    
+    public static void domain2entity(Entitlement entitlement, EntitlementEntity entity) {
+        //The ID must not be updated if the entity has got an id already (update case)
+        if (entitlement.getId() > 0) {
+            entity.setId(entitlement.getId());
+        }
+        //property 'internal' can't be changed, default is false
+        entity.setName(entitlement.getName());
+        entity.setDescription(entitlement.getDescription());
+    }
+    
+    public static Entitlement entity2domain(EntitlementEntity entity) {
+        Entitlement entitlement = new Entitlement();
+        entitlement.setId(entity.getId());
+        entitlement.setName(entity.getName());
+        entitlement.setDescription(entity.getDescription());
+        entitlement.setInternal(entity.isInternal());
+        return entitlement;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementEntity.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementEntity.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementEntity.java
new file mode 100644
index 0000000..aec6b91
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementEntity.java
@@ -0,0 +1,72 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+
+import org.apache.openjpa.persistence.jdbc.Index;
+
+@Entity(name = "Entitlement")
+public class EntitlementEntity {
+    
+    @Id
+    private int id;
+    
+    @Index
+    private String name;
+    
+    private String description;
+    
+    //Internal entities can't be updated, changed and deleted
+    //Default: false
+    private boolean internal;
+        
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public boolean isInternal() {
+        return internal;
+    }
+
+    public void setInternal(boolean internal) {
+        this.internal = internal;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPAImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPAImpl.java
new file mode 100644
index 0000000..5025a25
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPAImpl.java
@@ -0,0 +1,367 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityNotFoundException;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.service.IdpDAO;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+@Repository
+@Transactional
+public class IdpDAOJPAImpl implements IdpDAO {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(IdpDAOJPAImpl.class);
+
+    private EntityManager em;
+    
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+    
+    @Override
+    public List<Idp> getIdps(int start, int size, List<String> expandList) {
+        List<Idp> list = new ArrayList<>();
+        
+        Query query = null;
+        query = em.createQuery("select i from IDP i");
+        
+        /*List serviceEntities = query.setFirstResult(start)
+            .setMaxResults(size)
+            .getResultList();*/
+        
+        //@SuppressWarnings("rawtypes")
+        List<?> idpEntities = query
+            .setFirstResult(start)
+            .setMaxResults(size)
+            .getResultList();
+    
+        for (Object obj : idpEntities) {
+            IdpEntity entity = (IdpEntity) obj;
+            list.add(entity2domain(entity, expandList));
+        }
+        return list;
+    }
+    
+    @Override
+    public Idp getIdp(String realm, List<String> expandList) {
+        Query query = null;
+        query = em.createQuery("select i from IDP i where i.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        Object idpObj = query.getSingleResult();
+        return entity2domain((IdpEntity)idpObj, expandList);
+    }
+    
+    @Override
+    public Idp addIdp(Idp idp) {
+        IdpEntity entity = new IdpEntity();
+        domain2entity(idp, entity);
+        em.persist(entity);
+        
+        LOG.debug("IDP '{}' added", idp.getRealm());
+        return entity2domain(entity, Arrays.asList("all"));
+    }
+
+    @Override
+    public void updateIdp(String realm, Idp idp) {
+        Query query = null;
+        query = em.createQuery("select i from IDP i where i.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        IdpEntity idpEntity = (IdpEntity)query.getSingleResult();
+        
+        domain2entity(idp, idpEntity);
+        
+        em.persist(idpEntity);
+        
+        LOG.debug("IDP '{}' updated", idp.getRealm());
+    }
+
+    @Override
+    public void deleteIdp(String realm) {
+        Query query = null;
+        query = em.createQuery("select i from IDP i where i.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        Object idpObj = query.getSingleResult();
+        em.remove(idpObj);
+        
+        LOG.debug("IDP '{}' deleted", realm);
+    }
+    
+    @Override
+    public void addApplicationToIdp(Idp idp, Application application) {
+        IdpEntity idpEntity = null;
+        if (idp.getId() != 0) {
+            idpEntity = em.find(IdpEntity.class, idp.getId());
+        } else {
+            idpEntity = getIdpEntity(idp.getRealm(), em);
+        }
+        
+        ApplicationEntity applicationEntity = null;
+        if (application.getId() != 0) {
+            applicationEntity = em.find(ApplicationEntity.class, application.getId());
+        } else {
+            applicationEntity = ApplicationDAOJPAImpl.getApplicationEntity(application.getRealm(), em);
+        }
+        
+        idpEntity.getApplications().add(applicationEntity);
+        
+        LOG.debug("Application '{}' added to IDP '{}'", application.getRealm(), idp.getRealm());
+    }
+    
+    @Override
+    public void removeApplicationFromIdp(Idp idp, Application application) {
+        IdpEntity idpEntity = null;
+        if (idp.getId() != 0) {
+            idpEntity = em.find(IdpEntity.class, idp.getId());
+        } else {
+            idpEntity = getIdpEntity(idp.getRealm(), em);
+        }
+        
+        ApplicationEntity applicationEntity = null;
+        if (application.getId() != 0) {
+            applicationEntity = em.find(ApplicationEntity.class, application.getId());
+        } else {
+            applicationEntity = ApplicationDAOJPAImpl.getApplicationEntity(application.getRealm(), em);
+        }
+        
+        if (applicationEntity == null) {
+            throw new EntityNotFoundException("ApplicationEntity not found");
+        }
+        
+        if (!idpEntity.getApplications().remove(applicationEntity)) {
+            throw new EntityNotFoundException("ApplicationEntity not assigned to IdpEntity");
+        }
+                
+        LOG.debug("Application '{}' removed from IDP '{}'", application.getRealm(), idp.getRealm());
+    }
+    
+    @Override
+    public void addTrustedIdpToIdp(Idp idp, TrustedIdp trustedIdp) {
+        IdpEntity idpEntity = null;
+        if (idp.getId() != 0) {
+            idpEntity = em.find(IdpEntity.class, idp.getId());
+        } else {
+            idpEntity = getIdpEntity(idp.getRealm(), em);
+        }
+        
+        TrustedIdpEntity trustedIdpEntity = null;
+        if (trustedIdp.getId() != 0) {
+            trustedIdpEntity = em.find(TrustedIdpEntity.class, trustedIdp.getId());
+        } else {
+            trustedIdpEntity = TrustedIdpDAOJPAImpl.getTrustedIdpEntity(trustedIdp.getRealm(), em);
+        }
+        
+        idpEntity.getTrustedIdps().add(trustedIdpEntity);
+        
+        LOG.debug("Trusted IDP '{}' added to IDP '{}'", trustedIdp.getRealm(), idp.getRealm());
+    }
+    
+    @Override
+    public void removeTrustedIdpFromIdp(Idp idp, TrustedIdp trustedIdp) {
+        IdpEntity idpEntity = null;
+        if (idp.getId() != 0) {
+            idpEntity = em.find(IdpEntity.class, idp.getId());
+        } else {
+            idpEntity = getIdpEntity(idp.getRealm(), em);
+        }
+        
+        TrustedIdpEntity trustedIdpEntity = null;
+        if (trustedIdp.getId() != 0) {
+            trustedIdpEntity = em.find(TrustedIdpEntity.class, trustedIdp.getId());
+        } else {
+            trustedIdpEntity = TrustedIdpDAOJPAImpl.getTrustedIdpEntity(trustedIdp.getRealm(), em);
+        }
+        
+        idpEntity.getTrustedIdps().remove(trustedIdpEntity);
+        
+        LOG.debug("Trusted IDP '{}' removed from IDP '{}'", trustedIdp.getRealm(), idp.getRealm());
+    }
+        
+    @Override
+    public void addClaimToIdp(Idp idp, Claim claim) {
+        IdpEntity idpEntity = null;
+        if (idp.getId() != 0) {
+            idpEntity = em.find(IdpEntity.class, idp.getId());
+        } else {
+            idpEntity = getIdpEntity(idp.getRealm(), em);
+        }
+        
+        ClaimEntity claimEntity = null;
+        if (claim.getId() != 0) {
+            claimEntity = em.find(ClaimEntity.class, claim.getId());
+        } else {
+            claimEntity = ClaimDAOJPAImpl.getClaimEntity(claim.getClaimType().toString(), em);
+        }
+        
+        idpEntity.getClaimTypesOffered().add(claimEntity);
+        
+        LOG.debug("Claim '{}' added to IDP '{}'", claim.getClaimType(), idp.getRealm());
+    }
+    
+    @Override
+    public void removeClaimFromIdp(Idp idp, Claim claim) {
+        IdpEntity idpEntity = null;
+        if (idp.getId() != 0) {
+            idpEntity = em.find(IdpEntity.class, idp.getId());
+        } else {
+            idpEntity = getIdpEntity(idp.getRealm(), em);
+        }
+        if (idpEntity == null) {
+            throw new EntityNotFoundException("IdpEntity not found");
+        }
+        
+        ClaimEntity claimEntity = null;
+        if (claim.getId() != 0) {
+            claimEntity = em.find(ClaimEntity.class, claim.getId());
+        } else {
+            claimEntity = ClaimDAOJPAImpl.getClaimEntity(claim.getClaimType().toString(), em);
+        }
+        if (claimEntity == null) {
+            throw new EntityNotFoundException("ClaimEntity not found");
+        }
+        
+        if (!idpEntity.getClaimTypesOffered().remove(claimEntity)) {
+            throw new EntityNotFoundException("ClaimEntity not assigned to IdpEntity");
+        }
+        
+        LOG.debug("Claim '{}' removed from IDP '{}'", claim.getClaimType(), idp.getRealm());
+    }
+    
+    static IdpEntity getIdpEntity(String realm, EntityManager em) {
+        Query query = null;
+        query = em.createQuery("select i from IDP i where i.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        return (IdpEntity)query.getSingleResult();
+    }
+    
+    public static void domain2entity(Idp idp, IdpEntity entity) {
+        //The ID must not be updated if the entity has got an id already (update case)
+        if (idp.getId() > 0) {
+            entity.setId(idp.getId());
+        }
+        
+        entity.setCertificate(idp.getCertificate());
+        entity.setCertificatePassword(idp.getCertificatePassword());
+        entity.setRealm(idp.getRealm());
+        entity.setServiceDescription(idp.getServiceDescription());
+        entity.setServiceDisplayName(idp.getServiceDisplayName());
+        entity.setHrds(idp.getHrds());
+        entity.setIdpUrl(idp.getIdpUrl());
+        entity.setProvideIdpList(idp.isProvideIdpList());
+        entity.setStsUrl(idp.getStsUrl());
+        entity.setUri(idp.getUri());
+        entity.setUseCurrentIdp(idp.isUseCurrentIdp());
+        entity.setRpSingleSignOutConfirmation(idp.isRpSingleSignOutConfirmation());
+        entity.setRpSingleSignOutCleanupConfirmation(idp.isRpSingleSignOutCleanupConfirmation());
+        
+        entity.getAuthenticationURIs().clear();
+        for (Map.Entry<String, String> item : idp.getAuthenticationURIs().entrySet()) {
+            entity.getAuthenticationURIs().put(item.getKey(), item.getValue());
+        }
+        
+        entity.getTokenTypesOffered().clear();
+        for (String item : idp.getTokenTypesOffered()) {
+            entity.getTokenTypesOffered().add(item);
+        }
+        
+        entity.getSupportedProtocols().clear();
+        for (String item : idp.getSupportedProtocols()) {
+            entity.getSupportedProtocols().add(item);
+        }        
+    }
+
+    
+    public static Idp entity2domain(IdpEntity entity, List<String> expandList) {
+        Idp idp = new Idp();
+        idp.setId(entity.getId());
+        idp.setCertificate(entity.getCertificate());
+        idp.setCertificatePassword(entity.getCertificatePassword());
+        idp.setRealm(entity.getRealm());
+        idp.setServiceDescription(entity.getServiceDescription());
+        idp.setServiceDisplayName(entity.getServiceDisplayName());
+        idp.setHrds(entity.getHrds());
+        idp.setIdpUrl(entity.getIdpUrl());
+        idp.setProvideIdpList(entity.isProvideIdpList());
+        idp.setStsUrl(entity.getStsUrl());
+        idp.setUri(entity.getUri());
+        idp.setUseCurrentIdp(entity.isUseCurrentIdp());
+        idp.setRpSingleSignOutConfirmation(entity.isRpSingleSignOutConfirmation());
+        idp.setRpSingleSignOutCleanupConfirmation(entity.isRpSingleSignOutCleanupConfirmation());
+        
+        if (expandList != null && (expandList.contains("all") || expandList.contains("applications"))) {
+            for (ApplicationEntity item : entity.getApplications()) {
+                Application application = ApplicationDAOJPAImpl.entity2domain(item, expandList);
+                idp.getApplications().add(application);
+            }
+        }
+        
+        if (expandList != null && (expandList.contains("all") || expandList.contains("trusted-idps"))) {
+            for (TrustedIdpEntity item : entity.getTrustedIdps()) {
+                TrustedIdp trustedIdp = TrustedIdpDAOJPAImpl.entity2domain(item);
+                idp.getTrustedIdps().add(trustedIdp);
+            }
+        }
+        
+        for (Map.Entry<String, String> item : entity.getAuthenticationURIs().entrySet()) {
+            idp.getAuthenticationURIs().put(item.getKey(), item.getValue());
+        }
+        
+        for (String item : entity.getTokenTypesOffered()) {
+            idp.getTokenTypesOffered().add(item);
+        }
+        
+        for (String item : entity.getSupportedProtocols()) {
+            idp.getSupportedProtocols().add(item);
+        }
+        
+        if (expandList != null && (expandList.contains("all") || expandList.contains("claims"))) {
+            for (ClaimEntity item : entity.getClaimTypesOffered()) {
+                idp.getClaimTypesOffered().add(ClaimDAOJPAImpl.entity2domain(item));
+            }
+        }
+        
+        return idp;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpEntity.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpEntity.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpEntity.java
new file mode 100644
index 0000000..986b28d
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpEntity.java
@@ -0,0 +1,301 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.persistence.CascadeType;
+import javax.persistence.CollectionTable;
+import javax.persistence.Column;
+import javax.persistence.ElementCollection;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToMany;
+import javax.persistence.MapKeyColumn;
+import javax.validation.constraints.NotNull;
+
+import org.apache.openjpa.persistence.jdbc.Index;
+
+@Entity(name = "IDP")
+public class IdpEntity {
+
+    @Id
+    private int id;
+
+    // Unique
+    // fed:TargetScope
+    @Index
+    @NotNull
+    private String realm; // wtrealm, whr
+
+    // Unique
+    // https://<host>:<port>/fediz-idp/<IDP uri>/
+    private String uri;
+
+    // Home Realm Discovery Service
+    // Spring EL
+    private String hrds;
+
+    // if HRDS can't determine the home realm, should
+    // the list of trusted IDPs be shown to make a choice
+    private boolean provideIdpList;
+
+    // If HRDS can't discover a home realm and displaying IDP list is not
+    // enabled
+    // it falls back to current IDP if an authentication domain is configured
+    private boolean useCurrentIdp;
+
+    // Store certificate in DB or filesystem, provide options?
+    // md:KeyDescriptor, use="signing"
+    private String certificate;
+
+    // Password to read the private key to sign metadata document
+    private String certificatePassword;
+
+    // fed:SecurityTokenSerivceEndpoint
+    @NotNull
+    private URL stsUrl;
+
+    // fedl:PassiveRequestorEndpoint
+    // published hostname, port must be configured
+    @NotNull
+    private URL idpUrl;
+    
+    private boolean rpSingleSignOutConfirmation;
+
+    // RoleDescriptor protocolSupportEnumeration=
+    // "http://docs.oasis-open.org/wsfed/federation/200706"
+    // "http://docs.oasis-open.org/ws-sx/ws-trust/200512"
+    // Could be more in the future
+    
+    @ElementCollection
+    @CollectionTable(name = "idp_protocols")
+    @Column(name = "protocol")
+    private List<String> supportedProtocols = new ArrayList<>();
+
+    // list of RPs and RP-IDPs from whom we accept SignInResponse
+    // which includes RP IDPs
+    // key: wtrealm
+    @ManyToMany(cascade = CascadeType.ALL)
+    private List<ApplicationEntity> applications = new ArrayList<>();
+
+    // list of trusted IDP from whom we accept SignInResponse
+    // key: whr
+    @ManyToMany(cascade = CascadeType.ALL)
+    private List<TrustedIdpEntity> trustedIdps = new ArrayList<>();
+
+    // which URI to redirect for authentication
+    // fediz-idp/<IDP uri>/login/auth/<auth URI>
+    // wauth to auth URI mapping
+    @ElementCollection
+    @MapKeyColumn(name = "name")
+    @Column(name = "value")
+    @CollectionTable(name = "idp_auth_uris", joinColumns = @JoinColumn(name = "idp_id"))
+    private Map<String, String> authenticationURIs = new HashMap<>();
+
+    // required to create Federation Metadata document
+    // fed:TokenTypesOffered
+    //[TODO] Tokens could be managed independently, but no real impact in IDP at runtime
+    //       Only informational purpose for metadata document, but required in STS
+    @ElementCollection
+    @CollectionTable(name = "idp_tokentypes")
+    @Column(name = "tokentype")
+    private List<String> tokenTypesOffered = new ArrayList<>();
+
+    // fed:ClaimTypesOffered
+    @ManyToMany(cascade = CascadeType.ALL)
+    private List<ClaimEntity> claimTypesOffered = new ArrayList<>();
+
+    // ServiceDisplayName
+    @NotNull
+    private String serviceDisplayName;
+
+    // ServiceDescription
+    private String serviceDescription;
+    
+    private boolean rpSingleSignOutCleanupConfirmation;
+
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    public String getRealm() {
+        return realm;
+    }
+
+    public void setRealm(String realm) {
+        this.realm = realm;
+    }
+
+    public String getUri() {
+        return uri;
+    }
+
+    public void setUri(String uri) {
+        this.uri = uri;
+    }
+
+    public String getHrds() {
+        return hrds;
+    }
+
+    public void setHrds(String hrds) {
+        this.hrds = hrds;
+    }
+
+    public boolean isProvideIdpList() {
+        return provideIdpList;
+    }
+
+    public void setProvideIdpList(boolean provideIdpList) {
+        this.provideIdpList = provideIdpList;
+    }
+
+    public boolean isUseCurrentIdp() {
+        return useCurrentIdp;
+    }
+
+    public void setUseCurrentIdp(boolean useCurrentIdp) {
+        this.useCurrentIdp = useCurrentIdp;
+    }
+
+    public String getCertificate() {
+        return certificate;
+    }
+
+    public void setCertificate(String certificate) {
+        this.certificate = certificate;
+    }
+
+    public String getCertificatePassword() {
+        return certificatePassword;
+    }
+
+    public void setCertificatePassword(String password) {
+        this.certificatePassword = password;
+    }
+
+    public URL getStsUrl() {
+        return stsUrl;
+    }
+
+    public void setStsUrl(URL stsUrl) {
+        this.stsUrl = stsUrl;
+    }
+
+    public URL getIdpUrl() {
+        return idpUrl;
+    }
+
+    public void setIdpUrl(URL idpUrl) {
+        this.idpUrl = idpUrl;
+    }
+
+    public List<String> getSupportedProtocols() {
+        return supportedProtocols;
+    }
+
+    public void setSupportedProtocols(List<String> supportedProtocols) {
+        this.supportedProtocols = supportedProtocols;
+    }
+
+    public List<ApplicationEntity> getApplications() {
+        return applications;
+    }
+
+    public void setApplications(List<ApplicationEntity> applications) {
+        this.applications = applications;
+    }
+
+    public List<TrustedIdpEntity> getTrustedIdps() {
+        return trustedIdps;
+    }
+
+    public void setTrustedIdps(List<TrustedIdpEntity> trustedIdps) {
+        this.trustedIdps = trustedIdps;
+    }
+
+    public Map<String, String> getAuthenticationURIs() {
+        return authenticationURIs;
+    }
+
+    public void setAuthenticationURIs(Map<String, String> authenticationURIs) {
+        this.authenticationURIs = authenticationURIs;
+    }
+
+    public List<String> getTokenTypesOffered() {
+        return tokenTypesOffered;
+    }
+
+    public void setTokenTypesOffered(List<String> tokenTypesOffered) {
+        this.tokenTypesOffered = tokenTypesOffered;
+    }
+
+    public List<ClaimEntity> getClaimTypesOffered() {
+        return claimTypesOffered;
+    }
+
+    public void setClaimTypesOffered(List<ClaimEntity> claimTypesOffered) {
+        this.claimTypesOffered = claimTypesOffered;
+    }
+
+    public String getServiceDisplayName() {
+        return serviceDisplayName;
+    }
+
+    public void setServiceDisplayName(String serviceDisplayName) {
+        this.serviceDisplayName = serviceDisplayName;
+    }
+
+    public String getServiceDescription() {
+        return serviceDescription;
+    }
+
+    public void setServiceDescription(String serviceDescription) {
+        this.serviceDescription = serviceDescription;
+    }
+    
+    public boolean isRpSingleSignOutConfirmation() {
+        return rpSingleSignOutConfirmation;
+    }
+
+    public void setRpSingleSignOutConfirmation(boolean rpSingleSignOutConfirmation) {
+        this.rpSingleSignOutConfirmation = rpSingleSignOutConfirmation;
+    }
+
+    public boolean isRpSingleSignOutCleanupConfirmation() {
+        return rpSingleSignOutCleanupConfirmation;
+    }
+
+    public void setRpSingleSignOutCleanupConfirmation(boolean rpSingleSignOutCleanupConfirmation) {
+        this.rpSingleSignOutCleanupConfirmation = rpSingleSignOutCleanupConfirmation;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleDAOJPAImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleDAOJPAImpl.java
new file mode 100644
index 0000000..0493bf9
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleDAOJPAImpl.java
@@ -0,0 +1,206 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityNotFoundException;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+import org.apache.cxf.fediz.service.idp.domain.Role;
+import org.apache.cxf.fediz.service.idp.service.RoleDAO;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+@Repository
+@Transactional
+public class RoleDAOJPAImpl implements RoleDAO {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(RoleDAOJPAImpl.class);
+
+    private EntityManager em;
+    
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+    
+    @Override
+    public List<Role> getRoles(int start, int size, List<String> expandList) {
+        List<Role> list = new ArrayList<>();
+        
+        Query query = null;
+        query = em.createQuery("select r from Role r");
+        
+        //@SuppressWarnings("rawtypes")
+        List<?> roleEntities = query
+            .setFirstResult(start)
+            .setMaxResults(size)
+            .getResultList();
+    
+        for (Object obj : roleEntities) {
+            RoleEntity entity = (RoleEntity) obj;
+            list.add(entity2domain(entity, expandList));
+        }
+        return list;
+    }
+    
+    @Override
+    public Role getRole(String name, List<String> expandList) {
+        Query query = null;
+        query = em.createQuery("select r from Role r where r.name=:name");
+        query.setParameter("name", name);
+        
+        //@SuppressWarnings("rawtypes")
+        Object roleObj = query.getSingleResult();
+        return entity2domain((RoleEntity)roleObj, expandList);
+    }
+    
+    @Override
+    public Role addRole(Role role) {
+        RoleEntity entity = new RoleEntity();
+        domain2entity(role, entity);
+        em.persist(entity);
+        
+        LOG.debug("Role '{}' added", role.getName());
+        return entity2domain(entity, Arrays.asList("all"));
+    }
+
+    @Override
+    public void updateRole(String name, Role role) {
+        Query query = null;
+        query = em.createQuery("select r from Role r where r.name=:name");
+        query.setParameter("name", name);
+        
+        //@SuppressWarnings("rawtypes")
+        RoleEntity roleEntity = (RoleEntity)query.getSingleResult();
+        
+        domain2entity(role, roleEntity);
+        
+        em.persist(roleEntity);
+        
+        LOG.debug("Role '{}' updated", role.getName());
+    }
+
+    @Override
+    public void deleteRole(String name) {
+        Query query = null;
+        query = em.createQuery("select r from Role r where r.name=:name");
+        query.setParameter("name", name);
+        
+        //@SuppressWarnings("rawtypes")
+        Object roleObj = query.getSingleResult();
+        em.remove(roleObj);
+        
+        LOG.debug("Role '{}' deleted", name);
+    }
+    
+    @Override
+    public void addEntitlementToRole(Role role, Entitlement entitlement) {
+        RoleEntity roleEntity = null;
+        if (role.getId() != 0) {
+            roleEntity = em.find(RoleEntity.class, role.getId());
+        } else {
+            roleEntity = getRoleEntity(role.getName(), em);
+        }
+        
+        EntitlementEntity entitlementEntity = null;
+        if (entitlement.getId() != 0) {
+            entitlementEntity = em.find(EntitlementEntity.class, entitlement.getId());
+        } else {
+            entitlementEntity = EntitlementDAOJPAImpl.getEntitlementEntity(entitlement.getName(), em);
+        }
+        
+        roleEntity.getEntitlements().add(entitlementEntity);
+        
+        LOG.debug("Entitlement '{}' added to Role '{}'", entitlement.getName(), role.getName());
+    }
+    
+    @Override
+    public void removeEntitlementFromRole(Role role, Entitlement entitlement) {
+        RoleEntity roleEntity = null;
+        if (role.getId() != 0) {
+            roleEntity = em.find(RoleEntity.class, role.getId());
+        } else {
+            roleEntity = getRoleEntity(role.getName(), em);
+        }
+        
+        EntitlementEntity entitlementEntity = null;
+        if (entitlement.getId() != 0) {
+            entitlementEntity = em.find(EntitlementEntity.class, entitlement.getId());
+        } else {
+            entitlementEntity = EntitlementDAOJPAImpl.getEntitlementEntity(entitlement.getName(), em);
+        }
+        
+        if (entitlementEntity == null) {
+            throw new EntityNotFoundException("EntitlementEntity not found");
+        }
+        
+        if (!roleEntity.getEntitlements().remove(entitlementEntity)) {
+            throw new EntityNotFoundException("EntitlementEntity not assigned to RoleEntity");
+        }
+        
+        LOG.debug("Entitlement '{}' removed from Role '{}'", entitlement.getName(), role.getName());
+    }
+    
+    static RoleEntity getRoleEntity(String realm, EntityManager em) {
+        Query query = null;
+        query = em.createQuery("select i from IDP i where i.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        return (RoleEntity)query.getSingleResult();
+    }
+    
+    public static void domain2entity(Role role, RoleEntity entity) {
+        //The ID must not be updated if the entity has got an id already (update case)
+        if (role.getId() > 0) {
+            entity.setId(role.getId());
+        }
+        
+        entity.setName(role.getName());
+        entity.setDescription(role.getDescription());
+    }
+
+    
+    public static Role entity2domain(RoleEntity entity, List<String> expandList) {
+        Role role = new Role();
+        role.setId(entity.getId());
+        role.setName(entity.getName());
+        role.setDescription(entity.getDescription());
+        
+        if (expandList != null && (expandList.contains("all") || expandList.contains("entitlements"))) {
+            for (EntitlementEntity item : entity.getEntitlements()) {
+                Entitlement entitlement = EntitlementDAOJPAImpl.entity2domain(item);
+                role.getEntitlements().add(entitlement);
+            }
+        }
+        
+        return role;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleEntity.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleEntity.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleEntity.java
new file mode 100644
index 0000000..3b515c3
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/RoleEntity.java
@@ -0,0 +1,77 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.ManyToMany;
+
+import org.apache.openjpa.persistence.jdbc.Index;
+
+@Entity(name = "Role")
+public class RoleEntity {
+    
+    @Id
+    private int id;
+    
+    @Index
+    private String name;
+    
+    private String description;
+    
+    @ManyToMany(cascade = CascadeType.ALL)
+    private List<EntitlementEntity> entitlements = new ArrayList<>();
+    
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+    
+    public List<EntitlementEntity> getEntitlements() {
+        return entitlements;
+    }
+
+    public void setEntitlements(List<EntitlementEntity> entitlements) {
+        this.entitlements = entitlements;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPAImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPAImpl.java
new file mode 100644
index 0000000..16d05f1
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPAImpl.java
@@ -0,0 +1,154 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.service.TrustedIdpDAO;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+
+@Transactional
+@Repository
+public class TrustedIdpDAOJPAImpl implements TrustedIdpDAO {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpDAOJPAImpl.class);
+
+    private EntityManager em;
+    
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+    
+    @Override
+    public List<TrustedIdp> getTrustedIDPs(int start, int size) {
+        List<TrustedIdp> list = new ArrayList<>();
+        
+        Query query = null;
+        query = em.createQuery("select t from TrustedIDP t");
+        
+        List<?> idpEntities = query
+            .setFirstResult(start)
+            .setMaxResults(size)
+            .getResultList();
+
+        for (Object obj : idpEntities) {
+            TrustedIdpEntity entity = (TrustedIdpEntity) obj;
+            list.add(entity2domain(entity));
+        }
+        
+        return list;
+    }
+
+    @Override
+    public TrustedIdp getTrustedIDP(String realm) {
+        return entity2domain(getTrustedIdpEntity(realm, em));
+    }
+    
+    @Override
+    public TrustedIdp addTrustedIDP(TrustedIdp trustedIdp) {
+        TrustedIdpEntity entity = new TrustedIdpEntity();
+        domain2entity(trustedIdp, entity);
+        em.persist(entity);
+        
+        LOG.debug("Trusted IDP '" + trustedIdp.getRealm() + "' added");
+        return entity2domain(entity);
+    }
+    
+    @Override
+    public void updateTrustedIDP(String realm, TrustedIdp trustedIdp) {
+        TrustedIdpEntity trustedIdpEntity = getTrustedIdpEntity(realm, em);
+        
+        domain2entity(trustedIdp, trustedIdpEntity);
+        em.persist(trustedIdpEntity);
+        
+        LOG.debug("Trusted IDP '" + trustedIdp.getRealm() + "' updated");
+    }
+
+    @Override
+    public void deleteTrustedIDP(String realm) {
+        Query query = null;
+        query = em.createQuery("select t from TrustedIDP t where t.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        Object trustedIdpObj = query.getSingleResult();
+        em.remove(trustedIdpObj);
+        
+        LOG.debug("Trusted IDP '" + realm + "' deleted");
+    }
+    
+    static TrustedIdpEntity getTrustedIdpEntity(String realm, EntityManager em) {
+        Query query = null;
+        query = em.createQuery("select t from TrustedIDP t where t.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        return (TrustedIdpEntity)query.getSingleResult();
+    }
+    
+    public static void domain2entity(TrustedIdp trustedIDP, TrustedIdpEntity entity) {
+        //The ID must not be updated if the entity has got an id already (update case)
+        if (trustedIDP.getId() > 0) {
+            entity.setId(trustedIDP.getId());
+        }
+        entity.setCacheTokens(trustedIDP.isCacheTokens());
+        entity.setCertificate(trustedIDP.getCertificate());
+        entity.setDescription(trustedIDP.getDescription());
+        entity.setFederationType(trustedIDP.getFederationType());
+        entity.setLogo(trustedIDP.getLogo());
+        entity.setName(trustedIDP.getName());
+        entity.setProtocol(trustedIDP.getProtocol());
+        entity.setRealm(trustedIDP.getRealm());
+        entity.setIssuer(trustedIDP.getIssuer());
+        entity.setTrustType(trustedIDP.getTrustType());
+        entity.setUrl(trustedIDP.getUrl());
+        entity.setParameters(trustedIDP.getParameters());
+    }
+    
+    public static TrustedIdp entity2domain(TrustedIdpEntity entity) {
+        TrustedIdp trustedIDP = new TrustedIdp();
+        trustedIDP.setId(entity.getId());
+        trustedIDP.setCacheTokens(entity.isCacheTokens());
+        trustedIDP.setCertificate(entity.getCertificate());
+        trustedIDP.setDescription(entity.getDescription());
+        trustedIDP.setFederationType(entity.getFederationType());
+        trustedIDP.setLogo(entity.getLogo());
+        trustedIDP.setName(entity.getName());
+        trustedIDP.setProtocol(entity.getProtocol());
+        trustedIDP.setRealm(entity.getRealm());
+        trustedIDP.setIssuer(entity.getIssuer());
+        trustedIDP.setTrustType(entity.getTrustType());
+        trustedIDP.setUrl(entity.getUrl());
+        trustedIDP.setParameters(entity.getParameters());
+        return trustedIDP;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpEntity.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpEntity.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpEntity.java
new file mode 100644
index 0000000..a4c6592
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpEntity.java
@@ -0,0 +1,201 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.persistence.CollectionTable;
+import javax.persistence.Column;
+import javax.persistence.ElementCollection;
+import javax.persistence.Entity;
+import javax.persistence.EnumType;
+import javax.persistence.Enumerated;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.MapKeyColumn;
+import javax.validation.constraints.NotNull;
+
+import org.apache.cxf.fediz.service.idp.domain.FederationType;
+import org.apache.cxf.fediz.service.idp.domain.TrustType;
+import org.apache.openjpa.persistence.jdbc.Index;
+
+
+@Entity(name = "TrustedIDP")
+public class TrustedIdpEntity {
+
+    @Id
+    private int id;
+
+    //@Column(name = "REALM", nullable = true, length = FIELD_LENGTH)
+    @Index
+    @NotNull
+    private String realm;  //wtrealm, whr
+    
+    private String issuer;  //Validation of issuer name in SAMLResponse
+
+    // Should tokens be cached from trusted IDPs
+    // to avoid redirection to the trusted IDP again for next SignIn request
+    private boolean cacheTokens;
+    
+    //Could be read from Metadata, PassiveRequestorEndpoint
+    @NotNull
+    private String url;
+    
+    //Could be read from Metadata, md:KeyDescriptor, use="signing"
+    //Store certificate in DB or filesystem, provide options?
+    private String certificate;
+    
+    //Direct trust (signing cert imported), Indirect trust (CA certs imported, subject configured)
+    @Enumerated(EnumType.STRING)
+    private TrustType trustType;
+    
+    //Could be read from Metadata, RoleDescriptor protocolSupportEnumeration=
+    // "http://docs.oasis-open.org/wsfed/federation/200706"
+    // Metadata could provide more than one but one must be chosen
+    @TrustedIdpProtocolSupported
+    private String protocol;
+    
+    //FederateIdentity, FederateClaims
+    @Enumerated(EnumType.STRING)
+    private FederationType federationType;
+    
+    //optional (to provide a list of IDPs)
+    @NotNull
+    private String name;
+    
+    //optional (to provide a list of IDPs)
+    private String description;
+    
+    //optional (to provide a list of IDPs)
+    private String logo;
+    
+    // Additional (possibly protocol specific parameters)
+    @ElementCollection
+    @MapKeyColumn(name = "name")
+    @Column(name = "value")
+    @CollectionTable(name = "trusted_idp_parameters", joinColumns = @JoinColumn(name = "trusted_idp_id"))
+    private Map<String, String> parameters = new HashMap<>();
+    
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public String getIssuer() {
+        return issuer;
+    }
+
+    public void setIssuer(String issuer) {
+        this.issuer = issuer;
+    }
+    
+    public String getRealm() {
+        return realm;
+    }
+
+    public void setRealm(String realm) {
+        this.realm = realm;
+    }
+
+    public boolean isCacheTokens() {
+        return cacheTokens;
+    }
+
+    public void setCacheTokens(boolean cacheTokens) {
+        this.cacheTokens = cacheTokens;
+    }
+
+    public String getUrl() {
+        return url;
+    }
+
+    public void setUrl(String url) {
+        this.url = url;
+    }
+
+    public String getCertificate() {
+        return certificate;
+    }
+
+    public void setCertificate(String certificate) {
+        this.certificate = certificate;
+    }
+
+    public String getProtocol() {
+        return protocol;
+    }
+
+    public void setProtocol(String protocol) {
+        this.protocol = protocol;
+    }
+
+    public FederationType getFederationType() {
+        return federationType;
+    }
+
+    public void setFederationType(FederationType federationType) {
+        this.federationType = federationType;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public String getLogo() {
+        return logo;
+    }
+
+    public void setLogo(String logo) {
+        this.logo = logo;
+    }
+
+    public TrustType getTrustType() {
+        return trustType;
+    }
+
+    public void setTrustType(TrustType trustType) {
+        this.trustType = trustType;
+    }
+
+    public Map<String, String> getParameters() {
+        return parameters;
+    }
+
+    public void setParameters(Map<String, String> parameters) {
+        this.parameters = parameters;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupportValidator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupportValidator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupportValidator.java
new file mode 100644
index 0000000..75ac2ec
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupportValidator.java
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.List;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+import org.apache.cxf.fediz.service.idp.protocols.ProtocolController;
+import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Component;
+
+/**
+ * Validate that the protocol is a valid IdP protocol
+ */
+@Component
+public class TrustedIdpProtocolSupportValidator implements ConstraintValidator<TrustedIdpProtocolSupported, String> {
+
+    @Autowired
+    // Qualifier workaround. See http://www.jayway.com/2013/11/03/spring-and-autowiring-of-generic-types/
+    @Qualifier("trustedIdpProtocolControllerImpl")
+    private ProtocolController<TrustedIdpProtocolHandler> trustedIdpProtocolHandlers;
+    
+    @Override
+    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
+        
+        List<String> protocols = trustedIdpProtocolHandlers.getProtocols();
+        return protocols.contains(object);
+    }
+
+    @Override
+    public void initialize(TrustedIdpProtocolSupported constraintAnnotation) {
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupported.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupported.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupported.java
new file mode 100644
index 0000000..9c32af3
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpProtocolSupported.java
@@ -0,0 +1,47 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import javax.validation.Constraint;
+import javax.validation.Payload;
+
+@Target({ METHOD, FIELD, ANNOTATION_TYPE })
+@Retention(RUNTIME)
+@Constraint(validatedBy = TrustedIdpProtocolSupportValidator.class)
+@Documented
+public @interface TrustedIdpProtocolSupported {
+
+    String message() default "{Protocol not supported}";
+
+    Class<?>[] groups() default { };
+
+    Class<? extends Payload>[] payload() default { };
+
+}
\ No newline at end of file


[16/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
new file mode 100644
index 0000000..742797d
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans.samlsso;
+
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.samlsso.SAML2CallbackHandler;
+import org.apache.cxf.fediz.service.idp.samlsso.SAML2PResponseComponentBuilder;
+import org.apache.cxf.fediz.service.idp.samlsso.SAMLAuthnRequest;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.helpers.DOMUtils;
+import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.saml.OpenSAMLUtil;
+import org.apache.wss4j.common.saml.SAMLCallback;
+import org.apache.wss4j.common.saml.SAMLUtil;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.wss4j.common.saml.bean.AudienceRestrictionBean;
+import org.apache.wss4j.common.saml.bean.ConditionsBean;
+import org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.apache.wss4j.dom.WSConstants;
+import org.joda.time.DateTime;
+import org.opensaml.saml.saml2.core.Assertion;
+import org.opensaml.saml.saml2.core.NameID;
+import org.opensaml.saml.saml2.core.Response;
+import org.opensaml.saml.saml2.core.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Insert the SAML Token received from the STS into a SAML Response
+ */
+@Component
+public class SamlResponseCreator {
+
+    private static final Logger LOG = LoggerFactory.getLogger(SamlResponseCreator.class);
+    private boolean supportDeflateEncoding;
+
+    public String createSAMLResponse(RequestContext context, Idp idp, Element rpToken,
+                                     String consumerURL, String requestId, String requestIssuer) 
+                                         throws ProcessingException {
+        List<Element> samlTokens = 
+            DOMUtils.findAllElementsByTagNameNS(rpToken, WSConstants.SAML2_NS, "Assertion");
+        if (samlTokens.isEmpty() || samlTokens.size() != 1) {
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+        
+        try {
+            SamlAssertionWrapper wrapper = new SamlAssertionWrapper(samlTokens.get(0));
+            if (wrapper.getSaml2() == null) {
+                throw new ProcessingException(TYPE.BAD_REQUEST);
+            }
+            
+            String remoteAddr = WebUtils.getHttpServletRequest(context).getRemoteAddr();
+            Assertion saml2Assertion = 
+                createSAML2Assertion(context, idp, wrapper, requestId, requestIssuer, 
+                                     remoteAddr, consumerURL);
+            
+            Element response = createResponse(idp, requestId, saml2Assertion);
+            return encodeResponse(response);
+        } catch (Exception ex) {
+            LOG.warn("Error marshalling SAML Token: {}", ex.getMessage());
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+    }
+    
+    private Assertion createSAML2Assertion(RequestContext context, Idp idp, SamlAssertionWrapper receivedToken,
+                                           String requestID, String requestIssuer, 
+                                           String remoteAddr, String racs) throws Exception {
+        // Create an AuthenticationAssertion
+        SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
+        callbackHandler.setIssuer(idp.getRealm());
+        callbackHandler.setSubject(receivedToken.getSaml2().getSubject());
+        
+        // Test Subject against received Subject (if applicable)
+        SAMLAuthnRequest authnRequest = 
+            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
+        if (authnRequest.getSubjectNameId() != null && receivedToken.getSaml2().getSubject().getNameID() != null) {
+            NameID issuedNameId = receivedToken.getSaml2().getSubject().getNameID();
+            if (!authnRequest.getSubjectNameId().equals(issuedNameId.getValue())) {
+                LOG.debug("Received NameID value of {} does not match issued value {}",
+                          authnRequest.getSubjectNameId(), issuedNameId.getValue());
+                throw new ProcessingException(ProcessingException.TYPE.INVALID_REQUEST);
+            }
+        }
+        
+        // Subject Confirmation Data
+        SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
+        subjectConfirmationData.setAddress(remoteAddr);
+        subjectConfirmationData.setInResponseTo(requestID);
+        subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
+        subjectConfirmationData.setRecipient(racs);
+        callbackHandler.setSubjectConfirmationData(subjectConfirmationData);
+        
+        // Audience Restriction
+        ConditionsBean conditions = new ConditionsBean();
+        conditions.setTokenPeriodMinutes(5);
+        
+        AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
+        audienceRestriction.setAudienceURIs(Collections.singletonList(requestIssuer));
+        conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
+        callbackHandler.setConditions(conditions);
+        
+        // Attributes
+        callbackHandler.setAttributeStatements(receivedToken.getSaml2().getAttributeStatements());
+        
+        SAMLCallback samlCallback = new SAMLCallback();
+        SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
+        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
+        
+        Crypto issuerCrypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
+        assertion.signAssertion(issuerCrypto.getDefaultX509Identifier(), idp.getCertificatePassword(), 
+                                issuerCrypto, false);
+        
+        return assertion.getSaml2();
+    }
+    
+    protected Element createResponse(Idp idp, String requestID, Assertion assertion) throws Exception {
+        Document doc = DOMUtils.newDocument();
+        
+        Status status = 
+            SAML2PResponseComponentBuilder.createStatus(
+                "urn:oasis:names:tc:SAML:2.0:status:Success", null
+            );
+        Response response = 
+            SAML2PResponseComponentBuilder.createSAMLResponse(requestID, idp.getRealm(), status);
+        
+        response.getAssertions().add(assertion);
+        
+        Element policyElement = OpenSAMLUtil.toDom(response, doc);
+        doc.appendChild(policyElement);
+        
+        return policyElement;
+    }
+
+    protected String encodeResponse(Element response) throws IOException {
+        String responseMessage = DOM2Writer.nodeToString(response);
+        LOG.debug("Created Response: {}", responseMessage);
+
+        if (supportDeflateEncoding) {
+            DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
+            byte[] deflatedBytes = encoder.deflateToken(responseMessage.getBytes("UTF-8"));
+
+            return Base64Utility.encode(deflatedBytes);
+        }
+        
+        return Base64Utility.encode(responseMessage.getBytes());
+    }
+    
+    public boolean isSupportDeflateEncoding() {
+        return supportDeflateEncoding;
+    }
+
+    public void setSupportDeflateEncoding(boolean supportDeflateEncoding) {
+        this.supportDeflateEncoding = supportDeflateEncoding;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseErrorCreator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseErrorCreator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseErrorCreator.java
new file mode 100644
index 0000000..ce257e0
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseErrorCreator.java
@@ -0,0 +1,97 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans.samlsso;
+
+import java.io.IOException;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.samlsso.SAML2PResponseComponentBuilder;
+import org.apache.cxf.helpers.DOMUtils;
+import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
+import org.apache.wss4j.common.saml.OpenSAMLUtil;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.opensaml.saml.saml2.core.Response;
+import org.opensaml.saml.saml2.core.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Create a SAML Error Response
+ */
+@Component
+public class SamlResponseErrorCreator {
+
+    private static final Logger LOG = LoggerFactory.getLogger(SamlResponseErrorCreator.class);
+    private boolean supportDeflateEncoding;
+
+    public String createSAMLResponse(RequestContext context, boolean requestor,
+                                     Idp idp, String requestID) throws ProcessingException { 
+        Document doc = DOMUtils.newDocument();
+        
+        String statusValue = "urn:oasis:names:tc:SAML:2.0:status:Responder";
+        if (requestor) {
+            statusValue = "urn:oasis:names:tc:SAML:2.0:status:Requester";
+        }
+        Status status = 
+            SAML2PResponseComponentBuilder.createStatus(statusValue, null);
+        Response response = 
+            SAML2PResponseComponentBuilder.createSAMLResponse(requestID, idp.getRealm(), status);
+        
+        try {
+            Element policyElement = OpenSAMLUtil.toDom(response, doc);
+            doc.appendChild(policyElement);
+            
+            Element responseElement = policyElement;
+            return encodeResponse(responseElement);
+        } catch (Exception e) {
+            LOG.warn("Error marshalling SAML Token: {}", e.getMessage());
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+    }
+
+    protected String encodeResponse(Element response) throws IOException {
+        String responseMessage = DOM2Writer.nodeToString(response);
+        LOG.debug("Created Response: {}", responseMessage);
+
+        if (supportDeflateEncoding) {
+            DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
+            byte[] deflatedBytes = encoder.deflateToken(responseMessage.getBytes("UTF-8"));
+
+            return Base64Utility.encode(deflatedBytes);
+        }
+        
+        return Base64Utility.encode(responseMessage.getBytes());
+    }
+    
+    public boolean isSupportDeflateEncoding() {
+        return supportDeflateEncoding;
+    }
+
+    public void setSupportDeflateEncoding(boolean supportDeflateEncoding) {
+        this.supportDeflateEncoding = supportDeflateEncoding;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/wsfed/WfreshParser.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/wsfed/WfreshParser.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/wsfed/WfreshParser.java
new file mode 100644
index 0000000..148d24b
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/wsfed/WfreshParser.java
@@ -0,0 +1,84 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans.wsfed;
+
+import java.util.Date;
+
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * This class is responsible to parse the 'wfresh' parameter 
+ */
+@Component
+public class WfreshParser {
+
+    private static final Logger LOG = LoggerFactory.getLogger(WfreshParser.class);
+
+    public boolean authenticationRequired(String wfresh, String whr, RequestContext context)
+        throws Exception {
+        
+        SecurityToken idpToken = 
+            (SecurityToken) WebUtils.getAttributeFromExternalContext(context, whr);
+        if (idpToken == null) {
+            return true;
+        }
+        
+        if (wfresh == null || wfresh.trim().isEmpty()) {
+            return false;
+        }
+
+        long ttl;
+        try {
+            ttl = Long.parseLong(wfresh.trim());
+        } catch (Exception e) {
+            LOG.info("wfresh value '" + wfresh + "' is invalid.");
+            return false;
+        }
+        if (ttl == 0) {
+            return true;
+        }
+        
+        long ttlMs = ttl * 60L * 1000L;
+        if (ttlMs > 0) {
+            Date createdDate = idpToken.getCreated();
+            if (createdDate != null) {
+                Date expiryDate = new Date();
+                expiryDate.setTime(createdDate.getTime() + ttlMs);
+                if (expiryDate.before(new Date())) {
+                    LOG.info("[IDP_TOKEN="
+                            + idpToken.getId()
+                            + "] is valid but relying party requested new authentication caused by wfresh="
+                            + wfresh + " outdated.");
+                    return true;
+                }
+            } else {
+                LOG.info("token creation date not set. Unable to check wfresh is outdated.");
+            }
+        } else {
+            LOG.info("ttl value '" + ttl + "' is negative or is too large.");
+        }
+        return false;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Application.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Application.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Application.java
new file mode 100644
index 0000000..814e342
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Application.java
@@ -0,0 +1,242 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.domain;
+
+import java.io.Serializable;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+@XmlRootElement(name = "application", namespace = "http://org.apache.cxf.fediz/")
+@XmlType(propOrder = {"realm", "role", "serviceDisplayName", "serviceDescription", "protocol",
+                      "tokenType", "lifeTime", "encryptionCertificate", "requestedClaims",
+                      "policyNamespace", "passiveRequestorEndpoint", "passiveRequestorEndpointConstraint", "id",
+                      "validatingCertificate", "enableAppliesTo"})
+public class Application implements Serializable {
+        
+    private static final long serialVersionUID = 5644327504861846964L;
+
+    
+    
+    protected int id;
+    
+            
+    //Could be imported from Metadata document or manually filled
+    
+    //@Column(name = "REALM", nullable = true, length = FIELD_LENGTH)
+    protected String realm;  //wtrealm, whr
+
+    //Could be read from Metadata, RoleDescriptor protocolSupportEnumeration=
+    // "http://docs.oasis-open.org/wsfed/federation/200706"
+    // Metadata could provide more than one but one must be chosen
+    protected String protocol;
+ 
+    // Public key only
+    // Could be read from Metadata, md:KeyDescriptor, use="encryption"
+    protected String encryptionCertificate;
+    
+    // Certificate for Signature verification
+    protected String validatingCertificate;
+    
+    // Could be read from Metadata, fed:ClaimTypesRequested
+    protected List<RequestClaim> requestedClaims = new ArrayList<>();
+    
+    //Could be read from Metadata, ServiceDisplayName
+    //usage for list of application where user is logged in
+    protected String serviceDisplayName;
+    
+    //Could be read from Metadata, ServiceDescription
+    //usage for list of application where user is logged in
+    protected String serviceDescription;
+    
+    //Could be read from Metadata, RoleDescriptor
+    //fed:ApplicationServiceType, fed:SecurityTokenServiceType
+    protected String role;
+        
+    // Not in Metadata, configured in IDP or passed in wreq parameter
+    protected String tokenType;
+    
+    // Not in Metadata, configured in IDP or passed in wreq parameter
+    protected int lifeTime;
+    
+    // WS-Policy Namespace for AppliesTo element
+    protected String policyNamespace;
+    
+    // Request audience restriction in token for this application (default is true)
+    private boolean enableAppliesTo = true;
+    
+    private URI href;
+    
+    //Could be read from Metadata, PassiveRequestorEndpoint
+    //fed:ApplicationServiceType, fed:SecurityTokenServiceType
+    private String passiveRequestorEndpoint;
+    
+    // A regular expression constraint on the passiveRequestorEndpoint
+    private String passiveRequestorEndpointConstraint;
+    private Pattern compiledPassiveRequestorEndpointConstraint;
+    
+    
+    @XmlAttribute
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    @XmlAttribute
+    public URI getHref() {
+        return href;
+    }
+
+    public void setHref(URI href) {
+        this.href = href;
+    }
+
+    public String getRealm() {
+        return realm;
+    }
+
+    public void setRealm(String realm) {
+        this.realm = realm;
+    }
+
+    public String getProtocol() {
+        return protocol;
+    }
+
+    public void setProtocol(String protocol) {
+        this.protocol = protocol;
+    }
+
+    public String getEncryptionCertificate() {
+        return encryptionCertificate;
+    }
+
+    public void setEncryptionCertificate(String encryptionCertificate) {
+        this.encryptionCertificate = encryptionCertificate;
+    }
+
+    @XmlElementWrapper(name = "claims")
+    @XmlElementRef(name = "requestedClaims")
+    public List<RequestClaim> getRequestedClaims() {
+        return requestedClaims;
+    }
+
+    public void setRequestedClaims(List<RequestClaim> requestedClaims) {
+        this.requestedClaims = requestedClaims;
+    }
+
+    public String getServiceDisplayName() {
+        return serviceDisplayName;
+    }
+
+    public void setServiceDisplayName(String serviceDisplayName) {
+        this.serviceDisplayName = serviceDisplayName;
+    }
+
+    public String getServiceDescription() {
+        return serviceDescription;
+    }
+
+    public void setServiceDescription(String serviceDescription) {
+        this.serviceDescription = serviceDescription;
+    }
+
+    public String getRole() {
+        return role;
+    }
+
+    public void setRole(String role) {
+        this.role = role;
+    }
+
+    public String getTokenType() {
+        return tokenType;
+    }
+
+    public void setTokenType(String tokenType) {
+        this.tokenType = tokenType;
+    }
+
+    public int getLifeTime() {
+        return lifeTime;
+    }
+
+    public void setLifeTime(int lifeTime) {
+        this.lifeTime = lifeTime;
+    }
+
+    public String getPolicyNamespace() {
+        return policyNamespace;
+    }
+
+    public void setPolicyNamespace(String policyNamespace) {
+        this.policyNamespace = policyNamespace;
+    }
+
+    public String getPassiveRequestorEndpoint() {
+        return passiveRequestorEndpoint;
+    }
+
+    public void setPassiveRequestorEndpoint(String passiveRequestorEndpoint) {
+        this.passiveRequestorEndpoint = passiveRequestorEndpoint;
+    }
+
+    public String getPassiveRequestorEndpointConstraint() {
+        return passiveRequestorEndpointConstraint;
+    }
+
+    public void setPassiveRequestorEndpointConstraint(String passiveRequestorEndpointConstraint) {
+        this.passiveRequestorEndpointConstraint = passiveRequestorEndpointConstraint;
+        if (passiveRequestorEndpointConstraint != null) {
+            compiledPassiveRequestorEndpointConstraint = Pattern.compile(passiveRequestorEndpointConstraint);
+        } else {
+            compiledPassiveRequestorEndpointConstraint = null;
+        }
+    }
+    
+    public Pattern getCompiledPassiveRequestorEndpointConstraint() {
+        return compiledPassiveRequestorEndpointConstraint;
+    }
+    
+    public String getValidatingCertificate() {
+        return validatingCertificate;
+    }
+
+    public void setValidatingCertificate(String validatingCertificate) {
+        this.validatingCertificate = validatingCertificate;
+    }
+
+    public boolean isEnableAppliesTo() {
+        return enableAppliesTo;
+    }
+
+    public void setEnableAppliesTo(boolean useAudienceRestriction) {
+        this.enableAppliesTo = useAudienceRestriction;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Claim.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Claim.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Claim.java
new file mode 100644
index 0000000..96afed9
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Claim.java
@@ -0,0 +1,79 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.domain;
+
+import java.io.Serializable;
+import java.net.URI;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "claim", namespace = "http://org.apache.cxf.fediz/")
+public class Claim implements Serializable {
+    
+    private static final long serialVersionUID = 2635896159019665467L;
+    
+    protected URI claimType;
+    protected String displayName;
+    protected String description;
+    protected int id;
+    private URI href;
+    
+    @XmlAttribute
+    public URI getHref() {
+        return href;
+    }
+
+    public void setHref(URI href) {
+        this.href = href;
+    }
+    
+    @XmlAttribute
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    public void setClaimType(URI claimType) {
+        this.claimType = claimType;
+    }
+    
+    public URI getClaimType() {
+        return claimType;
+    }
+
+    public String getDisplayName() {
+        return displayName;
+    }
+
+    public void setDisplayName(String displayName) {
+        this.displayName = displayName;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Entitlement.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Entitlement.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Entitlement.java
new file mode 100644
index 0000000..c926386
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Entitlement.java
@@ -0,0 +1,70 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.domain;
+
+import java.io.Serializable;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+@XmlRootElement(name = "entitlement", namespace = "http://org.apache.cxf.fediz/")
+@XmlType(propOrder = {"name", "description", "internal", "id" })
+public class Entitlement implements Serializable {
+    
+    private static final long serialVersionUID = 2635896159019665467L;
+    
+    protected String name;
+    protected String description;
+    protected int id;
+    protected boolean internal;
+    
+    @XmlAttribute
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public boolean isInternal() {
+        return internal;
+    }
+
+    public void setInternal(boolean internal) {
+        this.internal = internal;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/FederationType.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/FederationType.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/FederationType.java
new file mode 100644
index 0000000..2dcc296
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/FederationType.java
@@ -0,0 +1,40 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.domain;
+
+import javax.xml.bind.annotation.XmlEnum;
+
+@XmlEnum
+public enum FederationType {
+
+    FEDERATE_IDENTITY("FederateIdentity"),
+    FEDERATE_CLAIMS("FederateClaims");
+
+    private String name;
+
+    FederationType(final String name) {
+        this.name = name;
+    }
+
+    @Override
+    public String toString() {
+        return name;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Idp.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Idp.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Idp.java
new file mode 100644
index 0000000..d382184
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Idp.java
@@ -0,0 +1,304 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.domain;
+
+import java.io.Serializable;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+@XmlRootElement(name = "idp", namespace = "http://org.apache.cxf.fediz/")
+@XmlType(propOrder = {"realm", "uri", "serviceDisplayName", "serviceDescription", "idpUrl", "stsUrl",
+                     "certificate", "certificatePassword", "provideIdpList", "useCurrentIdp", "hrds",
+                     "rpSingleSignOutConfirmation", "supportedProtocols", "tokenTypesOffered", "claimTypesOffered",
+                     "authenticationURIs", "applications", "trustedIdps", "id", "rpSingleSignOutCleanupConfirmation" })
+public class Idp implements Serializable {
+
+    private static final long serialVersionUID = -5570301342547139039L;
+
+    
+    protected int id;
+    
+    // Unique
+    // fed:TargetScope
+    protected String realm; // wtrealm, whr
+
+    // Unique
+    // https://<host>:<port>/fediz-idp/<IDP uri>/
+    protected String uri;
+
+    // Home Realm Discovery Service
+    // Spring EL
+    protected String hrds;
+
+    // @Column(name = "INACTIVE", nullable = true, length = FIELD_LENGTH)
+    // if HRDS can't determine the home realm, should
+    // the list of trusted IDPs be shown to make a choice
+    protected boolean provideIdpList;
+
+    // If HRDS can't discover a home realm and displaying IDP list is not
+    // enabled
+    // it falls back to current IDP if an authentication domain is configured
+    protected boolean useCurrentIdp;
+
+    // Store certificate in DB or filesystem, provide options?
+    // md:KeyDescriptor, use="signing"
+    protected String certificate;
+
+    // Password to read the private key to sign metadata document
+    protected String certificatePassword;
+
+    // fed:SecurityTokenSerivceEndpoint
+    protected URL stsUrl;
+
+    // fed:PassiveRequestorEndpoint
+    // published hostname, port must be configured
+    protected URL idpUrl;
+
+    // RoleDescriptor protocolSupportEnumeration=
+    // "http://docs.oasis-open.org/wsfed/federation/200706"
+    // "http://docs.oasis-open.org/ws-sx/ws-trust/200512"
+    // Could be more in the future
+    protected List<String> supportedProtocols = new ArrayList<>();
+
+    // list of RPs and RP-IDPs from whom we accept SignInResponse
+    // which includes RP IDPs
+    // key: wtrealm
+    protected List<Application> applications = new ArrayList<>();
+
+    // list of trusted IDP from whom we accept SignInResponse
+    // key: whr
+    protected List<TrustedIdp> trustedIdpList = new ArrayList<>();
+
+    // which URI to redirect for authentication
+    // fediz-idp/<IDP uri>/login/auth/<auth URI>
+    // wauth to auth URI mapping
+    protected Map<String, String> authenticationURIs = new HashMap<>();
+
+    // required to create Federation Metadata document
+    // fed:TokenTypesOffered
+    protected List<String> tokenTypesOffered = new ArrayList<>();
+
+    // fed:ClaimTypesOffered
+    protected List<Claim> claimTypesOffered = new ArrayList<>();
+
+    // ServiceDisplayName
+    protected String serviceDisplayName;
+
+    // ServiceDescription
+    protected String serviceDescription;
+    
+    // The user/browser must explicitly confirm to logout from all applications
+    private boolean rpSingleSignOutConfirmation;
+    
+    // Is explicit confirmation required when the "cleanup" URL is called
+    private boolean rpSingleSignOutCleanupConfirmation;
+    
+    @XmlAttribute
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    public String getRealm() {
+        return realm;
+    }
+
+    public void setRealm(String realm) {
+        this.realm = realm;
+    }
+
+    public String getUri() {
+        return uri;
+    }
+
+    public void setUri(String uri) {
+        this.uri = uri;
+    }
+
+    public String getHrds() {
+        return hrds;
+    }
+
+    public void setHrds(String hrds) {
+        this.hrds = hrds;
+    }
+
+    public boolean isProvideIdpList() {
+        return provideIdpList;
+    }
+
+    public void setProvideIdpList(boolean provideIdpList) {
+        this.provideIdpList = provideIdpList;
+    }
+
+    public boolean isUseCurrentIdp() {
+        return useCurrentIdp;
+    }
+
+    public void setUseCurrentIdp(boolean useCurrentIdp) {
+        this.useCurrentIdp = useCurrentIdp;
+    }
+
+    public String getCertificate() {
+        return certificate;
+    }
+
+    public void setCertificate(String certificate) {
+        this.certificate = certificate;
+    }
+
+    public String getCertificatePassword() {
+        return certificatePassword;
+    }
+
+    public void setCertificatePassword(String password) {
+        this.certificatePassword = password;
+    }
+
+    public URL getStsUrl() {
+        return stsUrl;
+    }
+
+    public void setStsUrl(URL stsUrl) {
+        this.stsUrl = stsUrl;
+    }
+
+    public URL getIdpUrl() {
+        return idpUrl;
+    }
+
+    public void setIdpUrl(URL idpUrl) {
+        this.idpUrl = idpUrl;
+    }
+
+    @XmlElementWrapper(name = "supportedProtocols")
+    public List<String> getSupportedProtocols() {
+        return supportedProtocols;
+    }
+
+    public void setSupportedProtocols(List<String> supportedProtocols) {
+        this.supportedProtocols = supportedProtocols;
+    }
+
+    public Application findApplication(String realmApplication) {
+        for (Application item : applications) {
+            if (item.getRealm().equals(realmApplication)) {
+                return item;
+            }
+        }
+        return null;
+    }
+    
+    @XmlElementWrapper(name = "applications")
+    @XmlElementRef(name = "application")
+    public List<Application> getApplications() {
+        return applications;
+    }
+
+    public void setApplications(List<Application> applications) {
+        this.applications = applications;
+    }
+
+    public TrustedIdp findTrustedIdp(String realmTrustedIdp) {
+        for (TrustedIdp item : trustedIdpList) {
+            if (item.getRealm().equals(realmTrustedIdp)) {
+                return item;
+            }
+        }
+        return null;
+    }
+    
+    @XmlElementWrapper(name = "trustedIdps")
+    @XmlElementRef(name = "trustedIdp")
+    public List<TrustedIdp> getTrustedIdps() {
+        return trustedIdpList;
+    }
+
+    public Map<String, String> getAuthenticationURIs() {
+        return authenticationURIs;
+    }
+
+    public void setAuthenticationURIs(Map<String, String> authenticationURIs) {
+        this.authenticationURIs = authenticationURIs;
+    }
+
+    @XmlElementWrapper(name = "tokenTypesOffered")
+    public List<String> getTokenTypesOffered() {
+        return tokenTypesOffered;
+    }
+
+    public void setTokenTypesOffered(List<String> tokenTypesOffered) {
+        this.tokenTypesOffered = tokenTypesOffered;
+    }
+
+    @XmlElementWrapper(name = "claimTypesOffered")
+    @XmlElementRef(name = "claimType")
+    public List<Claim> getClaimTypesOffered() {
+        return claimTypesOffered;
+    }
+
+    public void setClaimTypesOffered(List<Claim> claimTypesOffered) {
+        this.claimTypesOffered = claimTypesOffered;
+    }
+
+    public String getServiceDisplayName() {
+        return serviceDisplayName;
+    }
+
+    public void setServiceDisplayName(String serviceDisplayName) {
+        this.serviceDisplayName = serviceDisplayName;
+    }
+
+    public String getServiceDescription() {
+        return serviceDescription;
+    }
+
+    public void setServiceDescription(String serviceDescription) {
+        this.serviceDescription = serviceDescription;
+    }
+
+    public boolean isRpSingleSignOutConfirmation() {
+        return rpSingleSignOutConfirmation;
+    }
+
+    public void setRpSingleSignOutConfirmation(boolean rpSingleSignOutConfirmation) {
+        this.rpSingleSignOutConfirmation = rpSingleSignOutConfirmation;
+    }
+
+    public boolean isRpSingleSignOutCleanupConfirmation() {
+        return rpSingleSignOutCleanupConfirmation;
+    }
+
+    public void setRpSingleSignOutCleanupConfirmation(boolean rpSingleSignOutCleanupConfirmation) {
+        this.rpSingleSignOutCleanupConfirmation = rpSingleSignOutCleanupConfirmation;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/RequestClaim.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/RequestClaim.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/RequestClaim.java
new file mode 100644
index 0000000..008e75a
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/RequestClaim.java
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.domain;
+
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name = "requestClaim", namespace = "http://org.apache.cxf.fediz/")
+public class RequestClaim extends Claim {
+    
+    private static final long serialVersionUID = 8097560995225077866L;
+    
+    protected boolean optional;
+    
+    public RequestClaim() {
+        super();
+    }
+    
+    public RequestClaim(Claim c) {
+        super();
+        this.setClaimType(c.getClaimType());
+        this.setDescription(c.getDescription());
+        this.setDisplayName(c.getDisplayName());
+        this.setId(c.getId());
+    }
+      
+    public void setOptional(boolean optional) {
+        this.optional = optional;
+    }
+    
+    public boolean isOptional() {
+        return optional;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Role.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Role.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Role.java
new file mode 100644
index 0000000..f403546
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/Role.java
@@ -0,0 +1,74 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.domain;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+@XmlRootElement(name = "role", namespace = "http://org.apache.cxf.fediz/")
+@XmlType(propOrder = {"name", "description", "entitlements", "id" })
+public class Role implements Serializable {
+    
+    private static final long serialVersionUID = 2635896159019665467L;
+    
+    protected String name;
+    protected String description;
+    protected int id;
+    
+    protected List<Entitlement> entitlements = new ArrayList<>();
+    
+    @XmlAttribute
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public List<Entitlement> getEntitlements() {
+        return entitlements;
+    }
+
+    public void setEntitlements(List<Entitlement> entitlements) {
+        this.entitlements = entitlements;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustType.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustType.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustType.java
new file mode 100644
index 0000000..50efb25
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustType.java
@@ -0,0 +1,40 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.domain;
+
+import javax.xml.bind.annotation.XmlEnum;
+
+@XmlEnum
+public enum TrustType {
+
+    PEER_TRUST("PeerTrust"),
+    INDIRECT_TRUST("IndirectTrust");
+
+    private String name;
+
+    TrustType(final String name) {
+        this.name = name;
+    }
+
+    @Override
+    public String toString() {
+        return name;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustedIdp.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustedIdp.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustedIdp.java
new file mode 100644
index 0000000..b3262b5
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustedIdp.java
@@ -0,0 +1,187 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.domain;
+
+import java.io.Serializable;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlType;
+
+@XmlRootElement(name = "trustedIdp", namespace = "http://org.apache.cxf.fediz/")
+@XmlType(propOrder = {"realm", "issuer", "url", "name", "description", "protocol", "trustType",
+                      "certificate", "federationType", "cacheTokens", "logo", "id", "parameters" })
+//@XmlAttribute on Id must be set on getter, not on attribute, otherwise error
+public class TrustedIdp implements Serializable {
+
+    private static final long serialVersionUID = -6520081722646469178L;
+
+    
+    protected int id;
+
+    //@Column(name = "REALM", nullable = true, length = FIELD_LENGTH)
+    protected String realm;  //wtrealm, whr
+    
+    //@Column(name = "Issuer", nullable = true, length = FIELD_LENGTH)
+    protected String issuer;  //SAMLResponse issuer name
+
+    // Should tokens be cached from trusted IDPs
+    // to avoid redirection to the trusted IDP again for next SignIn request
+    protected boolean cacheTokens;
+    
+    //Could be read from Metadata, PassiveRequestorEndpoint
+    protected String url;
+    
+    //Could be read from Metadata, md:KeyDescriptor, use="signing"
+    //Store certificate in DB or filesystem, provide options?
+    protected String certificate;
+    
+    //Direct trust (signing cert imported), Indirect trust (CA certs imported, subject configured)
+    protected TrustType trustType;
+    
+    //Could be read from Metadata, RoleDescriptor protocolSupportEnumeration=
+    // "http://docs.oasis-open.org/wsfed/federation/200706"
+    // Metadata could provide more than one but one must be chosen
+    protected String protocol;
+    
+    //FederateIdentity, FederateClaims
+    protected FederationType federationType;
+    
+    //optional (to provide a list of IDPs)
+    protected String name;
+    
+    //optional (to provide a list of IDPs)
+    protected String description;
+    
+    //optional (to provide a list of IDPs)
+    protected String logo;
+    
+    // Additional (possibly protocol specific parameters)
+    protected Map<String, String> parameters = new HashMap<>();
+
+    
+    @XmlAttribute
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+    
+    public String getIssuer() {
+        return issuer;
+    }
+    
+    public void setIssuer(String issuer) {
+        this.issuer = issuer;
+    }
+    
+    public String getRealm() {
+        return realm;
+    }
+
+    public void setRealm(String realm) {
+        this.realm = realm;
+    }
+
+    public boolean isCacheTokens() {
+        return cacheTokens;
+    }
+
+    public void setCacheTokens(boolean cacheTokens) {
+        this.cacheTokens = cacheTokens;
+    }
+
+    public String getUrl() {
+        return url;
+    }
+
+    public void setUrl(String url) {
+        this.url = url;
+    }
+
+    public String getCertificate() {
+        return certificate;
+    }
+
+    public void setCertificate(String certificate) {
+        this.certificate = certificate;
+    }
+
+    public String getProtocol() {
+        return protocol;
+    }
+
+    public void setProtocol(String protocol) {
+        this.protocol = protocol;
+    }
+
+    public FederationType getFederationType() {
+        return federationType;
+    }
+
+    public void setFederationType(FederationType federationType) {
+        this.federationType = federationType;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getDescription() {
+        return description;
+    }
+
+    public void setDescription(String description) {
+        this.description = description;
+    }
+
+    public String getLogo() {
+        return logo;
+    }
+
+    public void setLogo(String logo) {
+        this.logo = logo;
+    }
+
+    public TrustType getTrustType() {
+        return trustType;
+    }
+
+    public void setTrustType(TrustType trustType) {
+        this.trustType = trustType;
+    }
+
+    public Map<String, String> getParameters() {
+        return parameters;
+    }
+
+    public void setParameters(Map<String, String> parameters) {
+        this.parameters = parameters;
+    }
+               
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosAuthenticationProcessingFilter.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosAuthenticationProcessingFilter.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosAuthenticationProcessingFilter.java
new file mode 100644
index 0000000..8e39e85
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosAuthenticationProcessingFilter.java
@@ -0,0 +1,199 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+/*
+ * Copyright 2002-2008 the original author or authors.
+ * 
+ * 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 org.apache.cxf.fediz.service.idp.kerberos;
+
+import java.io.IOException;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.springframework.security.authentication.AnonymousAuthenticationToken;
+import org.springframework.security.authentication.AuthenticationDetailsSource;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.security.crypto.codec.Base64;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
+import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
+import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
+import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
+import org.springframework.util.Assert;
+import org.springframework.web.filter.GenericFilterBean;
+/**
+ * Parses the SPNEGO authentication Header, which was generated by the browser
+ * and creates a {@link KerberosServiceRequestToken} out if it. It will then
+ * call the {@link AuthenticationManager}.
+ *
+ * @author Mike Wiesner
+ * @since 1.0
+ * @version $Id$
+ * @see KerberosServiceAuthenticationProvider
+ * @see KerberosEntryPoint
+ */
+public class KerberosAuthenticationProcessingFilter extends GenericFilterBean {
+    private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = 
+        new WebAuthenticationDetailsSource();
+    private AuthenticationManager authenticationManager;
+    private AuthenticationSuccessHandler successHandler;
+    private AuthenticationFailureHandler failureHandler;
+    private SessionAuthenticationStrategy sessionStrategy = new NullAuthenticatedSessionStrategy();
+    private boolean skipIfAlreadyAuthenticated = true;
+    /*
+     * (non-Javadoc)
+     *
+     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
+     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
+     */
+    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
+        throws IOException, ServletException {
+        HttpServletRequest request = (HttpServletRequest) req;
+        HttpServletResponse response = (HttpServletResponse) res;
+        if (skipIfAlreadyAuthenticated) {
+            Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
+            if (existingAuth != null && existingAuth.isAuthenticated()
+                && !(existingAuth instanceof AnonymousAuthenticationToken)) {
+                chain.doFilter(request, response);
+                return;
+            }
+        }
+        String header = request.getHeader("Authorization");
+        if ((header != null) && header.startsWith("Negotiate ")) {
+            if (logger.isDebugEnabled()) {
+                logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
+            }
+            byte[] base64Token = header.substring(10).getBytes("UTF-8");
+            byte[] kerberosTicket = Base64.decode(base64Token);
+            KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
+            authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));
+            Authentication authentication;
+            try {
+                authentication = authenticationManager.authenticate(authenticationRequest);
+            } catch (AuthenticationException e) {
+                //That shouldn't happen, as it is most likely a wrong
+                //configuration on the server side
+                logger.warn("Negotiate Header was invalid: " + header, e);
+                SecurityContextHolder.clearContext();
+                if (failureHandler != null) {
+                    failureHandler.onAuthenticationFailure(request, response, e);
+                } else {
+                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                    response.flushBuffer();
+                }
+                return;
+            }
+            sessionStrategy.onAuthentication(authentication, request, response);
+            SecurityContextHolder.getContext().setAuthentication(authentication);
+            if (successHandler != null) {
+                successHandler.onAuthenticationSuccess(request, response, authentication);
+            }
+        }
+        chain.doFilter(request, response);
+    }
+    /**
+     * The authentication manager for validating the ticket.
+     *
+     * @param authenticationManager
+     */
+    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
+        this.authenticationManager = authenticationManager;
+    }
+    /**
+     * This handler is called after a successful authentication. One can add
+     * additional authentication behavior by setting this.<br />
+     * Default is null, which means nothing additional happens
+     *
+     * @param successHandler
+     */
+    public void setSuccessHandler(AuthenticationSuccessHandler successHandler) {
+        this.successHandler = successHandler;
+    }
+    /**
+     * This handler is called after a failure authentication. In most cases you
+     * only get Kerberos/SPNEGO failures with a wrong server or network
+     * configurations and not during runtime. If the client encounters an error,
+     * he will just stop the communication with server and therefore this
+     * handler will not be called in this case.<br />
+     * Default is null, which means that the Filter returns the HTTP 500 code
+     *
+     * @param failureHandler
+     */
+    public void setFailureHandler(AuthenticationFailureHandler failureHandler) {
+        this.failureHandler = failureHandler;
+    }
+    /**
+     * Should Kerberos authentication be skipped if a user is already authenticated
+     * for this request (e.g. in the HTTP session).
+     *
+     * @param skipIfAlreadyAuthenticated default is true
+     */
+    public void setSkipIfAlreadyAuthenticated(boolean skipIfAlreadyAuthenticated) {
+        this.skipIfAlreadyAuthenticated = skipIfAlreadyAuthenticated;
+    }
+    /**
+     * The session handling strategy which will be invoked immediately after an authentication request is
+     * successfully processed by the <tt>AuthenticationManager</tt>. Used, for example, to handle changing of the
+     * session identifier to prevent session fixation attacks.
+     *
+     * @param sessionAuthStrategy the implementation to use. If not set a null implementation is
+     * used.
+     */
+    public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionAuthStrategy) {
+        this.sessionStrategy = sessionAuthStrategy;
+    }
+    public void setAuthenticationDetailsSource(
+        AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
+        Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
+        this.authenticationDetailsSource = authenticationDetailsSource;
+    }
+    /*
+     * (non-Javadoc)
+     *
+     * @see
+     * org.springframework.web.filter.GenericFilterBean#afterPropertiesSet()
+     */
+    @Override
+    public void afterPropertiesSet() throws ServletException {
+        super.afterPropertiesSet();
+        Assert.notNull(this.authenticationManager, "authenticationManager must be specified");
+    }
+}
+
+
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosEntryPoint.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosEntryPoint.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosEntryPoint.java
new file mode 100644
index 0000000..457a60e
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosEntryPoint.java
@@ -0,0 +1,70 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+/*
+ * Copyright 2009 the original author or authors.
+ * 
+ * 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 org.apache.cxf.fediz.service.idp.kerberos;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.AuthenticationEntryPoint;
+
+/**
+* Sends back a request for a Negotiate Authentication to the browser.
+*
+* @author Mike Wiesner
+* @since 1.0
+* @version $Id$
+* @see KerberosAuthenticationProcessingFilter
+*/
+public class KerberosEntryPoint implements AuthenticationEntryPoint {
+    
+    private static final Log LOG = LogFactory.getLog(KerberosEntryPoint.class);
+    
+    public void commence(HttpServletRequest request, HttpServletResponse response,
+                         AuthenticationException ex) throws IOException, ServletException {
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Sending back Negotiate Header for request: " + request.getRequestURL());
+        }
+        response.addHeader("WWW-Authenticate", "Negotiate");
+        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
+        response.flushBuffer();
+    }
+    
+}
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosServiceRequestToken.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosServiceRequestToken.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosServiceRequestToken.java
new file mode 100644
index 0000000..2aba9cf
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosServiceRequestToken.java
@@ -0,0 +1,150 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+/*
+ * Copyright 2009 the original author or authors.
+ * 
+ * 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 org.apache.cxf.fediz.service.idp.kerberos;
+
+import java.util.Arrays;
+import java.util.Collection;
+import org.springframework.security.authentication.AbstractAuthenticationToken;
+import org.springframework.security.core.GrantedAuthority;
+
+/**
+ * Holds the Kerberos/SPNEGO token for requesting a kerberized service
+ * and is also the output of <code>KerberosServiceAuthenticationProvider</code>.<br>
+ * Will mostly be created in <code>SpnegoAuthenticationProcessingFilter</code>
+ * and authenticated in <code>KerberosServiceAuthenticationProvider</code>.
+ *
+ * This token cannot be re-authenticated, as you will get a Kerberos Reply error.
+ *
+ * @author Mike Wiesner
+ * @since 1.0
+ * @version $Id$
+ * @see KerberosServiceAuthenticationProvider
+ * @see KerberosAuthenticationProcessingFilter
+ */
+public class KerberosServiceRequestToken extends AbstractAuthenticationToken {
+    private static final long serialVersionUID = 395488921064775014L;
+    private final byte[] token;
+    private final Object principal;
+    
+    /** Creates an authenticated token, normally used as an output of an authentication provider.
+     * @param principal the user principal (mostly of instance <code>UserDetails</code>
+     * @param authorities the authorities which are granted to the user
+     * @param token the Kerberos/SPNEGO token
+     * @see UserDetails
+     */
+    public KerberosServiceRequestToken(Object principal, 
+                                       Collection<? extends GrantedAuthority> authorities, 
+                                       byte[] token) {
+        super(authorities);
+        if (token != null) {
+            this.token = Arrays.copyOf(token, token.length);
+        } else {
+            this.token = null;
+        }
+        this.principal = principal;
+        super.setAuthenticated(true);
+    }
+    
+    /**
+     * Creates an unauthenticated instance which should then be authenticated by
+     * <code>KerberosServiceAuthenticationProvider/code>
+     *
+     * @param token Kerberos/SPNEGO token
+     * @see KerberosServiceAuthenticationProvider
+     */
+    public KerberosServiceRequestToken(byte[] token) {
+        super(null);
+        if (token != null) {
+            this.token = Arrays.copyOf(token, token.length);
+        } else {
+            this.token = null;
+        }
+        this.principal = null;
+    }
+    
+    /**
+     * Calculates hashcode based on the Kerberos token
+     */
+    @Override
+    public int hashCode() {
+        final int prime = 31;
+        int result = super.hashCode();
+        result = prime * result + Arrays.hashCode(token);
+        return result;
+    }
+    
+    /**
+     * equals() is based only on the Kerberos token
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (this == obj) {
+            return true;
+        }
+        if (!super.equals(obj)) {
+            return false;
+        }
+        if (getClass() != obj.getClass()) {
+            return false;
+        }
+        KerberosServiceRequestToken other = (KerberosServiceRequestToken) obj;
+        if (!Arrays.equals(token, other.token)) {       //NOPMD
+            return false;
+        }
+        return true;
+    }
+    
+    /* (non-Javadoc)
+     * @see org.springframework.security.core.Authentication#getCredentials()
+     */
+    public Object getCredentials() {
+        return null;
+    }
+    
+    /* (non-Javadoc)
+     * @see org.springframework.security.core.Authentication#getPrincipal()
+     */
+    public Object getPrincipal() {
+        return this.principal;
+    }
+    
+    /** Returns the Kerberos token
+     */
+    public byte[] getToken() {
+        if (token != null) {
+            return Arrays.copyOf(token, token.length);
+        }
+        return null;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosTokenValidator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosTokenValidator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosTokenValidator.java
new file mode 100644
index 0000000..c9b0cd7
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosTokenValidator.java
@@ -0,0 +1,185 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.kerberos;
+
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.util.Set;
+
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+
+import org.apache.wss4j.common.kerberos.KerberosServiceContext;
+import org.apache.wss4j.common.kerberos.KerberosServiceExceptionAction;
+
+/**
+ * Validate a Kerberos Token
+ */
+public class KerberosTokenValidator {
+
+    private static final org.slf4j.Logger LOG =
+        org.slf4j.LoggerFactory.getLogger(KerberosTokenValidator.class);
+
+    private String serviceName;
+    private CallbackHandler callbackHandler;
+    private String contextName;
+    private boolean usernameServiceNameForm;
+    private boolean spnego;
+
+    /**
+     * Get the JAAS Login context name to use.
+     * @return the JAAS Login context name to use
+     */
+    public String getContextName() {
+        return contextName;
+    }
+
+    /**
+     * Set the JAAS Login context name to use.
+     * @param contextName the JAAS Login context name to use
+     */
+    public void setContextName(String contextName) {
+        this.contextName = contextName;
+    }
+
+    /**
+     * Get the CallbackHandler to use with the LoginContext
+     * @return the CallbackHandler to use with the LoginContext
+     */
+    public CallbackHandler getCallbackHandler() {
+        return callbackHandler;
+    }
+
+    /**
+     * Set the CallbackHandler to use with the LoginContext. It can be null.
+     * @param callbackHandler the CallbackHandler to use with the LoginContext
+     */
+    public void setCallbackHandler(CallbackHandler callbackHandler) {
+        this.callbackHandler = callbackHandler;
+    }
+
+    /**
+     * The name of the service to use when contacting the KDC. This value can be null, in which
+     * case it defaults to the current principal name.
+     * @param serviceName the name of the service to use when contacting the KDC
+     */
+    public void setServiceName(String serviceName) {
+        this.serviceName = serviceName;
+    }
+
+    /**
+     * Get the name of the service to use when contacting the KDC. This value can be null, in which
+     * case it defaults to the current principal name.
+     * @return the name of the service to use when contacting the KDC
+     */
+    public String getServiceName() {
+        return serviceName;
+    }
+
+    public KerberosServiceContext validate(KerberosServiceRequestToken token) 
+        throws LoginException, PrivilegedActionException {
+        if (LOG.isDebugEnabled()) {
+            try {
+                String jaasAuth = System.getProperty("java.security.auth.login.config");
+                String krbConf = System.getProperty("java.security.krb5.conf");
+                LOG.debug("KerberosTokenValidator - Using JAAS auth login file: " + jaasAuth);
+                LOG.debug("KerberosTokenValidator - Using KRB conf file: " + krbConf);
+            } catch (SecurityException ex) {
+                LOG.debug(ex.getMessage(), ex);
+            }
+        }
+
+        // Get a TGT from the KDC using JAAS
+        LoginContext loginContext = null;
+        if (callbackHandler != null) {
+            loginContext = new LoginContext(getContextName(), callbackHandler);
+        } else {
+            loginContext = new LoginContext(getContextName());
+        }
+        loginContext.login();
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Successfully authenticated to the TGT");
+        }
+
+        // Get the service name to use - fall back on the principal
+        Subject subject = loginContext.getSubject();
+        String service = serviceName;
+        if (service == null) {
+            Set<Principal> principals = subject.getPrincipals();
+            if (principals.isEmpty()) {
+                LOG.debug("No Client principals found after login");
+                return null;
+            }
+            service = principals.iterator().next().getName();
+        }
+
+        // Validate the ticket
+        KerberosServiceExceptionAction action = 
+            new KerberosServiceExceptionAction(token.getToken(), service, 
+                                               isUsernameServiceNameForm(), spnego);
+        KerberosServiceContext krbServiceCtx = Subject.doAs(subject, action);
+
+        if (LOG.isDebugEnabled()) {
+            LOG.debug("Successfully validated a ticket");
+        }
+
+        return krbServiceCtx;
+    }
+
+    /**
+     * SPN can be configured to be in either <b>"hostbased"</b> or <b>"username"</b> form.<br/>
+     *     - <b>"hostbased"</b> - specifies that the service principal name should be interpreted
+     *      as a "host-based" name as specified in GSS API Rfc, section "4.1: Host-Based Service 
+     *      Name Form" - The service name, as it is specified in LDAP/AD, as it is listed in the
+     *      KDC.<br/>
+     *     - <b>"username"</b> - specifies that the service principal name should be interpreted
+     *      as a "username" name as specified in GSS API Rfc, section "4.2: User Name Form" 
+     *      This is usually the client username in LDAP/AD used for authentication to the KDC.
+     * 
+     * <br/><br/>Default is <b>"hostbased"</b>.
+     * 
+     * @return the isUsernameServiceNameForm
+     */
+    public boolean isUsernameServiceNameForm() {
+        return usernameServiceNameForm;
+    }
+
+    /**
+     * If true - sets the SPN form to "username"
+     * <br/>If false<b>(default)</b> - the SPN form is "hostbased"
+     * 
+     * @see KerberosSecurity#retrieveServiceTicket(String, CallbackHandler, String, boolean)
+     * 
+     * @param isUsernameServiceNameForm the isUsernameServiceNameForm to set
+     */
+    public void setUsernameServiceNameForm(boolean isUsernameServiceNameForm) {
+        this.usernameServiceNameForm = isUsernameServiceNameForm;
+    }
+
+    public boolean isSpnego() {
+        return spnego;
+    }
+
+    public void setSpnego(boolean spnego) {
+        this.spnego = spnego;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/PassThroughKerberosClient.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/PassThroughKerberosClient.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/PassThroughKerberosClient.java
new file mode 100644
index 0000000..d75b812
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/PassThroughKerberosClient.java
@@ -0,0 +1,80 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.kerberos;
+
+import java.util.Arrays;
+
+import org.apache.cxf.fediz.core.util.DOMUtils;
+import org.apache.cxf.ws.security.kerberos.KerberosClient;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.common.util.KeyUtils;
+import org.apache.wss4j.dom.WSConstants;
+import org.apache.wss4j.dom.engine.WSSConfig;
+import org.apache.wss4j.dom.message.token.KerberosSecurity;
+import org.apache.xml.security.utils.Base64;
+
+/**
+ * Override the default CXF KerberosClient just to create a BinarySecurityToken from a 
+ * give Kerberos token. This is used to pass a received Kerberos token through to the 
+ * STS, without retrieving a new token.
+ */
+public class PassThroughKerberosClient extends KerberosClient {
+    
+    private byte[] token;
+
+    public PassThroughKerberosClient() {
+        super();
+    }
+
+    @Override
+    public SecurityToken requestSecurityToken() throws Exception {
+        KerberosSecurity bst = new KerberosSecurity(DOMUtils.createDocument());
+        bst.setValueType(WSConstants.WSS_GSS_KRB_V5_AP_REQ);
+        bst.setToken(token);
+        bst.addWSUNamespace();
+        bst.setID(WSSConfig.getNewInstance().getIdAllocator().createSecureId("BST-", bst));
+        
+        SecurityToken securityToken = new SecurityToken(bst.getID());
+        securityToken.setToken(bst.getElement());
+        securityToken.setWsuId(bst.getID());
+        securityToken.setData(bst.getToken());
+        String sha1 = Base64.encode(KeyUtils.generateDigest(bst.getToken()));
+        securityToken.setSHA1(sha1);
+        securityToken.setTokenType(bst.getValueType());
+
+        return securityToken;
+    }
+
+    public byte[] getToken() {
+        if (token != null) {
+            return Arrays.copyOf(token, token.length);
+        }
+        return null;
+    }
+
+    public void setToken(byte[] token) {
+        if (token != null) {
+            this.token = Arrays.copyOf(token, token.length);
+        } else {
+            this.token = null;
+        }
+    }
+
+}


[08/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/resources/realma.cert
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/resources/realma.cert b/services/idp-core/src/test/resources/realma.cert
new file mode 100644
index 0000000..ff97f79
--- /dev/null
+++ b/services/idp-core/src/test/resources/realma.cert
@@ -0,0 +1,15 @@
+-----BEGIN CERTIFICATE-----
+MIICwTCCAamgAwIBAgIEINqJ9TANBgkqhkiG9w0BAQsFADARMQ8wDQYDVQQDEwZSRUFMTUEwHhcN
+MTUwNjEwMTU0NDE3WhcNMjUwNDE4MTU0NDE3WjARMQ8wDQYDVQQDEwZSRUFMTUEwggEiMA0GCSqG
+SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCJDSXn2lDR+JM+AsJarFG3/XGH7K+9AfAbQIz2IgB9MCpO
+KVWTUPCvuo1I+Fp5nEGreuHYLEwgIiam3o+C9tvpLgtDDaDkmXjDzkWpk8z6+im72HZ/ODF93Rqw
+jIiY5ZCzgDumFyPzdKiGwChThamidy+rd6oheSoi6qRVSMMcnwiEUmvkfFvV3izXRqeT5nGQwsin
+y9mCEiGx8jkfxP++H0RQjVjhOwzfQ7epsR7dTQNf2ZhkBR3o6wKV9QnF2IBWHZpA9EK58rWU9H6j
+G7b631rYvwsbOUF9HcZ8DI2BFh+4p18jDN/fnjNGSLr9rYOExpsIiF1cHBK7Tr7WwCmDAgMBAAGj
+ITAfMB0GA1UdDgQWBBRHy0qYoLm9jx/1L6r61NznHKun2jANBgkqhkiG9w0BAQsFAAOCAQEAR9rU
+5Sp1FsOErdvKNFqeaKl0oq6Fuz7BWcGm2kK6+1ZbWE8IOv6Vh+BlLuOe5hF7aLUbm8UIjhKsmg0M
+Ey5MBwkBZktT1qhQteMuiKgYR7CxayCxO0f125RYvvwntJa5rI7bUrzOqX29VQD1qQ/Tb+08fULT
+L7oURP+g88Ff99dn3IpO4VZxZdsbl4+KZRtqQvPAdXNYjOajJtPzS489+/DtfWJ6wPm/7YZ4did4
+1fYcrdwyEZ15L0/5i931z7sztNickm5WhO40qEVDKN6KrlV2Eyea0+933v2Pwe4resTlko9G2T5h
+dEaSbvht2Q/JOMMmT91daeto2oS8HTKhTA==
+-----END CERTIFICATE-----

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/resources/stsKeystoreA.properties
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/resources/stsKeystoreA.properties b/services/idp-core/src/test/resources/stsKeystoreA.properties
new file mode 100644
index 0000000..bd9fb1b
--- /dev/null
+++ b/services/idp-core/src/test/resources/stsKeystoreA.properties
@@ -0,0 +1,6 @@
+org.apache.ws.security.crypto.provider=org.apache.ws.security.components.crypto.Merlin
+org.apache.ws.security.crypto.merlin.keystore.type=jks
+org.apache.ws.security.crypto.merlin.keystore.password=storepass
+org.apache.ws.security.crypto.merlin.keystore.alias=realma
+org.apache.ws.security.crypto.merlin.keystore.file=stsrealm_a.jks
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/resources/stsrealm_a.jks
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/resources/stsrealm_a.jks b/services/idp-core/src/test/resources/stsrealm_a.jks
new file mode 100644
index 0000000..fde2928
Binary files /dev/null and b/services/idp-core/src/test/resources/stsrealm_a.jks differ

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/resources/testContext.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/resources/testContext.xml b/services/idp-core/src/test/resources/testContext.xml
new file mode 100644
index 0000000..bd015f0
--- /dev/null
+++ b/services/idp-core/src/test/resources/testContext.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:util="http://www.springframework.org/schema/util"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd">
+
+    <context:component-scan base-package="org.apache.cxf.fediz.service.idp.service" />
+    <context:component-scan base-package="org.apache.cxf.fediz.service.idp.protocols" />
+
+    <import resource="classpath:persistenceContext.xml" />
+
+    <!-- Use http://www.baeldung.com/2012/02/06/properties-with-spring/ instead -->
+    <bean
+        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
+        <property name="locations">
+            <list>
+                <value>classpath:persistence.properties</value>
+                <value>classpath:realm.properties</value>
+            </list>
+        </property>
+        <property name="ignoreResourceNotFound" value="true" />
+        <property name="ignoreUnresolvablePlaceholders" value="true" />
+    </bean>
+
+    <bean id="dbLoadertest"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.TestDBLoader" />
+
+</beans>
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/pom.xml
----------------------------------------------------------------------
diff --git a/services/idp/pom.xml b/services/idp/pom.xml
index ff92478..bfd4fa5 100644
--- a/services/idp/pom.xml
+++ b/services/idp/pom.xml
@@ -29,29 +29,6 @@
     <name>Apache Fediz IDP</name>
     <packaging>war</packaging>
     
-    <properties>
-        <swagger-ui.version>2.2.6</swagger-ui.version>
-    </properties>
-    
-    <dependencyManagement>
-        <dependencies>
-            <dependency>
-                <groupId>org.springframework</groupId>
-                <artifactId>spring-jdbc</artifactId>
-                <version>${spring.version}</version>
-            </dependency>
-            <dependency>
-                <groupId>org.springframework</groupId>
-                <artifactId>spring-tx</artifactId>
-                <version>${spring.version}</version>
-            </dependency>
-            <dependency>
-                <groupId>org.springframework</groupId>
-                <artifactId>spring-aop</artifactId>
-                <version>${spring.version}</version>
-            </dependency>
-        </dependencies>
-    </dependencyManagement>
     <dependencies>
         <dependency>
             <groupId>junit</groupId>
@@ -60,199 +37,10 @@
             <scope>test</scope>
         </dependency>
         <dependency>
-            <groupId>javax.servlet</groupId>
-            <artifactId>servlet-api</artifactId>
-            <version>${servlet.version}</version>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
             <groupId>org.apache.cxf.fediz</groupId>
-            <artifactId>fediz-core</artifactId>
+            <artifactId>fediz-idp-core</artifactId>
             <version>${project.version}</version>
         </dependency>
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-webmvc</artifactId>
-            <version>${spring.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-tx</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-orm</artifactId>
-            <version>${spring.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-web</artifactId>
-            <version>${spring.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework</groupId>
-            <artifactId>spring-test</artifactId>
-            <version>${spring.version}</version>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework.webflow</groupId>
-            <artifactId>spring-webflow</artifactId>
-            <version>2.4.4.RELEASE</version>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework.security</groupId>
-            <artifactId>spring-security-web</artifactId>
-            <version>${spring.security.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.springframework.security</groupId>
-            <artifactId>spring-security-config</artifactId>
-            <version>${spring.security.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.javassist</groupId>
-            <artifactId>javassist</artifactId>
-            <version>${javassist.version}</version>
-            <scope>runtime</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.slf4j</groupId>
-            <artifactId>slf4j-log4j12</artifactId>
-            <version>${slf4j.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-ws-security</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-rs-security-sso-saml</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-rs-security-sso-oidc</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-transports-http</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-ws-policy</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-ws-addr</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-rs-service-description-swagger</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.commons</groupId>
-            <artifactId>commons-lang3</artifactId>
-            <version>${commons.lang.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-frontend-jaxrs</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-rs-service-description</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-rs-extension-providers</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>com.fasterxml.jackson.jaxrs</groupId>
-            <artifactId>jackson-jaxrs-json-provider</artifactId>
-            <version>2.8.6</version>
-        </dependency>
-        <dependency>
-            <groupId>org.hsqldb</groupId>
-            <artifactId>hsqldb</artifactId>
-            <version>${hsqldb.version}</version>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>cglib</groupId>
-            <artifactId>cglib-nodep</artifactId>
-            <version>3.2.4</version>
-        </dependency>
-        <!-- 
-        <dependency>
-            <groupId>org.apache.openjpa</groupId>
-            <artifactId>openjpa-all</artifactId>
-            <version>${openjpa.version}</version>
-        </dependency>
-        -->
-        <dependency>
-            <groupId>org.apache.commons</groupId> 
-            <artifactId>commons-dbcp2</artifactId>
-            <version>${dbcp.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.openjpa</groupId>
-            <artifactId>openjpa-jdbc</artifactId>
-            <version>${openjpa.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.openjpa</groupId>
-            <artifactId>openjpa-persistence-jdbc</artifactId>
-            <version>${openjpa.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.cxf</groupId>
-            <artifactId>cxf-rt-rs-client</artifactId>
-            <version>${cxf.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>javax.validation</groupId>
-            <artifactId>validation-api</artifactId>
-            <version>${javax.validation.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>jstl</groupId>
-            <artifactId>jstl</artifactId>
-            <version>1.2</version>
-        </dependency>
-        <dependency>
-            <groupId>org.apache.bval</groupId>
-            <artifactId>bval-jsr</artifactId>
-            <version>${bval.version}</version>
-            <exclusions>
-                <exclusion>
-                    <groupId>com.sun.xml.bind</groupId>
-                    <artifactId>jaxb-impl</artifactId>
-                </exclusion>
-                <!-- 
-                dependency to newer version (commons-beanutils)
-                imported from commons-validator
-                -->
-                <exclusion>
-                    <groupId>commons-beanutils</groupId>
-                    <artifactId>commons-beanutils-core</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>commons-validator</groupId>
-            <artifactId>commons-validator</artifactId>
-            <version>${commons.validator.version}</version>
-        </dependency>
     </dependencies>
     <build>
         <resources>
@@ -279,32 +67,6 @@
         </resources>
         <plugins>
             <plugin>
-                <groupId>org.apache.openjpa</groupId>
-                <artifactId>openjpa-maven-plugin</artifactId>
-                <version>${openjpa.version}</version>
-                <inherited>true</inherited>
-                <configuration>
-                    <persistenceXmlFile>${project.basedir}/src/main/resources/META-INF/spring-persistence.xml</persistenceXmlFile>
-                    <includes>org/apache/cxf/fediz/service/idp/service/jpa/**/*.class</includes>
-                </configuration>
-                <executions>
-                    <execution>
-                        <id>enhancer</id>
-                        <phase>process-classes</phase>
-                        <goals>
-                            <goal>enhance</goal>
-                        </goals>
-                    </execution>
-                </executions>
-                <dependencies>
-                    <dependency>
-                        <groupId>xerces</groupId>
-                        <artifactId>xercesImpl</artifactId>
-                        <version>2.11.0</version>
-                    </dependency>
-                </dependencies>
-            </plugin>
-            <plugin>
                 <!--for mvn tomcat:deploy/:undeploy/:redeploy -->
                 <groupId>org.codehaus.mojo</groupId>
                 <artifactId>tomcat-maven-plugin</artifactId>
@@ -342,74 +104,6 @@
                 </configuration>
             </plugin>
             <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-dependency-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <phase>generate-resources</phase>
-                        <goals>
-                            <goal>unpack</goal>
-                        </goals>
-                        <configuration>
-                            <artifactItems>
-                                <artifactItem>
-                                    <groupId>org.webjars</groupId>
-                                    <artifactId>swagger-ui</artifactId>
-                                    <version>${swagger-ui.version}</version>
-                                    <overWrite>true</overWrite>
-                                    <outputDirectory>${project.build.directory}/swagger-ui</outputDirectory>
-                                    <excludes>**/*.gz</excludes>
-                                </artifactItem>
-                            </artifactItems>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-resources-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>copy-swagger-resources-in-place</id>
-                        <phase>process-resources</phase>
-                        <goals>
-                            <goal>copy-resources</goal>
-                        </goals>
-                        <configuration>
-                            <outputDirectory>${project.build.directory}/${project.build.finalName}/resources/swagger</outputDirectory>
-                            <resources>
-                                <resource>
-                                    <directory>${project.build.directory}/swagger-ui/META-INF/resources/webjars/swagger-ui/${swagger-ui.version}</directory>
-                                    <excludes>
-                                        <exclude>index.html</exclude>
-                                        <exclude>swagger-ui.min.js</exclude>
-                                    </excludes>
-                                </resource>
-                            </resources>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-antrun-plugin</artifactId>
-                <inherited>true</inherited>
-                <executions>
-                    <execution>
-                        <id>addMatrixParamSupport</id>
-                        <phase>process-resources</phase>
-                        <goals>
-                            <goal>run</goal>
-                        </goals>
-                        <configuration>
-                            <target>
-                                <replace file="${project.build.directory}/swagger-ui/META-INF/resources/webjars/swagger-ui/${swagger-ui.version}/swagger-ui.js" token="return url + requestUrl + querystring;" value="&#xA;var matrixstring = '';&#xA; for (var i = 0; i &lt; this.parameters.length; i++) {&#xA; var param = this.parameters[i];&#xA; &#xA; if (param.in === 'matrix') {&#xA; matrixstring += ';' + this.encodeQueryParam(param.name) + '=' + this.encodeQueryParam(args[param.name]);&#xA;     }&#xA;   }&#xA; &#xA;   var url = this.scheme + '://' + this.host;&#xA; &#xA;   if (this.basePath !== '/') {&#xA;     url += this.basePath;&#xA;   }&#xA;   return url + requestUrl + matrixstring + querystring;" />
-                            </target>
-                        </configuration>
-                    </execution>
-                </executions>
-            </plugin>
-            <plugin>
                 <groupId>org.codehaus.mojo</groupId>
                 <artifactId>build-helper-maven-plugin</artifactId>
                 <executions>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/FedizEntryPoint.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/FedizEntryPoint.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/FedizEntryPoint.java
deleted file mode 100644
index dd121fb..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/FedizEntryPoint.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLEncoder;
-import java.util.Enumeration;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.cxf.fediz.core.FederationConstants;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.service.ConfigService;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.springframework.beans.BeansException;
-import org.springframework.beans.factory.InitializingBean;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.AuthenticationEntryPoint;
-import org.springframework.util.Assert;
-
-
-/**
- * Used by the <code>ExceptionTranslationFilter</code> to commence authentication
- * <p>
- * The user's browser will be redirected to the IDP.
- *
- */
-public class FedizEntryPoint implements AuthenticationEntryPoint,
-    InitializingBean, ApplicationContextAware {
-
-    private static final Logger LOG = LoggerFactory.getLogger(FedizEntryPoint.class);
-
-    private ApplicationContext appContext;
-    private ConfigService configService;
-    private String realm;
-    private Idp idpConfig;
-
-    public ConfigService getConfigService() {
-        return configService;
-    }
-
-    public void setConfigService(ConfigService configService) {
-        this.configService = configService;
-    }
-
-    public String getRealm() {
-        return realm;
-    }
-
-    public void setRealm(String realm) {
-        this.realm = realm;
-    }
-
-    public void afterPropertiesSet() throws Exception {
-        Assert.notNull(this.appContext, "ApplicationContext cannot be null.");
-        Assert.notNull(this.configService, "ConfigService cannot be null.");
-        Assert.notNull(this.realm, "realm cannot be null.");
-    }
-
-    public final void commence(final HttpServletRequest servletRequest, final HttpServletResponse response,
-            final AuthenticationException authenticationException) throws IOException, ServletException {
-
-        idpConfig = configService.getIDP(realm);
-        Assert.notNull(this.idpConfig, "idpConfig cannot be null. Check realm and config service implementation");
-
-        String wauth = servletRequest.getParameter(FederationConstants.PARAM_AUTH_TYPE);
-        if (wauth == null) {
-            wauth = "default";
-        }
-        String loginUri = idpConfig.getAuthenticationURIs().get(wauth);
-        if (loginUri == null) {
-            LOG.warn("wauth value '" + wauth + "' not supported");
-            response.sendError(
-                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The wauth value that was supplied is not supported");
-            return;
-        }
-
-        StringBuilder builder = new StringBuilder(extractFullContextPath(servletRequest))
-            .append(loginUri).append("?");
-
-        // Add the query parameters - URL encoding them for safety
-        @SuppressWarnings("unchecked")
-        Enumeration<String> names = servletRequest.getParameterNames();
-        while (names.hasMoreElements()) {
-            String name = names.nextElement();
-            String[] values = servletRequest.getParameterValues(name);
-            if (values != null && values.length > 0) {
-                builder.append(name).append("=");
-                builder.append(URLEncoder.encode(values[0], "UTF-8"));
-                builder.append("&");
-            }
-        }
-        // Remove trailing ampersand
-        if (builder.charAt(builder.length() - 1) == '&') {
-            builder.deleteCharAt(builder.length() - 1);
-        }
-
-        String redirectUrl = builder.toString();
-        preCommence(servletRequest, response);
-        if (LOG.isInfoEnabled()) {
-            LOG.info("Redirect to " + redirectUrl);
-        }
-        response.sendRedirect(redirectUrl);
-    }
-
-
-    /**
-     * Template method for you to do your own pre-processing before the redirect occurs.
-     *
-     * @param request the HttpServletRequest
-     * @param response the HttpServletResponse
-     */
-    protected void preCommence(final HttpServletRequest request, final HttpServletResponse response) {
-
-    }
-
-    @Override
-    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
-        this.appContext = applicationContext;
-    }
-
-    protected String extractFullContextPath(HttpServletRequest request) throws MalformedURLException {
-        String result = null;
-        String contextPath = request.getContextPath();
-        String requestUrl = request.getRequestURL().toString();
-
-        String requestPath = new URL(requestUrl).getPath();
-        // Cut request path of request url and add context path if not ROOT
-        if (requestPath != null && requestPath.length() > 0) {
-            int lastIndex = requestUrl.lastIndexOf(requestPath);
-            result = requestUrl.substring(0, lastIndex);
-        } else {
-            result = requestUrl;
-        }
-        if (contextPath != null && contextPath.length() > 0) {
-            // contextPath contains starting slash
-            result = result + contextPath;
-        }
-        if (result.charAt(result.length() - 1) != '/') {
-            result = result + "/";
-        }
-        return result;
-    }
-
-
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/IdpConstants.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/IdpConstants.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/IdpConstants.java
deleted file mode 100644
index 1e2969b..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/IdpConstants.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-public final class IdpConstants {
-
-    public static final String IDP_CONFIG = "idpConfig";
-
-    /**
-     * A key used to store context/state when communicating with a trusted third party IdP.
-     */
-    public static final String TRUSTED_IDP_CONTEXT = "trusted_idp_context";
-
-    /**
-     * A key used to store the application realm for the given request.
-     */
-    public static final String REALM = "realm";
-
-    /**
-     * A key used to store the home realm for the given request.
-     */
-    public static final String HOME_REALM = "home_realm";
-
-    /**
-     * The SAML Authn Request
-     */
-    public static final String SAML_AUTHN_REQUEST = "saml_authn_request";
-
-    /**
-     * A Context variable associated with the request (independent of protocol)
-     */
-    public static final String CONTEXT = "request_context";
-
-    /**
-     * A key used to store the return address for the given request
-     */
-    public static final String RETURN_ADDRESS = "return_address";
-
-
-    private IdpConstants() {
-        // complete
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/IdpSTSClient.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/IdpSTSClient.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/IdpSTSClient.java
deleted file mode 100644
index b8450b4..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/IdpSTSClient.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-import org.w3c.dom.Element;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.cxf.ws.security.trust.STSClient;
-
-public class IdpSTSClient extends STSClient {
-
-    public IdpSTSClient(Bus b) {
-        super(b);
-    }
-
-    public Element requestSecurityTokenResponse() throws Exception {
-        return requestSecurityTokenResponse(null);
-    }
-
-    public Element requestSecurityTokenResponse(String appliesTo) throws Exception {
-        String action = null;
-        if (isSecureConv) {
-            action = namespace + "/RST/SCT";
-        }
-        return requestSecurityTokenResponse(appliesTo, action, "/Issue", null);
-    }
-
-    public Element requestSecurityTokenResponse(String appliesTo, String action,
-            String requestType, SecurityToken target) throws Exception {
-        STSResponse response = issue(appliesTo, null, "/Issue", null);
-
-        return getDocumentElement(response.getResponse());
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/MetadataServlet.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/MetadataServlet.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/MetadataServlet.java
deleted file mode 100644
index 0aab857..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/MetadataServlet.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.w3c.dom.Document;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.metadata.IdpMetadataWriter;
-import org.apache.cxf.fediz.service.idp.metadata.ServiceMetadataWriter;
-import org.apache.cxf.fediz.service.idp.service.ConfigService;
-import org.apache.wss4j.common.util.DOM2Writer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.ApplicationContext;
-import org.springframework.web.context.support.WebApplicationContextUtils;
-
-
-public class MetadataServlet extends HttpServlet {
-
-    public static final String PARAM_REALM = "realm";
-    
-    private static final Logger LOG = LoggerFactory
-        .getLogger(MetadataServlet.class);
-    private static final long serialVersionUID = 1L;
-    
-    private ApplicationContext applicationContext;
-    private String realm;
-    
-    
-    @Override
-    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
-        IOException {
-        response.setContentType("text/xml; charset=utf-8");
-        PrintWriter out = response.getWriter();
-        
-        ConfigService cs = (ConfigService)getApplicationContext().getBean("config");
-        Idp idpConfig = cs.getIDP(realm);
-        try {
-            if (request.getServletPath() != null && request.getServletPath().startsWith("/metadata")) {
-                String serviceRealm = 
-                    request.getRequestURI().substring(request.getRequestURI().indexOf("/metadata")
-                                                      + "/metadata".length());
-                if (serviceRealm != null && serviceRealm.charAt(0) == '/') {
-                    serviceRealm = serviceRealm.substring(1);
-                }
-                TrustedIdp trustedIdp = idpConfig.findTrustedIdp(serviceRealm);
-                if (trustedIdp == null) {
-                    LOG.error("No TrustedIdp found for desired realm: " + serviceRealm);
-                    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
-                    return;
-                }
-                ServiceMetadataWriter mw = new ServiceMetadataWriter();
-                Document metadata = mw.getMetaData(idpConfig, trustedIdp);
-                out.write(DOM2Writer.nodeToString(metadata));
-            } else {
-                // Otherwise return the Metadata for the Idp
-                LOG.debug(idpConfig.toString());
-                IdpMetadataWriter mw = new IdpMetadataWriter();
-                Document metadata = mw.getMetaData(idpConfig);
-                out.write(DOM2Writer.nodeToString(metadata));
-            }
-        } catch (Exception ex) {
-            LOG.error("Failed to get metadata document: ", ex);
-            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-        }
-    }
-
-    @Override
-    public void init(ServletConfig config) throws ServletException {
-        super.init(config);
-        realm = config.getInitParameter(PARAM_REALM);
-        if (realm == null || realm.length() == 0) {
-            throw new ServletException("Servlet parameter '" + PARAM_REALM + "' not defined");
-        }
-    }
-
-    public ApplicationContext getApplicationContext() {
-        if (applicationContext == null) {
-            LOG.debug(this.getServletContext().toString());
-            applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
-        }
-        return applicationContext;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSAuthenticationProvider.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSAuthenticationProvider.java
deleted file mode 100644
index 4e8ed11..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSAuthenticationProvider.java
+++ /dev/null
@@ -1,307 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.w3c.dom.Element;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.BusFactory;
-//import org.apache.cxf.endpoint.Client;
-import org.apache.cxf.fediz.core.Claim;
-import org.apache.cxf.fediz.core.ClaimTypes;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.opensaml.core.xml.XMLObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.authentication.AuthenticationProvider;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-//import org.apache.cxf.transport.http.HTTPConduit;
-//import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
-
-/**
- * A base class for authenticating credentials to the STS
- */
-public abstract class STSAuthenticationProvider implements AuthenticationProvider {
-
-    public static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER = 
-        "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
-    
-    public static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512 = 
-        "http://docs.oasis-open.org/ws-sx/ws-trust/200512/";
-    
-    public static final String HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST =
-        "http://schemas.xmlsoap.org/ws/2005/02/trust";
-    
-    private static final Logger LOG = LoggerFactory.getLogger(STSAuthenticationProvider.class);
-
-    protected String wsdlLocation;
-    
-    protected String namespace = HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512;
-    
-    protected String wsdlService;
-
-    protected String wsdlEndpoint;
-
-    protected String appliesTo;
-    
-    protected boolean use200502Namespace;
-    
-    protected String tokenType;
-    
-    protected Bus bus;
-    
-    protected Integer lifetime;
-    
-    //Required to get IDP roles to use the IDP application, used in future release
-    protected String roleURI;
-    
-    protected Map<String, Object> properties = new HashMap<>();
-    
-    private String customSTSParameter;
-    
-    protected List<GrantedAuthority> createAuthorities(SecurityToken token) throws WSSecurityException {
-        List<GrantedAuthority> authorities = new ArrayList<>();
-        //authorities.add(new SimpleGrantedAuthority("ROLE_AUTHENTICATED"));
-        //Not needed because AuthenticatedVoter has been added for SecurityFlowExecutionListener
-        if (roleURI != null) {
-            SamlAssertionWrapper assertion = new SamlAssertionWrapper(token.getToken());
-            
-            List<Claim> claims = parseClaimsInAssertion(assertion.getSaml2());
-            for (Claim c : claims) {
-                if (c.getClaimType() != null && roleURI.equals(c.getClaimType().toString())) {
-                    Object oValue = c.getValue();
-                    if ((oValue instanceof List<?>) && !((List<?>)oValue).isEmpty()) {
-                        List<?> values = (List<?>)oValue;
-                        for (Object role: values) {
-                            if (role instanceof String) {
-                                authorities.add(new SimpleGrantedAuthority((String)role));
-                            }
-                        }
-                    } else {
-                        LOG.error("Unsupported value type of Claim value");
-                        throw new IllegalStateException("Unsupported value type of Claim value");
-                    }
-                    claims.remove(c);
-                    break;
-                }
-            }
-        }
-        
-        //Add IDP_LOGIN role to be able to access resource Idp, TrustedIdp, etc.
-        authorities.add(new SimpleGrantedAuthority("ROLE_IDP_LOGIN"));
-        
-        return authorities;
-    }
-    
-    public String getWsdlLocation() {
-        return wsdlLocation;
-    }
-
-    public void setWsdlLocation(String wsdlLocation) {
-        this.wsdlLocation = wsdlLocation;
-    }
-
-    public String getWsdlService() {
-        return wsdlService;
-    }
-
-    public void setWsdlService(String wsdlService) {
-        this.wsdlService = wsdlService;
-    }
-
-    public String getWsdlEndpoint() {
-        return wsdlEndpoint;
-    }
-
-    public void setWsdlEndpoint(String wsdlEndpoint) {
-        this.wsdlEndpoint = wsdlEndpoint;
-    }
-    
-    public String getNamespace() {
-        return namespace;
-    }
-
-    public void setNamespace(String namespace) {
-        this.namespace = namespace;
-    }
-
-    public String getAppliesTo() {
-        return appliesTo;
-    }
-
-    public void setAppliesTo(String appliesTo) {
-        this.appliesTo = appliesTo;
-    }
-    
-    public void setBus(Bus bus) {
-        this.bus = bus;
-    }
-
-    public Bus getBus() {
-        // do not store a referance to the default bus
-        return (bus != null) ? bus : BusFactory.getDefaultBus();
-    }
-
-    public String getTokenType() {
-        return tokenType;
-    }
-
-    public void setTokenType(String tokenType) {
-        this.tokenType = tokenType;
-    }
-    
-    public Integer getLifetime() {
-        return lifetime;
-    }
-
-    public void setLifetime(Integer lifetime) {
-        this.lifetime = lifetime;
-    }
-
-    protected List<Claim> parseClaimsInAssertion(org.opensaml.saml.saml2.core.Assertion assertion) {
-        List<org.opensaml.saml.saml2.core.AttributeStatement> attributeStatements = assertion
-        .getAttributeStatements();
-        if (attributeStatements == null || attributeStatements.isEmpty()) {
-            LOG.debug("No attribute statements found");
-            return Collections.emptyList();
-        }
-
-        List<Claim> collection = new ArrayList<>();
-        Map<String, Claim> claimsMap = new HashMap<>();
-
-        for (org.opensaml.saml.saml2.core.AttributeStatement statement : attributeStatements) {
-            LOG.debug("parsing statement: {}", statement.getElementQName());
-            List<org.opensaml.saml.saml2.core.Attribute> attributes = statement
-            .getAttributes();
-            for (org.opensaml.saml.saml2.core.Attribute attribute : attributes) {
-                LOG.debug("parsing attribute: {}", attribute.getName());
-                Claim c = new Claim();
-                // Workaround for CXF-4484 
-                // Value of Attribute Name not fully qualified
-                // if NameFormat is http://schemas.xmlsoap.org/ws/2005/05/identity/claims
-                // but ClaimType value must be fully qualified as Namespace attribute goes away
-                URI attrName = URI.create(attribute.getName());
-                if (ClaimTypes.URI_BASE.toString().equals(attribute.getNameFormat())
-                    && !attrName.isAbsolute()) {
-                    c.setClaimType(URI.create(ClaimTypes.URI_BASE + "/" + attribute.getName()));
-                } else {
-                    c.setClaimType(URI.create(attribute.getName()));
-                }
-                c.setIssuer(assertion.getIssuer().getNameQualifier());
-
-                List<String> valueList = new ArrayList<>();
-                for (XMLObject attributeValue : attribute.getAttributeValues()) {
-                    Element attributeValueElement = attributeValue.getDOM();
-                    String value = attributeValueElement.getTextContent();
-                    LOG.debug(" [{}]", value);
-                    valueList.add(value);
-                }
-                mergeClaimToMap(claimsMap, c, valueList);
-            }
-        }
-        collection.addAll(claimsMap.values());
-        return collection;
-
-    }
-    
-    protected void mergeClaimToMap(Map<String, Claim> claimsMap, Claim c,
-                                   List<String> valueList) {
-        Claim t = claimsMap.get(c.getClaimType().toString());
-        if (t != null) {
-            //same SAML attribute already processed. Thus Claim object already created.
-            Object oValue = t.getValue();
-            if (oValue instanceof String) {
-                //one child element AttributeValue only
-                List<String> values = new ArrayList<>();
-                values.add((String)oValue); //add existing value
-                values.addAll(valueList);
-                t.setValue(values);
-            } else if (oValue instanceof List<?>) {
-                //more than one child element AttributeValue
-                @SuppressWarnings("unchecked")
-                List<String> values = (List<String>)oValue;
-                values.addAll(valueList);
-                t.setValue(values);
-            } else {
-                LOG.error("Unsupported value type of Claim value");
-                throw new IllegalStateException("Unsupported value type of Claim value");
-            }
-        } else {
-            if (valueList.size() == 1) {
-                c.setValue(valueList.get(0));
-            } else {
-                c.setValue(valueList);
-            }
-            // Add claim to map
-            claimsMap.put(c.getClaimType().toString(), c);
-        }
-    }
-
-    public String getRoleURI() {
-        return roleURI;
-    }
-
-    public void setRoleURI(String roleURI) {
-        this.roleURI = roleURI;
-    }
-    
-    public void setProperties(Map<String, Object> p) {
-        properties.putAll(p);
-    }
-
-    public Map<String, Object> getProperties() {
-        return properties;
-    }
-
-    public boolean isUse200502Namespace() {
-        return use200502Namespace;
-    }
-
-    public void setUse200502Namespace(boolean use200502Namespace) {
-        this.use200502Namespace = use200502Namespace;
-    }
-
-    public String getCustomSTSParameter() {
-        return customSTSParameter;
-    }
-
-    public void setCustomSTSParameter(String customSTSParameter) {
-        this.customSTSParameter = customSTSParameter;
-    }
-
-//May be uncommented for debugging    
-//    private void setTimeout(Client client, Long timeout) {
-//        HTTPConduit conduit = (HTTPConduit) client.getConduit();
-//        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
-//        httpClientPolicy.setConnectionTimeout(timeout);
-//        httpClientPolicy.setReceiveTimeout(timeout);
-//        conduit.setClient(httpClientPolicy);
-//    }
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSKrbAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSKrbAuthenticationProvider.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSKrbAuthenticationProvider.java
deleted file mode 100644
index 62f4817..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSKrbAuthenticationProvider.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.util.List;
-
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginException;
-import javax.xml.namespace.QName;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.fediz.service.idp.kerberos.KerberosServiceRequestToken;
-import org.apache.cxf.fediz.service.idp.kerberos.KerberosTokenValidator;
-import org.apache.cxf.fediz.service.idp.kerberos.PassThroughKerberosClient;
-import org.apache.cxf.ws.security.SecurityConstants;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.wss4j.common.kerberos.KerberosServiceContext;
-import org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.apache.wss4j.dom.WSConstants;
-import org.ietf.jgss.GSSContext;
-import org.ietf.jgss.GSSCredential;
-import org.ietf.jgss.GSSException;
-import org.ietf.jgss.GSSManager;
-import org.ietf.jgss.GSSName;
-import org.ietf.jgss.Oid;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.GrantedAuthority;
-
-/**
- * An authentication provider to authenticate a Kerberos token to the STS
- */
-public class STSKrbAuthenticationProvider extends STSAuthenticationProvider {
-
-    private static final Logger LOG = LoggerFactory.getLogger(STSKrbAuthenticationProvider.class);
-
-    private KerberosTokenValidator kerberosTokenValidator;
-    
-    private CallbackHandler kerberosCallbackHandler;
-    
-    private boolean kerberosUsernameServiceNameForm;
-    
-    private boolean requireDelegation;
-    
-    
-    @Override
-    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
-        // We only handle KerberosServiceRequestTokens
-        if (!(authentication instanceof KerberosServiceRequestToken)) {
-            return null;
-        }
-        
-        Bus cxfBus = getBus();
-        IdpSTSClient sts = new IdpSTSClient(cxfBus);
-        sts.setAddressingNamespace("http://www.w3.org/2005/08/addressing");
-        if (tokenType != null && tokenType.length() > 0) {
-            sts.setTokenType(tokenType);
-        } else {
-            sts.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
-        }
-        sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
-        sts.setWsdlLocation(wsdlLocation);
-        sts.setServiceQName(new QName(namespace, wsdlService));
-        sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
-        
-        sts.getProperties().putAll(properties);
-        if (use200502Namespace) {
-            sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
-        }
-        
-        if (lifetime != null) {
-            sts.setEnableLifetime(true);
-            sts.setTtl(lifetime.intValue());
-        }
-        
-        return handleKerberos((KerberosServiceRequestToken)authentication, sts);
-    }
-    
-    private Authentication handleKerberos(
-        KerberosServiceRequestToken kerberosRequestToken,
-        IdpSTSClient sts
-    ) {
-        Principal kerberosPrincipal = null;
-        // 
-        // If delegation is required then validate the received token + store the
-        // Delegated Credential so that we can retrieve a new kerberos token for the
-        // STS with it. If delegation is not required, then we just get the received
-        // token + pass it to the STS
-        //
-        if (requireDelegation) {
-            kerberosPrincipal = validateKerberosToken(kerberosRequestToken, sts);
-            if (kerberosPrincipal == null) {
-                return null;
-            }
-        } else {
-            PassThroughKerberosClient kerberosClient = new PassThroughKerberosClient();
-            kerberosClient.setToken(kerberosRequestToken.getToken());
-            sts.getProperties().put(SecurityConstants.KERBEROS_CLIENT, kerberosClient);
-        }
-        
-        try {
-            // Line below may be uncommented for debugging    
-            // setTimeout(sts.getClient(), 3600000L);
-
-            SecurityToken token = sts.requestSecurityToken(this.appliesTo);
-            
-            if (kerberosPrincipal == null && token.getToken() != null
-                && "Assertion".equals(token.getToken().getLocalName())) {
-                // For the pass-through Kerberos case, we don't know the Principal name...
-                kerberosPrincipal = 
-                    new SAMLTokenPrincipalImpl(new SamlAssertionWrapper(token.getToken()));
-            }
-            
-            if (kerberosPrincipal == null) {
-                LOG.info("Failed to authenticate user '" + kerberosRequestToken.getName());
-                return null;
-            }
-            
-            List<GrantedAuthority> authorities = createAuthorities(token);
-            
-            KerberosServiceRequestToken ksrt = 
-                new KerberosServiceRequestToken(kerberosPrincipal, authorities, kerberosRequestToken.getToken());
-            
-            STSUserDetails details = new STSUserDetails(kerberosPrincipal.getName(),
-                                                        "",
-                                                        authorities,
-                                                        token);
-            ksrt.setDetails(details);
-            
-            LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), kerberosPrincipal.getName());
-            return ksrt;
-        } catch (Exception ex) {
-            LOG.info("Failed to authenticate user '" + kerberosRequestToken.getName() + "'", ex);
-            return null;
-        }
-    }
-    
-    private Principal validateKerberosToken(
-        KerberosServiceRequestToken token,
-        IdpSTSClient sts
-    ) {
-        if (kerberosTokenValidator == null) {
-            LOG.error("KerberosTokenValidator must be configured to support kerberos "
-                + "credential delegation");
-            return null;
-        }
-        KerberosServiceContext kerberosContext;
-        Principal kerberosPrincipal = null;
-        try {
-            kerberosContext = kerberosTokenValidator.validate(token);
-            if (kerberosContext == null || kerberosContext.getDelegationCredential() == null) {
-                LOG.info("Kerberos Validation failure");
-                return null;
-            }
-            GSSCredential delegatedCredential = kerberosContext.getDelegationCredential();
-            sts.getProperties().put(SecurityConstants.DELEGATED_CREDENTIAL, 
-                                    delegatedCredential);
-            sts.getProperties().put(SecurityConstants.KERBEROS_USE_CREDENTIAL_DELEGATION, "true");
-            kerberosPrincipal = kerberosContext.getPrincipal();
-        } catch (LoginException ex) {
-            LOG.info("Failed to authenticate user", ex);
-            return null;
-        } catch (PrivilegedActionException ex) {
-            LOG.info("Failed to authenticate user", ex);
-            return null;
-        }
-
-        if (kerberosTokenValidator.getContextName() != null) {
-            sts.getProperties().put(SecurityConstants.KERBEROS_JAAS_CONTEXT_NAME, 
-                                    kerberosTokenValidator.getContextName());
-        }
-        if (kerberosTokenValidator.getServiceName() != null) {
-            sts.getProperties().put(SecurityConstants.KERBEROS_SPN,
-                                    kerberosTokenValidator.getServiceName());
-        }
-        if (kerberosCallbackHandler != null) {
-            sts.getProperties().put(SecurityConstants.CALLBACK_HANDLER, 
-                                    kerberosCallbackHandler);
-        }
-        if (kerberosUsernameServiceNameForm) {
-            sts.getProperties().put(SecurityConstants.KERBEROS_IS_USERNAME_IN_SERVICENAME_FORM, 
-                                    "true");
-        }
-        
-        return kerberosPrincipal;
-    }
-    
-    protected GSSContext createGSSContext() throws GSSException {
-        Oid oid = new Oid("1.2.840.113554.1.2.2");
-
-        GSSManager gssManager = GSSManager.getInstance();
-
-        String spn = "bob@service.ws.apache.org";
-        GSSName gssService = gssManager.createName(spn, null);
-
-        return gssManager.createContext(gssService.canonicalize(oid),
-                                        oid, null, GSSContext.DEFAULT_LIFETIME);
-
-    }
-
-    @Override
-    public boolean supports(Class<?> authentication) {
-        return authentication.equals(KerberosServiceRequestToken.class);
-    }
-    
-    public KerberosTokenValidator getKerberosTokenValidator() {
-        return kerberosTokenValidator;
-    }
-
-    public void setKerberosTokenValidator(KerberosTokenValidator kerberosTokenValidator) {
-        this.kerberosTokenValidator = kerberosTokenValidator;
-    }
-
-    public CallbackHandler getKerberosCallbackHandler() {
-        return kerberosCallbackHandler;
-    }
-
-    public void setKerberosCallbackHandler(CallbackHandler kerberosCallbackHandler) {
-        this.kerberosCallbackHandler = kerberosCallbackHandler;
-    }
-
-    public boolean isKerberosUsernameServiceNameForm() {
-        return kerberosUsernameServiceNameForm;
-    }
-
-    public void setKerberosUsernameServiceNameForm(boolean kerberosUsernameServiceNameForm) {
-        this.kerberosUsernameServiceNameForm = kerberosUsernameServiceNameForm;
-    }
-
-    public boolean isRequireDelegation() {
-        return requireDelegation;
-    }
-
-    public void setRequireDelegation(boolean requireDelegation) {
-        this.requireDelegation = requireDelegation;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSPortFilter.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSPortFilter.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSPortFilter.java
deleted file mode 100644
index 889dadd..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSPortFilter.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.BeansException;
-import org.springframework.context.ApplicationContext;
-import org.springframework.context.ApplicationContextAware;
-import org.springframework.util.Assert;
-import org.springframework.web.filter.GenericFilterBean;
-
-public class STSPortFilter extends GenericFilterBean implements ApplicationContextAware {
-
-    private static final Logger LOG = LoggerFactory.getLogger(STSPortFilter.class);
-    
-    private ApplicationContext applicationContext;
-    private STSAuthenticationProvider authenticationProvider;
-    
-    private boolean isPortSet;
-    
-    @Override
-    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
-        throws IOException, ServletException {
-        
-        Assert.isTrue(applicationContext != null, "Application context must not be null");
-        STSAuthenticationProvider authProvider = authenticationProvider;
-        if (authProvider == null) {
-            authProvider = applicationContext.getBean(STSAuthenticationProvider.class);
-        }
-        Assert.isTrue(authProvider != null, "STSAuthenticationProvider must be configured");
-        
-        //Only update the port if HTTPS is used, otherwise ignored (like retrieving the WADL over HTTP)
-        if (!isPortSet && request.isSecure()) {
-            try {
-                URL url = new URL(authProvider.getWsdlLocation());
-                if (url.getPort() == 0) {
-                    URL updatedUrl = new URL(url.getProtocol(), url.getHost(), request.getLocalPort(), url.getFile());
-                    setSTSWsdlUrl(authProvider, updatedUrl.toString());
-                    LOG.info("STSAuthenticationProvider.wsdlLocation set to " + updatedUrl.toString());
-                } else {
-                    setSTSWsdlUrl(authProvider, url.toString());
-                }
-            } catch (MalformedURLException e) {
-                LOG.error("Invalid Url '" + authProvider.getWsdlLocation() + "': "  + e.getMessage());
-            }
-        }
-        
-        chain.doFilter(request, response);
-    }
-
-    private synchronized void setSTSWsdlUrl(STSAuthenticationProvider authProvider, String wsdlUrl) {
-        authProvider.setWsdlLocation(wsdlUrl);
-        this.isPortSet = true;
-    }
-    
-    @Override
-    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
-        this.applicationContext = applicationContext;
-    }
-
-    public STSAuthenticationProvider getAuthenticationProvider() {
-        return authenticationProvider;
-    }
-
-    public void setAuthenticationProvider(STSAuthenticationProvider authenticationProvider) {
-        this.authenticationProvider = authenticationProvider;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSPreAuthAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSPreAuthAuthenticationProvider.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSPreAuthAuthenticationProvider.java
deleted file mode 100644
index 45ec0a3..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSPreAuthAuthenticationProvider.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-import java.security.cert.X509Certificate;
-import java.util.List;
-
-import javax.xml.namespace.QName;
-
-import org.w3c.dom.Document;
-import org.apache.cxf.Bus;
-import org.apache.cxf.fediz.core.util.DOMUtils;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.wss4j.dom.WSConstants;
-import org.apache.xml.security.exceptions.XMLSecurityException;
-import org.apache.xml.security.keys.content.X509Data;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken;
-
-/**
- * An authentication provider to authenticate a preauthenticated token to the STS
- */
-public class STSPreAuthAuthenticationProvider extends STSAuthenticationProvider {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(STSPreAuthAuthenticationProvider.class);
-
-    @Override
-    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
-        // We only handle PreAuthenticatedAuthenticationTokens
-        if (!(authentication instanceof PreAuthenticatedAuthenticationToken)) {
-            return null;
-        }
-        
-        Bus cxfBus = getBus();
-        IdpSTSClient sts = new IdpSTSClient(cxfBus);
-        sts.setAddressingNamespace("http://www.w3.org/2005/08/addressing");
-        if (tokenType != null && tokenType.length() > 0) {
-            sts.setTokenType(tokenType);
-        } else {
-            sts.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
-        }
-        sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
-        sts.setWsdlLocation(wsdlLocation);
-        sts.setServiceQName(new QName(namespace, wsdlService));
-        sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
-        
-        sts.getProperties().putAll(properties);
-        if (use200502Namespace) {
-            sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
-        }
-        
-        if (lifetime != null) {
-            sts.setEnableLifetime(true);
-            sts.setTtl(lifetime.intValue());
-        }
-        
-        return handlePreAuthenticated((PreAuthenticatedAuthenticationToken)authentication, sts);
-    }
-    
-    private Authentication handlePreAuthenticated(
-        PreAuthenticatedAuthenticationToken preauthenticatedToken,
-        IdpSTSClient sts
-    ) {
-        X509Certificate cert = (X509Certificate)preauthenticatedToken.getCredentials();
-        if (cert == null) {
-            return null;
-        }
-        
-        // Convert the received certificate to a DOM Element to write it out "OnBehalfOf"
-        Document doc = DOMUtils.createDocument();
-        X509Data certElem = new X509Data(doc);
-        try {
-            certElem.addCertificate(cert);
-            sts.setOnBehalfOf(certElem.getElement());
-        } catch (XMLSecurityException e) {
-            LOG.debug("Error parsing a client certificate", e);
-            return null;
-        }
-        
-        try {
-            // Line below may be uncommented for debugging    
-            // setTimeout(sts.getClient(), 3600000L);
-
-            SecurityToken token = sts.requestSecurityToken(this.appliesTo);
-            
-            List<GrantedAuthority> authorities = createAuthorities(token);
-            
-            STSUserDetails details = new STSUserDetails(preauthenticatedToken.getName(),
-                                                        "",
-                                                        authorities,
-                                                        token);
-            
-            preauthenticatedToken.setDetails(details);
-            
-            LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), preauthenticatedToken.getName());
-            return preauthenticatedToken;
-            
-        } catch (Exception ex) {
-            LOG.info("Failed to authenticate user '" + preauthenticatedToken.getName() + "'", ex);
-            return null;
-        }
-    }
-
-    @Override
-    public boolean supports(Class<?> authentication) {
-        return authentication.equals(PreAuthenticatedAuthenticationToken.class);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSUPAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSUPAuthenticationProvider.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSUPAuthenticationProvider.java
deleted file mode 100644
index 6e9130c..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSUPAuthenticationProvider.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.xml.namespace.QName;
-
-import org.apache.cxf.Bus;
-import org.apache.cxf.ws.security.SecurityConstants;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.wss4j.dom.WSConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
-
-/**
- * An authentication provider to authenticate a Username/Password to the STS
- */
-public class STSUPAuthenticationProvider extends STSAuthenticationProvider {
-
-    private static final Logger LOG = LoggerFactory.getLogger(STSUPAuthenticationProvider.class);
-    
-    @Override
-    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
-        // We only handle UsernamePasswordAuthenticationTokens
-        if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
-            return null;
-        }
-        
-        Bus cxfBus = getBus();
-        IdpSTSClient sts = new IdpSTSClient(cxfBus);
-        sts.setAddressingNamespace("http://www.w3.org/2005/08/addressing");
-        if (tokenType != null && tokenType.length() > 0) {
-            sts.setTokenType(tokenType);
-        } else {
-            sts.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
-        }
-        sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
-        sts.setWsdlLocation(wsdlLocation);
-        sts.setServiceQName(new QName(namespace, wsdlService));
-        sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
-        
-        sts.getProperties().putAll(properties);
-        if (use200502Namespace) {
-            sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
-        }
-        
-        if (lifetime != null) {
-            sts.setEnableLifetime(true);
-            sts.setTtl(lifetime.intValue());
-        }
-        
-        return handleUsernamePassword((UsernamePasswordAuthenticationToken)authentication, sts);
-    }
-    
-    private Authentication handleUsernamePassword(
-        UsernamePasswordAuthenticationToken usernamePasswordToken,
-        IdpSTSClient sts
-    ) {
-        sts.getProperties().put(SecurityConstants.USERNAME, usernamePasswordToken.getName());
-        sts.getProperties().put(SecurityConstants.PASSWORD, (String)usernamePasswordToken.getCredentials());
-        
-        try {
-            
-            if (getCustomSTSParameter() != null) {
-                HttpServletRequest request = 
-                    ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
-                String authRealmParameter = request.getParameter(getCustomSTSParameter());
-                LOG.debug("Found {} custom STS parameter {}", getCustomSTSParameter(), authRealmParameter);
-                if (authRealmParameter != null) {
-                    sts.setCustomContent(authRealmParameter);
-                }
-            }
-
-            // Line below may be uncommented for debugging    
-            // setTimeout(sts.getClient(), 3600000L);
-
-            SecurityToken token = sts.requestSecurityToken(this.appliesTo);
-            
-            List<GrantedAuthority> authorities = createAuthorities(token);
-            
-            UsernamePasswordAuthenticationToken upat = 
-                new UsernamePasswordAuthenticationToken(usernamePasswordToken.getName(), 
-                                                        usernamePasswordToken.getCredentials(), 
-                                                        authorities);
-
-            STSUserDetails details = new STSUserDetails(usernamePasswordToken.getName(),
-                                                        (String)usernamePasswordToken.getCredentials(),
-                                                        authorities,
-                                                        token);
-            upat.setDetails(details);
-
-            LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), usernamePasswordToken.getName());
-            return upat;
-                                                                                           
-        } catch (Exception ex) {
-            LOG.info("Failed to authenticate user '" + usernamePasswordToken.getName() + "'", ex);
-            return null;
-        }
-        
-    }
-    
-    @Override
-    public boolean supports(Class<?> authentication) {
-        return authentication.equals(UsernamePasswordAuthenticationToken.class);
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSUserDetails.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSUserDetails.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSUserDetails.java
deleted file mode 100644
index 080bcb4..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/STSUserDetails.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp;
-
-import java.util.Collection;
-
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.userdetails.User;
-
-public class STSUserDetails extends User {
-    
-    private static final long serialVersionUID = 1975259365978165675L;
-    
-    private SecurityToken token;
-    
-    public STSUserDetails(String username, String password, boolean enabled, boolean accountNonExpired,
-                          boolean credentialsNonExpired, boolean accountNonLocked,
-                          Collection<? extends GrantedAuthority> authorities) {
-        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
-    }
-    
-    public STSUserDetails(String username, String password, 
-                          Collection<? extends GrantedAuthority> authorities, SecurityToken token) {
-        super(username, password, true, true, true, true, authorities);
-        this.token = token;
-    }
-
-    public SecurityToken getSecurityToken() {
-        return this.token;
-    }
-
-    @Override
-    public boolean equals(Object object) {
-        if (!(object instanceof STSUserDetails)) {
-            return false;
-        }
-        
-        if (token != null && !token.equals(((STSUserDetails)object).token)) {
-            return false;
-        } else  if (token == null && ((STSUserDetails)object).token != null) {
-            return false;
-        }
-        
-        return super.equals(object);
-    }
-    
-    @Override
-    public int hashCode() {
-        int hashCode = 17;
-        if (token != null) {
-            hashCode *= 31 * token.hashCode();
-        }
-        
-        return hashCode * super.hashCode();
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/CacheSecurityToken.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/CacheSecurityToken.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/CacheSecurityToken.java
deleted file mode 100644
index e219741..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/CacheSecurityToken.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import org.apache.cxf.fediz.service.idp.STSUserDetails;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.stereotype.Component;
-import org.springframework.util.Assert;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * This class is responsible to cache the IDP token.
- */
-@Component
-public class CacheSecurityToken {
-
-    private static final String IDP_CONFIG = "idpConfig";
-    private static final Logger LOG = LoggerFactory.getLogger(CacheSecurityToken.class);
-
-    public void submit(RequestContext context) {
-
-        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
-        Assert.isInstanceOf(STSUserDetails.class, auth.getDetails());
-        final STSUserDetails stsUserDetails = (STSUserDetails) auth.getDetails();
-        SecurityToken securityToken = stsUserDetails.getSecurityToken();
-
-        Idp idpConfig = (Idp)WebUtils.getAttributeFromFlowScope(context, IDP_CONFIG);
-
-        WebUtils.putAttributeInExternalContext(context, idpConfig.getRealm(), securityToken);
-        LOG.info("Token [IDP_TOKEN=" + securityToken.getId()
-                + "] for realm ["
-                + idpConfig.getRealm() + "] successfully cached.");
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/CommonsURLValidator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/CommonsURLValidator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/CommonsURLValidator.java
deleted file mode 100644
index 25780d2..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/CommonsURLValidator.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import org.apache.commons.validator.routines.UrlValidator;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Validate a URL using Commons Validator
- */
-@Component
-public class CommonsURLValidator {
-
-    private static final Logger LOG = LoggerFactory.getLogger(CommonsURLValidator.class);
-
-    public boolean isValid(RequestContext context, String endpointAddress)
-        throws Exception {
-        if (endpointAddress == null) {
-            return true;
-        }
-        
-        // The endpointAddress address must be a valid URL + start with http(s)
-        // Validate it first using commons-validator
-        UrlValidator urlValidator = new UrlValidator(new String[] {"http", "https"}, UrlValidator.ALLOW_LOCAL_URLS);
-        if (!urlValidator.isValid(endpointAddress)) {
-            LOG.warn("The given endpointAddress parameter {} is not a valid URL", endpointAddress);
-            return false;
-        }
-        
-        return true;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/HomeRealmReminder.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/HomeRealmReminder.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/HomeRealmReminder.java
deleted file mode 100644
index c755ebf..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/HomeRealmReminder.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import javax.servlet.http.Cookie;
-
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-@Component
-public class HomeRealmReminder {
-
-    public static final String FEDIZ_HOME_REALM = "FEDIZ_HOME_REALM";
-
-    public Cookie readCookie(RequestContext requestContext) {
-        return WebUtils.readCookie(requestContext, FEDIZ_HOME_REALM);
-    }
-
-    public void addCookie(RequestContext requestContext, String cookieValue) {
-        WebUtils.addCookie(requestContext, FEDIZ_HOME_REALM, cookieValue);
-    }
-
-    public void removeCookie(RequestContext requestContext) {
-        WebUtils.removeCookie(requestContext, FEDIZ_HOME_REALM);
-    }
-}


[03/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
deleted file mode 100644
index 9981253..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.samlsso;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.UnsupportedCallbackException;
-
-import org.apache.wss4j.common.saml.SAMLCallback;
-import org.apache.wss4j.common.saml.bean.AttributeBean;
-import org.apache.wss4j.common.saml.bean.AttributeStatementBean;
-import org.apache.wss4j.common.saml.bean.AuthenticationStatementBean;
-import org.apache.wss4j.common.saml.bean.ConditionsBean;
-import org.apache.wss4j.common.saml.bean.SubjectBean;
-import org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean;
-import org.apache.wss4j.common.saml.bean.Version;
-import org.apache.wss4j.common.saml.builder.SAML2Constants;
-import org.opensaml.core.xml.XMLObject;
-import org.opensaml.saml.saml2.core.Attribute;
-import org.opensaml.saml.saml2.core.AttributeStatement;
-import org.opensaml.saml.saml2.core.Subject;
-
-/**
- * A Callback Handler implementation for a SAML 2 assertion. By default it creates a SAML 2.0 Assertion with
- * an AuthenticationStatement. If a list of AttributeStatements are also supplied it will insert them into the
- * Assertion.
- */
-public class SAML2CallbackHandler implements CallbackHandler {
-    
-    private Subject subject;
-    private String confirmationMethod = SAML2Constants.CONF_BEARER;
-    private String issuer;
-    private ConditionsBean conditions;
-    private SubjectConfirmationDataBean subjectConfirmationData;
-    private List<AttributeStatement> attributeStatements;
-    
-    private void createAndSetStatement(SAMLCallback callback) {
-        AuthenticationStatementBean authBean = new AuthenticationStatementBean();
-        authBean.setAuthenticationMethod("Password");
-        callback.setAuthenticationStatementData(Collections.singletonList(authBean));
-
-        if (attributeStatements != null && !attributeStatements.isEmpty()) {
-            List<AttributeStatementBean> attrStatementBeans = new ArrayList<>();
-            
-            for (AttributeStatement attrStatement : attributeStatements) {
-                AttributeStatementBean attrStatementBean = new AttributeStatementBean();
-                List<AttributeBean> attrBeans = new ArrayList<>();
-                
-                for (Attribute attribute : attrStatement.getAttributes()) {
-                    AttributeBean attributeBean = new AttributeBean();
-                    attributeBean.setQualifiedName(attribute.getName());
-                    attributeBean.setNameFormat(attribute.getNameFormat());
-                    List<Object> attributeValues = new ArrayList<>();
-                    for (XMLObject attrVal : attribute.getAttributeValues()) {
-                        attributeValues.add(attrVal.getDOM().getTextContent());
-                    }
-                    attributeBean.setAttributeValues(attributeValues);
-                    attrBeans.add(attributeBean);
-                }
-                attrStatementBean.setSamlAttributes(attrBeans);
-                attrStatementBeans.add(attrStatementBean);
-            }
-            callback.setAttributeStatementData(attrStatementBeans);
-        }
-    }
-    
-    public void handle(Callback[] callbacks)
-        throws IOException, UnsupportedCallbackException {
-        for (int i = 0; i < callbacks.length; i++) {
-            if (callbacks[i] instanceof SAMLCallback) {
-                SAMLCallback callback = (SAMLCallback) callbacks[i];
-                callback.setSamlVersion(Version.SAML_20);
-                callback.setIssuer(issuer);
-                if (conditions != null) {
-                    callback.setConditions(conditions);
-                }
-                
-                SubjectBean subjectBean = 
-                    new SubjectBean(
-                        subject.getNameID().getValue(), subject.getNameID().getNameQualifier(), confirmationMethod
-                    );
-                subjectBean.setSubjectNameIDFormat(subject.getNameID().getFormat());
-                subjectBean.setSubjectConfirmationData(subjectConfirmationData);
-
-                callback.setSubject(subjectBean);
-                createAndSetStatement(callback);
-            } else {
-                throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
-            }
-        }
-    }
-    
-    public void setSubjectConfirmationData(SubjectConfirmationDataBean subjectConfirmationData) {
-        this.subjectConfirmationData = subjectConfirmationData;
-    }
-    
-    public void setConditions(ConditionsBean conditionsBean) {
-        this.conditions = conditionsBean;
-    }
-    
-    public void setConfirmationMethod(String confMethod) {
-        confirmationMethod = confMethod;
-    }
-    
-    public void setIssuer(String issuer) {
-        this.issuer = issuer;
-    }
-
-    public Subject getSubject() {
-        return subject;
-    }
-
-    public void setSubject(Subject subject) {
-        this.subject = subject;
-    }
-
-    public List<AttributeStatement> getAttributeStatements() {
-        return attributeStatements;
-    }
-
-    public void setAttributeStatements(List<AttributeStatement> attributeStatements) {
-        this.attributeStatements = attributeStatements;
-    }
-    
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2PResponseComponentBuilder.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2PResponseComponentBuilder.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2PResponseComponentBuilder.java
deleted file mode 100644
index 7e64cfa..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2PResponseComponentBuilder.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.samlsso;
-
-import java.util.UUID;
-
-import org.joda.time.DateTime;
-import org.opensaml.core.xml.XMLObjectBuilderFactory;
-import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
-import org.opensaml.saml.common.SAMLObjectBuilder;
-import org.opensaml.saml.common.SAMLVersion;
-import org.opensaml.saml.saml2.core.Issuer;
-import org.opensaml.saml.saml2.core.Response;
-import org.opensaml.saml.saml2.core.Status;
-import org.opensaml.saml.saml2.core.StatusCode;
-import org.opensaml.saml.saml2.core.StatusMessage;
-
-/**
-* A (basic) set of utility methods to construct SAML 2.0 Protocol Response statements
-*/
-public final class SAML2PResponseComponentBuilder {
-    
-    private static SAMLObjectBuilder<Response> responseBuilder;
-    
-    private static SAMLObjectBuilder<Issuer> issuerBuilder;
-    
-    private static SAMLObjectBuilder<Status> statusBuilder;
-    
-    private static SAMLObjectBuilder<StatusCode> statusCodeBuilder;
-    
-    private static SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
-    
-    private static XMLObjectBuilderFactory builderFactory = 
-        XMLObjectProviderRegistrySupport.getBuilderFactory();
-    
-    private SAML2PResponseComponentBuilder() {
-        
-    }
-    
-    @SuppressWarnings("unchecked")
-    public static Response createSAMLResponse(
-        String inResponseTo,
-        String issuer,
-        Status status
-    ) {
-        if (responseBuilder == null) {
-            responseBuilder = (SAMLObjectBuilder<Response>)
-                builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
-        }
-        Response response = responseBuilder.buildObject();
-        
-        response.setID(UUID.randomUUID().toString());
-        response.setIssueInstant(new DateTime());
-        response.setInResponseTo(inResponseTo);
-        response.setIssuer(createIssuer(issuer));
-        response.setStatus(status);
-        response.setVersion(SAMLVersion.VERSION_20);
-        
-        return response;
-    }
-    
-    @SuppressWarnings("unchecked")
-    public static Issuer createIssuer(
-        String issuerValue
-    ) {
-        if (issuerBuilder == null) {
-            issuerBuilder = (SAMLObjectBuilder<Issuer>)
-                builderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
-        }
-        Issuer issuer = issuerBuilder.buildObject();
-        issuer.setValue(issuerValue);
-        
-        return issuer;
-    }
-    
-    @SuppressWarnings("unchecked")
-    public static Status createStatus(
-        String statusCodeValue,
-        String statusMessage
-    ) {
-        if (statusBuilder == null) {
-            statusBuilder = (SAMLObjectBuilder<Status>)
-                builderFactory.getBuilder(Status.DEFAULT_ELEMENT_NAME);
-        }
-        if (statusCodeBuilder == null) {
-            statusCodeBuilder = (SAMLObjectBuilder<StatusCode>)
-                builderFactory.getBuilder(StatusCode.DEFAULT_ELEMENT_NAME);
-        }
-        if (statusMessageBuilder == null) {
-            statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>)
-                builderFactory.getBuilder(StatusMessage.DEFAULT_ELEMENT_NAME);
-        }
-        
-        Status status = statusBuilder.buildObject();
-        
-        StatusCode statusCode = statusCodeBuilder.buildObject();
-        statusCode.setValue(statusCodeValue);
-        status.setStatusCode(statusCode);
-        
-        if (statusMessage != null) {
-            StatusMessage statusMessageObject = statusMessageBuilder.buildObject();
-            statusMessageObject.setMessage(statusMessage);
-            status.setStatusMessage(statusMessageObject);
-        }
-        
-        return status;
-    }
-    
-    
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAMLAuthnRequest.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAMLAuthnRequest.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAMLAuthnRequest.java
deleted file mode 100644
index c7ded4b..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAMLAuthnRequest.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.samlsso;
-
-import java.io.Serializable;
-
-import org.opensaml.saml.saml2.core.AuthnRequest;
-
-/**
- * This class encapsulates a (parsed) SAML AuthnRequest Object. The OpenSAML AuthnRequest Object is not
- * serializable.
- */
-public class SAMLAuthnRequest implements Serializable {
-    /**
-     * 
-     */
-    private static final long serialVersionUID = 4353024755428346545L;
-    
-    private String issuer;
-    private String consumerServiceURL;
-    private String requestId;
-    private boolean forceAuthn;
-    private String subjectNameId;
-    
-    public SAMLAuthnRequest(AuthnRequest authnRequest) {
-        if (authnRequest.getIssuer() != null) {
-            issuer = authnRequest.getIssuer().getValue();
-        }
-        
-        consumerServiceURL = authnRequest.getAssertionConsumerServiceURL();
-        requestId = authnRequest.getID();
-        forceAuthn = authnRequest.isForceAuthn().booleanValue();
-        if (authnRequest.getSubject() != null && authnRequest.getSubject().getNameID() != null) {
-            subjectNameId = authnRequest.getSubject().getNameID().getValue();
-        }
-    }
-    
-    public String getIssuer() {
-        return issuer;
-    }
-    
-    public String getConsumerServiceURL() {
-        return consumerServiceURL;
-    }
-    
-    public String getRequestId() {
-        return requestId;
-    }
-    
-    public boolean isForceAuthn() {
-        return forceAuthn;
-    }
-    
-    public String getSubjectNameId() {
-        return subjectNameId;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ApplicationDAO.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ApplicationDAO.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ApplicationDAO.java
deleted file mode 100644
index a519908..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ApplicationDAO.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service;
-
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
-
-public interface ApplicationDAO {
-
-    List<Application> getApplications(int start, int size, List<String> expand);
-
-    Application getApplication(String realm, List<String> expand);
-
-    Application addApplication(Application application);
-
-    void updateApplication(String realm, Application application);
-
-    void deleteApplication(String realm);
-
-    void addClaimToApplication(Application application, RequestClaim claim);
-    
-    void removeClaimFromApplication(Application application, RequestClaim claim);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ClaimDAO.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ClaimDAO.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ClaimDAO.java
deleted file mode 100644
index 417a50a..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ClaimDAO.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service;
-
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-
-public interface ClaimDAO {
-
-    List<Claim> getClaims(int start, int size);
-    
-    Claim getClaim(String claimType);
-    
-    Claim addClaim(Claim claim);
-    
-    void updateClaim(String claimType, Claim claim);
-    
-    void deleteClaim(String claimType);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigService.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigService.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigService.java
deleted file mode 100644
index e306ff4..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigService.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service;
-
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-
-
-public interface ConfigService {
-
-    Idp getIDP(String realm);
-
-    void setIDP(Idp config);
-
-    void removeIDP(String realm);
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigServiceSpring.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigServiceSpring.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigServiceSpring.java
deleted file mode 100644
index 8545af3..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigServiceSpring.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.model.IDPConfig;
-import org.apache.cxf.fediz.service.idp.model.ServiceConfig;
-
-public class ConfigServiceSpring implements ConfigService {
-
-    private Map<String, Application> serviceConfigs = new HashMap<>();
-    private Map<String, Idp> idpConfigs = new HashMap<>();
-
-
-    @Override
-    public Idp getIDP(String realm) {
-        if (realm == null || realm.length() == 0) {
-            return this.getIdpConfigs().get(0);
-        } else {
-            return idpConfigs.get(realm);
-        }
-    }
-
-    @Override
-    public void setIDP(Idp config) {
-        idpConfigs.put(config.getRealm(), config);
-    }
-
-    @Override
-    public void removeIDP(String realm) {
-        idpConfigs.remove(realm);
-    }
-
-    public List<Application> getServiceConfigs() {
-        return new ArrayList<Application>(serviceConfigs.values());
-    }
-
-    public void setServiceConfigs(List<ServiceConfig> serviceList) {
-        for (ServiceConfig s : serviceList) {
-            serviceConfigs.put(s.getRealm(), s);
-        }
-    }
-    
-    public List<Idp> getIdpConfigs() {
-        return new ArrayList<Idp>(idpConfigs.values());
-    }
-
-    public void setIdpConfigs(List<IDPConfig> idpList) {
-        for (IDPConfig i : idpList) {
-            idpConfigs.put(i.getRealm(), i);
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/EntitlementDAO.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/EntitlementDAO.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/EntitlementDAO.java
deleted file mode 100644
index d93cdc0..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/EntitlementDAO.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service;
-
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-
-public interface EntitlementDAO {
-
-    List<Entitlement> getEntitlements(int start, int size);
-    
-    Entitlement getEntitlement(String name);
-    
-    Entitlement addEntitlement(Entitlement entitlement);
-    
-    void updateEntitlement(String name, Entitlement entitlement);
-    
-    void deleteEntitlement(String name);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/IdpDAO.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/IdpDAO.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/IdpDAO.java
deleted file mode 100644
index 41c5cdf..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/IdpDAO.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service;
-
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-
-public interface IdpDAO {
-
-    List<Idp> getIdps(int start, int size, List<String> expand);
-
-    Idp getIdp(String realm, List<String> expand);
-
-    Idp addIdp(Idp idp);
-
-    void updateIdp(String realm, Idp idp);
-
-    void deleteIdp(String realm);
-
-    void addApplicationToIdp(Idp idp, Application application);
-    
-    void removeApplicationFromIdp(Idp idp, Application application);
-    
-    void addTrustedIdpToIdp(Idp idp, TrustedIdp trustedIdp);
-    
-    void removeTrustedIdpFromIdp(Idp idp, TrustedIdp trustedIdp);
-    
-    void addClaimToIdp(Idp idp, Claim claim);
-    
-    void removeClaimFromIdp(Idp idp, Claim claim);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/RoleDAO.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/RoleDAO.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/RoleDAO.java
deleted file mode 100644
index 2d8e7f5..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/RoleDAO.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service;
-
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.domain.Entitlement;
-import org.apache.cxf.fediz.service.idp.domain.Role;
-
-public interface RoleDAO {
-
-    List<Role> getRoles(int start, int size, List<String> expand);
-
-    Role getRole(String name, List<String> expand);
-
-    Role addRole(Role role);
-
-    void updateRole(String realm, Role role);
-
-    void deleteRole(String name);
-
-    void addEntitlementToRole(Role role, Entitlement entitlement);
-    
-    void removeEntitlementFromRole(Role role, Entitlement entitlement);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/TrustedIdpDAO.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/TrustedIdpDAO.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/TrustedIdpDAO.java
deleted file mode 100644
index 54fb634..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/TrustedIdpDAO.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service;
-
-import java.util.List;
-
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-
-public interface TrustedIdpDAO {
-
-    List<TrustedIdp> getTrustedIDPs(int start, int size);
-
-    TrustedIdp getTrustedIDP(String realm);
-
-    TrustedIdp addTrustedIDP(TrustedIdp trustedIdp);
-
-    void updateTrustedIDP(String realm, TrustedIdp trustedIdp);
-
-    void deleteTrustedIDP(String realm);
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationClaimEntity.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationClaimEntity.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationClaimEntity.java
deleted file mode 100644
index e2ca923..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationClaimEntity.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-
-@Entity(name = "Application_Claim")
-//@IdClass(ApplicationClaimId.class)
-public class ApplicationClaimEntity {
-    
-    @Id
-    private int id;
-    
-    @ManyToOne
-    @JoinColumn(name = "applicationid")
-    private ApplicationEntity application;
- 
-    @ManyToOne
-    @JoinColumn(name = "claimid")
-    private ClaimEntity claim;
- 
-    private boolean optional;
-    
-    public ApplicationClaimEntity() {
-    }
-    
-    public ApplicationClaimEntity(ApplicationEntity application, ClaimEntity claim) {
-        super();
-        this.application = application;
-        this.claim = claim;
-    }
-    
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-
-    public boolean isOptional() {
-        return optional;
-    }
-
-    public void setOptional(boolean optional) {
-        this.optional = optional;
-    }
-
-    public ApplicationEntity getApplication() {
-        return application;
-    }
-
-    public void setApplication(ApplicationEntity application) {
-        this.application = application;
-    }
-
-    public ClaimEntity getClaim() {
-        return claim;
-    }
-
-    public void setClaim(ClaimEntity claim) {
-        this.claim = claim;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPAImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPAImpl.java
deleted file mode 100644
index 307e381..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPAImpl.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.EntityNotFoundException;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
-import org.apache.cxf.fediz.service.idp.service.ApplicationDAO;
-import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Repository;
-import org.springframework.transaction.annotation.Transactional;
-
-@Repository
-@Transactional
-public class ApplicationDAOJPAImpl implements ApplicationDAO {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(ApplicationDAOJPAImpl.class);
-
-    private EntityManager em;
-    
-    @Autowired
-    private ClaimDAO claimDAO;
-    
-    
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-    
-    @Override
-    public List<Application> getApplications(int start, int size, List<String> expandList) {
-        List<Application> list = new ArrayList<>();
-        
-        Query query = null;
-        query = em.createQuery("select a from Application a");
-        
-        //@SuppressWarnings("rawtypes")
-        List<?> serviceEntities = query
-            .setFirstResult(start)
-            .setMaxResults(size)
-            .getResultList();
-    
-        for (Object obj : serviceEntities) {
-            ApplicationEntity entity = (ApplicationEntity) obj;
-            list.add(entity2domain(entity, expandList));
-        }
-        return list;
-    }
-    
-    @Override
-    public Application getApplication(String realm, List<String> expandList) {
-        return entity2domain(getApplicationEntity(realm, em), expandList);
-    }
-    
-    @Override
-    public Application addApplication(Application application) {
-        ApplicationEntity entity = new ApplicationEntity();
-        
-        domain2entity(application, entity);
-        em.persist(entity);
-        
-        LOG.debug("Application '{}' added", application.getRealm());
-        return entity2domain(entity, Arrays.asList("all"));
-    }
-
-    @Override
-    public void updateApplication(String realm, Application application) {
-        Query query = null;
-        query = em.createQuery("select a from Application a where a.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        ApplicationEntity applicationEntity = (ApplicationEntity)query.getSingleResult();
-        
-        domain2entity(application, applicationEntity);
-        
-        em.persist(applicationEntity);
-        
-        LOG.debug("Application '{}' updated", realm);
-    }
-    
-
-    @Override
-    public void deleteApplication(String realm) {
-        Query query = null;
-        query = em.createQuery("select a from Application a where a.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        Object applObj = query.getSingleResult();
-        em.remove(applObj);
-        
-        LOG.debug("Application '{}' deleted", realm);
-        
-    }
-    
-    @Override
-    public void addClaimToApplication(Application application, RequestClaim claim) {
-        ApplicationEntity applicationEntity = null;
-        if (application.getId() != 0) {
-            applicationEntity = em.find(ApplicationEntity.class, application.getId());
-        } else {
-            Query query = null;
-            query = em.createQuery("select a from Application a where a.realm=:realm");
-            query.setParameter("realm", application.getRealm());
-            
-            applicationEntity = (ApplicationEntity)query.getSingleResult();
-        }
-        
-        Claim c = claimDAO.getClaim(claim.getClaimType().toString());
-        ClaimEntity claimEntity = em.find(ClaimEntity.class, c.getId());
-                
-        ApplicationClaimEntity appClaimEntity = new ApplicationClaimEntity();
-        appClaimEntity.setClaim(claimEntity);
-        appClaimEntity.setApplication(applicationEntity);
-        appClaimEntity.setOptional(claim.isOptional());
-        
-        applicationEntity.getRequestedClaims().add(appClaimEntity);
-    }
-    
-    @Override
-    public void removeClaimFromApplication(Application application, RequestClaim claim) {
-        ApplicationEntity applicationEntity = null;
-        if (application.getId() != 0) {
-            applicationEntity = em.find(ApplicationEntity.class, application.getId());
-        } else {
-            Query query = null;
-            query = em.createQuery("select a from Application a where a.realm=:realm");
-            query.setParameter("realm", application.getRealm());
-            
-            applicationEntity = (ApplicationEntity)query.getSingleResult();
-        }
-        
-        ApplicationClaimEntity foundEntity = null;
-        for (ApplicationClaimEntity acm : applicationEntity.getRequestedClaims()) {
-            if (claim.getClaimType().toString().equals(acm.getClaim().getClaimType())) {
-                foundEntity = acm;
-                break;
-            }
-        }
-        if (foundEntity == null) {
-            throw new EntityNotFoundException("ApplicationClaimEntity not found");
-        }
-        
-        applicationEntity.getRequestedClaims().remove(foundEntity);
-    }
-    
-    
-    static ApplicationEntity getApplicationEntity(String realm, EntityManager em) {
-        Query query = null;
-        query = em.createQuery("select a from Application a where a.realm=:realm");
-        query.setParameter("realm", realm);
-        
-        //@SuppressWarnings("rawtypes")
-        return (ApplicationEntity)query.getSingleResult();
-    }
-        
-    public static void domain2entity(Application application, ApplicationEntity entity) {
-        //The ID must not be updated if the entity has got an id already (update case)
-        if (application.getId() > 0) {
-            entity.setId(application.getId());
-        }
-        
-        entity.setEncryptionCertificate(application.getEncryptionCertificate());
-        entity.setValidatingCertificate(application.getValidatingCertificate());
-        entity.setLifeTime(application.getLifeTime());
-        entity.setProtocol(application.getProtocol());
-        entity.setRealm(application.getRealm());
-        entity.setRole(application.getRole());
-        entity.setServiceDescription(application.getServiceDescription());
-        entity.setServiceDisplayName(application.getServiceDisplayName());
-        entity.setTokenType(application.getTokenType());
-        entity.setPolicyNamespace(application.getPolicyNamespace());
-        entity.setPassiveRequestorEndpoint(application.getPassiveRequestorEndpoint());
-        entity.setPassiveRequestorEndpointConstraint(application.getPassiveRequestorEndpointConstraint());
-        entity.setEnableAppliesTo(application.isEnableAppliesTo());
-    }
-    
-    public static Application entity2domain(ApplicationEntity entity, List<String> expandList) {
-        Application application = new Application();
-        application.setId(entity.getId());
-        application.setEncryptionCertificate(entity.getEncryptionCertificate());
-        application.setValidatingCertificate(entity.getValidatingCertificate());
-        application.setLifeTime(entity.getLifeTime());
-        application.setProtocol(entity.getProtocol());
-        application.setRealm(entity.getRealm());
-        application.setRole(entity.getRole());
-        application.setServiceDescription(entity.getServiceDescription());
-        application.setServiceDisplayName(entity.getServiceDisplayName());
-        application.setTokenType(entity.getTokenType());
-        application.setPolicyNamespace(entity.getPolicyNamespace());
-        application.setPassiveRequestorEndpoint(entity.getPassiveRequestorEndpoint());
-        application.setPassiveRequestorEndpointConstraint(entity.getPassiveRequestorEndpointConstraint());
-        application.setEnableAppliesTo(entity.isEnableAppliesTo());
-        
-        if (expandList != null && (expandList.contains("all") || expandList.contains("claims"))) {
-            for (ApplicationClaimEntity item : entity.getRequestedClaims()) {
-                RequestClaim claim = entity2domain(item);
-                application.getRequestedClaims().add(claim);
-            }
-        }
-        return application;
-    }
-    
-    public static RequestClaim entity2domain(ApplicationClaimEntity entity) {
-        Claim claim = ClaimDAOJPAImpl.entity2domain(entity.getClaim());
-        RequestClaim reqClaim = new RequestClaim(claim);
-        reqClaim.setId(entity.getId());
-        reqClaim.setOptional(entity.isOptional());
-        
-        return reqClaim;
-    }
-    
-    public static void domain2entity(ApplicationEntity application,
-                                     RequestClaim reqClaim, ApplicationClaimEntity entity) {
-        //The ID must not be updated if the entity has got an id already (update case)
-        ClaimEntity claim = new ClaimEntity();
-        ClaimDAOJPAImpl.domain2entity(reqClaim, claim);
-        
-        entity.setApplication(application);
-        entity.setClaim(claim);
-        entity.setOptional(reqClaim.isOptional());
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationEntity.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationEntity.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationEntity.java
deleted file mode 100644
index 1397da2..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationEntity.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.persistence.OneToMany;
-import javax.validation.constraints.Min;
-import javax.validation.constraints.NotNull;
-
-import org.apache.openjpa.persistence.jdbc.Index;
-
-
-@Entity(name = "Application")
-public class ApplicationEntity {
-    
-    @Id
-    private int id;
-    
-    @Index
-    @NotNull
-    private String realm;  //wtrealm, whr
-
-    //Could be read from Metadata, RoleDescriptor protocolSupportEnumeration=
-    // "http://docs.oa14sis-open.org/wsfed/federation/200706"
-    // Metadata could provide more than one but one must be chosen
-    @NotNull
-    @ApplicationProtocolSupported
-    private String protocol;
- 
-    // Public key only
-    // Could be read from Metadata, md:KeyDescriptor, use="encryption"
-    private String encryptionCertificate;
-    
-    // Certificate for Signature verification
-    private String validatingCertificate;
-    
-    // Could be read from Metadata, fed:ClaimTypesRequested
-    @OneToMany(mappedBy = "application", cascade = CascadeType.ALL, orphanRemoval = true)
-    private List<ApplicationClaimEntity> requestedClaims = new ArrayList<>();
-    
-    //Could be read from Metadata, ServiceDisplayName
-    //usage for list of application where user is logged in
-    @NotNull
-    private String serviceDisplayName;
-    
-    //Could be read from Metadata, ServiceDescription
-    //usage for list of application where user is logged in
-    private String serviceDescription;
-    
-    //Could be read from Metadata, RoleDescriptor
-    //fed:ApplicationServiceType, fed:SecurityTokenServiceType
-    private String role;
-    
-    // Not in Metadata, configured in IDP or passed in wreq parameter
-    @NotNull
-    private String tokenType;
-    
-    // Not in Metadata, configured in IDP or passed in wreq parameter
-    @Min(value = 1)
-    private int lifeTime;
-    
-    // Request audience restriction in token for this application (default is true)
-    private boolean enableAppliesTo = true;
-    
-    // WS-Policy Namespace in SignIn Response
-    private String policyNamespace;
-    
-    private String passiveRequestorEndpoint;
-    
-    // A regular expression constraint on the passiveRequestorEndpoint
-    private String passiveRequestorEndpointConstraint;
-
-
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }    
-    
-    public String getRealm() {
-        return realm;
-    }
-
-    public void setRealm(String realm) {
-        this.realm = realm;
-    }
-
-    public String getProtocol() {
-        return protocol;
-    }
-
-    public void setProtocol(String protocol) {
-        this.protocol = protocol;
-    }
-
-    public String getEncryptionCertificate() {
-        return encryptionCertificate;
-    }
-
-    public void setEncryptionCertificate(String encryptionCertificate) {
-        this.encryptionCertificate = encryptionCertificate;
-    }
-
-    public List<ApplicationClaimEntity> getRequestedClaims() {
-        return requestedClaims;
-    }
-
-    public void setRequestedClaims(List<ApplicationClaimEntity> requestedClaims) {
-        this.requestedClaims = requestedClaims;
-    }
-
-    public String getServiceDisplayName() {
-        return serviceDisplayName;
-    }
-
-    public void setServiceDisplayName(String serviceDisplayName) {
-        this.serviceDisplayName = serviceDisplayName;
-    }
-
-    public String getServiceDescription() {
-        return serviceDescription;
-    }
-
-    public void setServiceDescription(String serviceDescription) {
-        this.serviceDescription = serviceDescription;
-    }
-
-    public String getRole() {
-        return role;
-    }
-
-    public void setRole(String role) {
-        this.role = role;
-    }
-
-    public String getTokenType() {
-        return tokenType;
-    }
-
-    public void setTokenType(String tokenType) {
-        this.tokenType = tokenType;
-    }
-
-    public int getLifeTime() {
-        return lifeTime;
-    }
-
-    public void setLifeTime(int lifeTime) {
-        this.lifeTime = lifeTime;
-    }
-    
-    public String getPolicyNamespace() {
-        return policyNamespace;
-    }
-
-    public void setPolicyNamespace(String policyNamespace) {
-        this.policyNamespace = policyNamespace;
-    }
-
-    public String getPassiveRequestorEndpoint() {
-        return passiveRequestorEndpoint;
-    }
-
-    public void setPassiveRequestorEndpoint(String passiveRequestorEndpoint) {
-        this.passiveRequestorEndpoint = passiveRequestorEndpoint;
-    }
-    
-    public String getPassiveRequestorEndpointConstraint() {
-        return passiveRequestorEndpointConstraint;
-    }
-
-    public void setPassiveRequestorEndpointConstraint(String passiveRequestorEndpointConstraint) {
-        this.passiveRequestorEndpointConstraint = passiveRequestorEndpointConstraint;
-    }
-
-    public String getValidatingCertificate() {
-        return validatingCertificate;
-    }
-
-    public void setValidatingCertificate(String validatingCertificate) {
-        this.validatingCertificate = validatingCertificate;
-    }
-
-    public boolean isEnableAppliesTo() {
-        return enableAppliesTo;
-    }
-
-    public void setEnableAppliesTo(boolean enableAppliesTo) {
-        this.enableAppliesTo = enableAppliesTo;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationIdpProtocolSupportValidator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationIdpProtocolSupportValidator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationIdpProtocolSupportValidator.java
deleted file mode 100644
index 5a999e9..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationIdpProtocolSupportValidator.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.List;
-
-import javax.validation.ConstraintValidator;
-import javax.validation.ConstraintValidatorContext;
-
-import org.apache.cxf.fediz.service.idp.protocols.ProtocolController;
-import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.stereotype.Component;
-
-/**
- * Validate that the protocol is a valid Application protocol
- */
-@Component
-public class ApplicationIdpProtocolSupportValidator
-    implements ConstraintValidator<ApplicationProtocolSupported, String> {
-
-    @Autowired
-    @Qualifier("applicationProtocolControllerImpl")
-    private ProtocolController<ApplicationProtocolHandler> applicationProtocolHandlers;
-    
-    @Override
-    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
-        
-        List<String> protocols = applicationProtocolHandlers.getProtocols();
-        return protocols.contains(object);
-    }
-
-    @Override
-    public void initialize(ApplicationProtocolSupported constraintAnnotation) {
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationProtocolSupported.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationProtocolSupported.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationProtocolSupported.java
deleted file mode 100644
index 6dc69a5..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationProtocolSupported.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.lang.annotation.Documented;
-import java.lang.annotation.Retention;
-import java.lang.annotation.Target;
-
-import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
-import static java.lang.annotation.ElementType.FIELD;
-import static java.lang.annotation.ElementType.METHOD;
-
-import static java.lang.annotation.RetentionPolicy.RUNTIME;
-
-import javax.validation.Constraint;
-import javax.validation.Payload;
-
-@Target({ METHOD, FIELD, ANNOTATION_TYPE })
-@Retention(RUNTIME)
-@Constraint(validatedBy = ApplicationIdpProtocolSupportValidator.class)
-@Documented
-public @interface ApplicationProtocolSupported {
-
-    String message() default "{Protocol not supported}";
-
-    Class<?>[] groups() default { };
-
-    Class<? extends Payload>[] payload() default { };
-
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPAImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPAImpl.java
deleted file mode 100644
index dea2b8d..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPAImpl.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.Query;
-
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Repository;
-import org.springframework.transaction.annotation.Transactional;
-
-
-@Repository
-@Transactional
-public class ClaimDAOJPAImpl implements ClaimDAO {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(ClaimDAOJPAImpl.class);
-
-    private EntityManager em;
-    
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-    
-    @Override
-    public List<Claim> getClaims(int start, int size) {
-        List<Claim> list = new ArrayList<>();
-        
-        Query query = null;
-        query = em.createQuery("select c from Claim c");
-        
-        //@SuppressWarnings("rawtypes")
-        List<?> claimEntities = query
-            .setFirstResult(start)
-            .setMaxResults(size)
-            .getResultList();
-
-        for (Object obj : claimEntities) {
-            ClaimEntity entity = (ClaimEntity) obj;
-            list.add(entity2domain(entity));
-        }
-        
-        return list;
-    }
-    
-    @Override
-    public Claim addClaim(Claim claim) {
-        ClaimEntity entity = new ClaimEntity();
-        domain2entity(claim, entity);
-        em.persist(entity);
-        
-        LOG.debug("Claim '{}' added", claim.getClaimType());
-        return entity2domain(entity);
-    }
-
-    @Override
-    public Claim getClaim(String claimType) {
-        return entity2domain(getClaimEntity(claimType, em));
-    }
-
-    @Override
-    public void updateClaim(String claimType, Claim claim) {
-        Query query = null;
-        query = em.createQuery("select c from Claim c where c.claimtype=:claimtype");
-        query.setParameter("claimtype", claimType);
-        
-        //@SuppressWarnings("rawtypes")
-        ClaimEntity claimEntity = (ClaimEntity)query.getSingleResult();
-        
-        domain2entity(claim, claimEntity);
-        
-        LOG.debug("Claim '{}' added", claim.getClaimType());
-        em.persist(claimEntity);
-    }
-
-    @Override
-    public void deleteClaim(String claimType) {
-        Query query = null;
-        query = em.createQuery("select c from Claim c where c.claimType=:claimtype");
-        query.setParameter("claimtype", claimType);
-        
-        //@SuppressWarnings("rawtypes")
-        Object claimObj = query.getSingleResult();
-        em.remove(claimObj);
-        
-        LOG.debug("Claim '{}' deleted", claimType);
-    }
-    
-    static ClaimEntity getClaimEntity(String claimType, EntityManager em) {
-        Query query = null;
-        query = em.createQuery("select c from Claim c where c.claimType=:claimtype");
-        query.setParameter("claimtype", claimType);
-        
-        //@SuppressWarnings("rawtypes")
-        return (ClaimEntity)query.getSingleResult();
-    }
-    
-    public static void domain2entity(Claim claim, ClaimEntity entity) {
-        //The ID must not be updated if the entity has got an id already (update case)
-        if (claim.getId() > 0) {
-            entity.setId(claim.getId());
-        }
-        entity.setClaimType(claim.getClaimType().toString());
-        entity.setDisplayName(claim.getDisplayName());
-        entity.setDescription(claim.getDescription());
-    }
-    
-    public static Claim entity2domain(ClaimEntity entity) {
-        Claim claim = new Claim();
-        claim.setId(entity.getId());
-        claim.setClaimType(URI.create(entity.getClaimType()));
-        claim.setDisplayName(entity.getDisplayName());
-        claim.setDescription(entity.getDescription());
-        return claim;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimEntity.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimEntity.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimEntity.java
deleted file mode 100644
index 54ee1eb..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimEntity.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import javax.persistence.Entity;
-import javax.persistence.Id;
-import javax.validation.constraints.NotNull;
-
-import org.apache.openjpa.persistence.jdbc.Index;
-
-@Entity(name = "Claim")
-public class ClaimEntity {
-    
-    @Id
-    private int id;
-    
-    @Index
-    @NotNull
-    private String claimType;
-    
-    private String displayName;
-    private String description;
-        
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    public void setClaimType(String claimType) {
-        this.claimType = claimType;
-    }
-    
-    public String getClaimType() {
-        return claimType;
-    }
-
-    public String getDisplayName() {
-        return displayName;
-    }
-
-    public void setDisplayName(String displayName) {
-        this.displayName = displayName;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ConfigServiceJPA.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ConfigServiceJPA.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ConfigServiceJPA.java
deleted file mode 100644
index 03f70b9..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ConfigServiceJPA.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.rest.IdpService;
-import org.apache.cxf.fediz.service.idp.service.ConfigService;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
-import org.springframework.security.core.context.SecurityContextHolder;
-
-
-public class ConfigServiceJPA implements ConfigService {
-
-    private static final Logger LOG = LoggerFactory.getLogger(ConfigServiceJPA.class);
-    
-    IdpService idpService;
-
-    @Override
-    public Idp getIDP(String realm) {
-        Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
-        try {
-            final Set<GrantedAuthority> authorities = new HashSet<>();
-            
-            if (realm == null || realm.length() == 0) {
-                authorities.add(new SimpleGrantedAuthority("IDP_LIST"));
-                UsernamePasswordAuthenticationToken technicalUser =
-                    new UsernamePasswordAuthenticationToken("IDP_TEST", "N.A", authorities);
-                
-                SecurityContextHolder.getContext().setAuthentication(technicalUser);
-                
-                return idpService.getIdps(0, 1, Arrays.asList("all"), null).getIdps().iterator().next();
-            } else {
-                authorities.add(new SimpleGrantedAuthority("IDP_READ"));
-                UsernamePasswordAuthenticationToken technicalUser =
-                    new UsernamePasswordAuthenticationToken("IDP_TEST", "N.A", authorities);
-                
-                SecurityContextHolder.getContext().setAuthentication(technicalUser);
-                
-                return idpService.getIdp(realm, Arrays.asList("all"));
-            }
-        } finally {
-            SecurityContextHolder.getContext().setAuthentication(currentAuthentication);
-            LOG.info("Old Spring security context restored");
-        }
-    }
-
-    @Override
-    public void setIDP(Idp config) {
-        // TODO Auto-generated method stub
-        
-    }
-
-    @Override
-    public void removeIDP(String realm) {
-        // TODO Auto-generated method stub
-        
-    }
-
-    public IdpService getIdpService() {
-        return idpService;
-    }
-
-    public void setIdpService(IdpService idpService) {
-        this.idpService = idpService;
-    }
-    
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBInitApplicationListener.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBInitApplicationListener.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBInitApplicationListener.java
deleted file mode 100644
index eebb99a..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBInitApplicationListener.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.List;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.ApplicationListener;
-import org.springframework.context.event.ContextRefreshedEvent;
-import org.springframework.stereotype.Component;
-
-@Component
-public class DBInitApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
-
-    private static final Logger LOG = LoggerFactory.getLogger(DBInitApplicationListener.class);
-    
-    private EntityManager em;
-    
-    @Autowired
-    private List<DBLoader> dbloader;
-    
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-        
-    @Override
-    public void onApplicationEvent(ContextRefreshedEvent arg0) {
-        if (!isDBEmpty()) {
-            LOG.info("Inital DB already loaded");
-            return;
-        }
-        
-        LOG.debug("Loading inital DB data...");
-        for (DBLoader loader : this.dbloader) {
-            loader.load();
-            LOG.info("Inital DB data loaded for " + loader.getName());
-        }
-    }
-    
-    protected boolean isDBEmpty() {
-        CriteriaBuilder cb = em.getCriteriaBuilder();
-        CriteriaQuery<Long> cq = cb.createQuery(Long.class);
-        cq.select(cb.count(cq.from(ClaimEntity.class)));
-
-        return em.createQuery(cq).getSingleResult() == 0;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoader.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoader.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoader.java
deleted file mode 100644
index c79a79b..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoader.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-public interface DBLoader {
-
-    void load();
-    
-    String getName();
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderImpl.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderImpl.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderImpl.java
deleted file mode 100644
index 2c6ab15..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderImpl.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-
-import org.apache.cxf.fediz.service.idp.domain.FederationType;
-import org.apache.cxf.fediz.service.idp.domain.TrustType;
-import org.apache.wss4j.dom.WSConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional
-//CHECKSTYLE:OFF
-public class DBLoaderImpl implements DBLoader {
-    
-    public static final String NAME = "DEMODBLOADER";
-    
-    private static final Logger LOG = LoggerFactory.getLogger(DBLoaderImpl.class);
-    
-    private EntityManager em;
-
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-    
-    @Override
-    public String getName() {
-        return NAME;
-    }
-    
-    @Override
-    public void load() {
-
-        try {
-            ClaimEntity claimEntity1 = new ClaimEntity();
-            claimEntity1.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname");
-            claimEntity1.setDisplayName("firstname");
-            claimEntity1.setDescription("Description for firstname");
-            em.persist(claimEntity1);
-    
-            ClaimEntity claimEntity2 = new ClaimEntity();
-            claimEntity2.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname");
-            claimEntity2.setDisplayName("lastname");
-            claimEntity2.setDescription("Description for lastname");
-            em.persist(claimEntity2);
-    
-            ClaimEntity claimEntity3 = new ClaimEntity();
-            claimEntity3.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress");
-            claimEntity3.setDisplayName("email");
-            claimEntity3.setDescription("Description for email");
-            em.persist(claimEntity3);
-    
-            ClaimEntity claimEntity4 = new ClaimEntity();
-            claimEntity4.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role");
-            claimEntity4.setDisplayName("role");
-            claimEntity4.setDescription("Description for role");
-            em.persist(claimEntity4);
-            
-            
-            ApplicationEntity entity = new ApplicationEntity();
-            entity.setEncryptionCertificate("");
-            entity.setLifeTime(3600);
-            entity.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-            entity.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
-            entity.setRole("ApplicationServiceType");
-            entity.setServiceDescription("Web Application to illustrate WS-Federation");
-            entity.setServiceDisplayName("Fedizhelloworld");
-            entity.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
-            // must be persistet here already as the ApplicationClaimEntity requires the Application Id
-            em.persist(entity);
-            ApplicationClaimEntity ace1 = new ApplicationClaimEntity(entity, claimEntity1);
-            ace1.setOptional(true);
-            em.persist(ace1);
-            entity.getRequestedClaims().add(ace1);
-            ApplicationClaimEntity ace2 = new ApplicationClaimEntity(entity, claimEntity2);
-            ace2.setOptional(true);
-            em.persist(ace2);
-            entity.getRequestedClaims().add(ace2);
-            ApplicationClaimEntity ace3 = new ApplicationClaimEntity(entity, claimEntity3);
-            ace3.setOptional(true);
-            em.persist(ace3);
-            entity.getRequestedClaims().add(ace3);
-            ApplicationClaimEntity ace4 = new ApplicationClaimEntity(entity, claimEntity4);
-            ace4.setOptional(false);
-            em.persist(ace4);
-            entity.getRequestedClaims().add(ace4);
-            em.persist(entity);
-            
-            
-            TrustedIdpEntity entity3 = new TrustedIdpEntity();
-            entity3.setCacheTokens(true);
-            entity3.setCertificate("trusted cert");
-            entity3.setDescription("Realm B description");
-            entity3.setFederationType(FederationType.FEDERATE_IDENTITY);
-            entity3.setName("Realm B");
-            entity3.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
-            entity3.setRealm("urn:org:apache:cxf:fediz:idp:realm-B");
-            entity3.setTrustType(TrustType.PEER_TRUST);
-            entity3.setUrl("https://localhost:12443/fediz-idp-remote/federation");
-            em.persist(entity3);
-            
-            IdpEntity idpEntity = new IdpEntity();
-            idpEntity.getApplications().add(entity);
-            idpEntity.getTrustedIdps().add(entity3);
-            idpEntity.setCertificate("stsKeystoreA.properties");
-            idpEntity.setCertificatePassword("realma");
-            idpEntity.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federation"));
-            idpEntity.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
-            idpEntity.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMA"));
-            idpEntity.setServiceDisplayName("REALM A");
-            idpEntity.setServiceDescription("IDP of Realm A");
-            idpEntity.setUri("realma");
-            idpEntity.setProvideIdpList(true);
-            Map<String, String> authUris = new HashMap<>();
-            authUris.put("default", "/login/default");
-            idpEntity.setAuthenticationURIs(authUris);
-            List<String> protocols = new ArrayList<>();
-            protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
-            protocols.add("http://docs.oasis-open.org/ws-sx/ws-trust/200512");
-            idpEntity.setSupportedProtocols(protocols);
-            idpEntity.getClaimTypesOffered().add(claimEntity1);
-            idpEntity.getClaimTypesOffered().add(claimEntity2);
-            idpEntity.getClaimTypesOffered().add(claimEntity3);
-            idpEntity.getClaimTypesOffered().add(claimEntity4);
-            List<String> tokenTypes = new ArrayList<>();
-            tokenTypes.add(WSConstants.SAML2_NS);
-            tokenTypes.add(WSConstants.SAML_NS);
-            idpEntity.setTokenTypesOffered(tokenTypes);
-            idpEntity.setUseCurrentIdp(true);
-            em.persist(idpEntity);
-            
-            em.flush();
-        } catch (Exception ex) {
-            LOG.warn("Failed to initialize DB with data", ex);
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderSpring.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderSpring.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderSpring.java
deleted file mode 100644
index eb0fa40..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/DBLoaderSpring.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
-
-import java.util.Collection;
-
-import javax.persistence.EntityManager;
-import javax.persistence.PersistenceContext;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.context.support.GenericXmlApplicationContext;
-import org.springframework.transaction.annotation.Transactional;
-
-@Transactional
-public class DBLoaderSpring implements DBLoader {
-    
-    public static final String NAME = "SPRINGDBLOADER";
-    
-    private static final Logger LOG = LoggerFactory.getLogger(DBLoaderSpring.class);
-    
-    private EntityManager em;
-    private String resource;
-
-    @PersistenceContext
-    public void setEntityManager(EntityManager entityManager) {
-        this.em = entityManager;
-    }
-    
-    @Override
-    public String getName() {
-        return NAME;
-    }
-    
-    public String getResource() {
-        return resource;
-    }
-
-    public void setResource(String resource) {
-        this.resource = resource;
-    }
-
-    @Override
-    public void load() {
-
-        GenericXmlApplicationContext ctx = null;
-        try {
-            
-            if (resource == null) {
-                LOG.warn("Resource null for DBLoaderSpring");
-            }
-            
-            ctx = new GenericXmlApplicationContext();
-            ctx.load(resource);
-            ctx.refresh();
-            ctx.start();
-            
-            Collection<EntitlementEntity> entitlements = ctx.
-                getBeansOfType(EntitlementEntity.class, true, true).values();
-            for (EntitlementEntity e : entitlements) {
-                em.persist(e);
-            }
-            LOG.info(entitlements.size() + " EntitlementEntity added");
-            
-            Collection<RoleEntity> roles = ctx.
-                getBeansOfType(RoleEntity.class, true, true).values();
-            for (RoleEntity r : roles) {
-                em.persist(r);
-            }
-            LOG.info(roles.size() + " RoleEntity added");
-            
-            Collection<ClaimEntity> claims = ctx.getBeansOfType(ClaimEntity.class, true, true).values();
-            for (ClaimEntity c : claims) {
-                em.persist(c);
-            }
-            LOG.info(claims.size() + " ClaimEntity added");
-            
-            Collection<TrustedIdpEntity> trustedIdps = ctx.getBeansOfType(TrustedIdpEntity.class).values();
-            for (TrustedIdpEntity t : trustedIdps) {
-                em.persist(t);
-            }
-            LOG.info(trustedIdps.size() + " TrustedIdpEntity added");
-            
-            Collection<ApplicationEntity> applications = ctx.getBeansOfType(ApplicationEntity.class).values();
-            for (ApplicationEntity a : applications) {
-                em.persist(a);
-            }
-            LOG.info(applications.size() + " ApplicationEntity added");
-            
-            Collection<IdpEntity> idps = ctx.getBeansOfType(IdpEntity.class).values();
-            for (IdpEntity i : idps) {
-                em.persist(i);
-            }
-            LOG.info(idps.size() + " IdpEntity added");
-            
-            Collection<ApplicationClaimEntity> applicationClaims =
-                ctx.getBeansOfType(ApplicationClaimEntity.class).values();
-            for (ApplicationClaimEntity ac : applicationClaims) {
-                em.persist(ac);
-            }
-            LOG.info(applicationClaims.size() + " ApplicationClaimEntity added");
-            
-            em.flush();
-        } catch (Exception ex) {
-            LOG.warn("Failed to initialize DB with data", ex);
-        } finally {
-            if (ctx != null) {
-                ctx.close();
-            }
-        }
-    }
-
-}


[13/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
new file mode 100644
index 0000000..27d498c
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleService.java
@@ -0,0 +1,88 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.List;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+import org.apache.cxf.fediz.service.idp.domain.Role;
+
+import org.springframework.security.access.prepost.PreAuthorize;
+
+
+@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Path("roles")
+public interface RoleService {
+
+    @GET
+    @PreAuthorize("hasRole('ROLE_LIST')")
+    Roles getRoles(@QueryParam("start") int start,
+                                 @QueryParam("size") @DefaultValue("2") int size,
+                                 @QueryParam("expand") @DefaultValue("all")  List<String> expand,
+                                 @Context UriInfo uriInfo);
+
+    @GET
+    @Path("{name}")
+    @PreAuthorize("hasRole('ROLE_CREATE')")
+    Role getRole(@PathParam("name") String realm,
+                               @QueryParam("expand") @DefaultValue("all")  List<String> expand);
+
+    @POST
+    @PreAuthorize("hasRole('ROLE_CREATE')")
+    Response addRole(@Context UriInfo ui, Role role);
+    
+    @PUT
+    @Path("{name}")
+    @PreAuthorize("hasRole('ROLE_UPDATE')")
+    Response updateRole(@Context UriInfo ui, @PathParam("name") String name, Role role);
+    
+    @DELETE
+    @Path("{name}")
+    @PreAuthorize("hasRole('ROLE_DELETE')")
+    Response deleteRole(@PathParam("name") String name);
+    
+    @POST
+    @Path("{name}/entitlements")
+    @PreAuthorize("hasRole('ROLE_UPDATE')")
+    Response addEntitlementToRole(@Context UriInfo ui, @PathParam("name") String name, Entitlement entitlement);
+    
+    @DELETE
+    @Path("{name}/entitlements/{entitlementName}")
+    @PreAuthorize("hasRole('ROLE_UPDATE')")
+    Response removeEntitlementFromRole(@Context UriInfo ui, @PathParam("name") String name,
+                                        @PathParam("entitlementName") String entitlementName);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
new file mode 100644
index 0000000..24ff339
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RoleServiceImpl.java
@@ -0,0 +1,134 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.net.URI;
+import java.util.List;
+
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.UriBuilder;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+import org.apache.cxf.fediz.service.idp.domain.Role;
+import org.apache.cxf.fediz.service.idp.service.EntitlementDAO;
+import org.apache.cxf.fediz.service.idp.service.RoleDAO;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class RoleServiceImpl implements RoleService {
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(RoleServiceImpl.class);
+
+    @Autowired
+    private RoleDAO roleDAO;
+    
+    @Autowired
+    private EntitlementDAO entitlementDAO;
+           
+    @Override
+    public Roles getRoles(int start, int size, List<String> expand, UriInfo uriInfo) {
+        List<Role> roles = roleDAO.getRoles(start, size, expand);
+        
+        Roles list = new Roles();
+        list.setRoles(roles);
+        return list;
+    }
+    
+    @Override
+    public Role getRole(String name, List<String> expand) {
+        Role role = roleDAO.getRole(name, expand);
+        if (role == null) {
+            throw new NotFoundException();
+        } else {
+            return role;
+        }
+    }
+    
+    @Override
+    public Response addRole(UriInfo ui, Role role) {
+        if (role.getEntitlements() != null && role.getEntitlements().size() > 0) {
+            LOG.warn("Role resource contains sub resource 'entitlements'");
+            throw new WebApplicationException(Status.BAD_REQUEST);
+        }
+        Role createdRole = roleDAO.addRole(role);
+        
+        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
+        uriBuilder.path("{index}");
+        URI location = uriBuilder.build(createdRole.getName());
+        
+        LOG.debug("Role '" + role.getName() + "' added");
+        return Response.created(location).entity(role).build();
+    }
+    
+    @Override
+    public Response updateRole(UriInfo ui, String name, Role role) {
+        if (!name.equals(role.getName().toString())) {
+            throw new BadRequestException();
+        }
+        if (role.getEntitlements() != null && role.getEntitlements().size() > 0) {
+            LOG.warn("Role resource contains sub resource 'entitlements'");
+            throw new WebApplicationException(Status.BAD_REQUEST);
+        }
+        roleDAO.updateRole(name, role);
+        
+        LOG.debug("Role '" + role.getName() + "' updated");
+        return Response.noContent().build();
+    }
+ 
+    @Override
+    public Response deleteRole(String name) {
+        roleDAO.deleteRole(name);
+        
+        LOG.debug("Role '" + name + "' deleted");
+        return Response.noContent().build();
+    }
+    
+    @Override
+    public Response addEntitlementToRole(UriInfo ui, String name, Entitlement entitlement) {
+        Role role = roleDAO.getRole(name, null);
+        
+        Entitlement foundEntitlement = entitlementDAO.getEntitlement(entitlement.getName());
+        roleDAO.addEntitlementToRole(role, foundEntitlement);
+        
+        LOG.debug("Entitlement '" + entitlement.getName() + "' added to Role '" + name + "'");
+        return Response.noContent().build();
+    }
+    
+    @Override
+    public Response removeEntitlementFromRole(UriInfo ui, String name, String entitlementName) {
+        Role role = roleDAO.getRole(name, null);
+        Entitlement entitlement = entitlementDAO.getEntitlement(entitlementName);
+        
+        roleDAO.removeEntitlementFromRole(role, entitlement);
+        
+        LOG.debug("Entitlement '" + entitlementName + "' removed from Role '" + name + "'");
+        return Response.noContent().build();
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java
new file mode 100644
index 0000000..6ecd2f2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Roles.java
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.Collection;
+
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.cxf.fediz.service.idp.domain.Role;
+
+@XmlRootElement(name = "roles", namespace = "http://org.apache.cxf.fediz/")
+public class Roles {
+
+    private Collection<Role> roles;
+
+    public Roles() {
+    }
+
+    public Roles(Collection<Role> roles) {
+        this.roles = roles;
+    }
+
+    @XmlElementRef
+    public Collection<Role> getRoles() {
+        return roles;
+    }
+
+    public void setRoles(Collection<Role> roles) {
+        this.roles = roles;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootService.java
new file mode 100644
index 0000000..86d8a3b
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootService.java
@@ -0,0 +1,39 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.HEAD;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+
+@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+public interface RootService {
+
+    @HEAD
+    Response head(@Context UriInfo uriInfo);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
new file mode 100644
index 0000000..03eb6da
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RootServiceImpl.java
@@ -0,0 +1,60 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.net.URI;
+
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+import javax.ws.rs.core.UriInfo;
+
+
+public class RootServiceImpl implements RootService {
+
+    public RootServiceImpl() {
+    }
+    
+    public Response head(UriInfo uriInfo) {
+        UriBuilder absolute = uriInfo.getBaseUriBuilder();
+        URI claimUrl = absolute.clone().path("claims").build();
+        URI idpUrl = absolute.clone().path("idps").build();
+        URI applicationUrl = absolute.clone().path("applications").build();
+        URI trustedIdpUrl = absolute.clone().path("trusted-idps").build();
+        URI rolesUrl = absolute.clone().path("roles").build();
+        URI entitlementsUrl = absolute.clone().path("entitlements").build();
+        javax.ws.rs.core.Link claims = javax.ws.rs.core.Link.fromUri(claimUrl).rel("claims")
+            .type("application/xml").build();
+        javax.ws.rs.core.Link idps = javax.ws.rs.core.Link.fromUri(idpUrl).rel("idps")
+            .type("application/xml").build();
+        javax.ws.rs.core.Link applications = javax.ws.rs.core.Link.fromUri(applicationUrl).rel("applications")
+            .type("application/xml").build();
+        javax.ws.rs.core.Link trustedIdps = javax.ws.rs.core.Link.fromUri(trustedIdpUrl).rel("trusted-idps")
+            .type("application/xml").build();
+        javax.ws.rs.core.Link roles = javax.ws.rs.core.Link.fromUri(rolesUrl).rel("roles")
+            .type("application/xml").build();
+        javax.ws.rs.core.Link entitlements = javax.ws.rs.core.Link.fromUri(entitlementsUrl).rel("entitlements")
+            .type("application/xml").build();
+
+        Response.ResponseBuilder builder = Response.ok().links(
+            claims, idps, applications, trustedIdps, roles, entitlements);
+        return builder.build();
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
new file mode 100644
index 0000000..b76d91d
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpService.java
@@ -0,0 +1,71 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+
+import org.springframework.security.access.prepost.PreAuthorize;
+
+@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Path("trusted-idps")
+public interface TrustedIdpService {
+
+    @GET
+    @PreAuthorize("hasRole('TRUSTEDIDP_LIST')")
+    TrustedIdps getTrustedIDPs(@QueryParam("start") int start,
+                               @QueryParam("size") @DefaultValue("2") int size,
+                               @Context UriInfo uriInfo);
+
+    @GET
+    @Path("{realm}")
+    @PreAuthorize("hasRole('TRUSTEDIDP_READ')")
+    TrustedIdp getTrustedIDP(@PathParam("realm") String realm);
+
+    @POST
+    @PreAuthorize("hasRole('TRUSTEDIDP_CREATE')")
+    Response addTrustedIDP(@Context UriInfo ui, TrustedIdp trustedIdp);
+    
+    @PUT
+    @Path("{realm}")
+    @PreAuthorize("hasRole('TRUSTEDIDP_UPDATE')")
+    Response updateTrustedIDP(@Context UriInfo ui, @PathParam("realm") String realm, TrustedIdp trustedIdp);
+    
+    @DELETE
+    @Path("{realm}")
+    @PreAuthorize("hasRole('TRUSTEDIDP_DELETE')")
+    Response deleteTrustedIDP(@PathParam("realm") String realm);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpServiceImpl.java
new file mode 100644
index 0000000..e01c80b
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdpServiceImpl.java
@@ -0,0 +1,93 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.net.URI;
+import java.util.List;
+
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.service.TrustedIdpDAO;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class TrustedIdpServiceImpl implements TrustedIdpService {
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(TrustedIdpServiceImpl.class);
+
+    @Autowired
+    private TrustedIdpDAO trustedIdpDAO;
+    
+    
+    @Override
+    public Response updateTrustedIDP(UriInfo ui, String realm, TrustedIdp trustedIdp) {
+        if (!realm.equals(trustedIdp.getRealm().toString())) {
+            throw new BadRequestException();
+        }
+        trustedIdpDAO.updateTrustedIDP(realm, trustedIdp);
+        
+        return Response.noContent().build();
+    }
+    
+    @Override
+    public TrustedIdps getTrustedIDPs(int start, int size, UriInfo uriInfo) {
+        List<TrustedIdp> trustedIdps = trustedIdpDAO.getTrustedIDPs(start, size);
+        
+        TrustedIdps list = new TrustedIdps();
+        list.setTrustedIDPs(trustedIdps);
+        return list;
+    }
+    
+    @Override
+    public TrustedIdp getTrustedIDP(String realm) {
+        return this.trustedIdpDAO.getTrustedIDP(realm);
+    }
+    
+    @Override
+    public Response addTrustedIDP(UriInfo ui, TrustedIdp trustedIDP) {
+        LOG.info("add Trusted IDP config");
+        
+        TrustedIdp createdTrustedIdp = trustedIdpDAO.addTrustedIDP(trustedIDP);
+        
+        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
+        uriBuilder.path("{index}");
+        URI location = uriBuilder.build(createdTrustedIdp.getRealm());
+        return Response.created(location).entity(trustedIDP).build();
+    }
+
+    @Override
+    public Response deleteTrustedIDP(String realm) {
+        trustedIdpDAO.deleteTrustedIDP(realm);
+        
+        return Response.noContent().build();
+    }
+           
+    
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdps.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdps.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdps.java
new file mode 100644
index 0000000..ea57acd
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/TrustedIdps.java
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.Collection;
+
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+
+@XmlRootElement(name = "trustedIdps", namespace = "http://org.apache.cxf.fediz/")
+public class TrustedIdps {
+
+    private Collection<TrustedIdp> trustedIDPs;
+
+    public TrustedIdps() {
+    }
+
+    public TrustedIdps(Collection<TrustedIdp> trustedIDPs) {
+        this.trustedIDPs = trustedIDPs;
+    }
+
+    @XmlElementRef
+    public Collection<TrustedIdp> getTrustedIDPs() {
+        return trustedIDPs;
+    }
+
+    public void setTrustedIDPs(Collection<TrustedIdp> trustedIDPs) {
+        this.trustedIDPs = trustedIDPs;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
new file mode 100644
index 0000000..9981253
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2CallbackHandler.java
@@ -0,0 +1,148 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.samlsso;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import org.apache.wss4j.common.saml.SAMLCallback;
+import org.apache.wss4j.common.saml.bean.AttributeBean;
+import org.apache.wss4j.common.saml.bean.AttributeStatementBean;
+import org.apache.wss4j.common.saml.bean.AuthenticationStatementBean;
+import org.apache.wss4j.common.saml.bean.ConditionsBean;
+import org.apache.wss4j.common.saml.bean.SubjectBean;
+import org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean;
+import org.apache.wss4j.common.saml.bean.Version;
+import org.apache.wss4j.common.saml.builder.SAML2Constants;
+import org.opensaml.core.xml.XMLObject;
+import org.opensaml.saml.saml2.core.Attribute;
+import org.opensaml.saml.saml2.core.AttributeStatement;
+import org.opensaml.saml.saml2.core.Subject;
+
+/**
+ * A Callback Handler implementation for a SAML 2 assertion. By default it creates a SAML 2.0 Assertion with
+ * an AuthenticationStatement. If a list of AttributeStatements are also supplied it will insert them into the
+ * Assertion.
+ */
+public class SAML2CallbackHandler implements CallbackHandler {
+    
+    private Subject subject;
+    private String confirmationMethod = SAML2Constants.CONF_BEARER;
+    private String issuer;
+    private ConditionsBean conditions;
+    private SubjectConfirmationDataBean subjectConfirmationData;
+    private List<AttributeStatement> attributeStatements;
+    
+    private void createAndSetStatement(SAMLCallback callback) {
+        AuthenticationStatementBean authBean = new AuthenticationStatementBean();
+        authBean.setAuthenticationMethod("Password");
+        callback.setAuthenticationStatementData(Collections.singletonList(authBean));
+
+        if (attributeStatements != null && !attributeStatements.isEmpty()) {
+            List<AttributeStatementBean> attrStatementBeans = new ArrayList<>();
+            
+            for (AttributeStatement attrStatement : attributeStatements) {
+                AttributeStatementBean attrStatementBean = new AttributeStatementBean();
+                List<AttributeBean> attrBeans = new ArrayList<>();
+                
+                for (Attribute attribute : attrStatement.getAttributes()) {
+                    AttributeBean attributeBean = new AttributeBean();
+                    attributeBean.setQualifiedName(attribute.getName());
+                    attributeBean.setNameFormat(attribute.getNameFormat());
+                    List<Object> attributeValues = new ArrayList<>();
+                    for (XMLObject attrVal : attribute.getAttributeValues()) {
+                        attributeValues.add(attrVal.getDOM().getTextContent());
+                    }
+                    attributeBean.setAttributeValues(attributeValues);
+                    attrBeans.add(attributeBean);
+                }
+                attrStatementBean.setSamlAttributes(attrBeans);
+                attrStatementBeans.add(attrStatementBean);
+            }
+            callback.setAttributeStatementData(attrStatementBeans);
+        }
+    }
+    
+    public void handle(Callback[] callbacks)
+        throws IOException, UnsupportedCallbackException {
+        for (int i = 0; i < callbacks.length; i++) {
+            if (callbacks[i] instanceof SAMLCallback) {
+                SAMLCallback callback = (SAMLCallback) callbacks[i];
+                callback.setSamlVersion(Version.SAML_20);
+                callback.setIssuer(issuer);
+                if (conditions != null) {
+                    callback.setConditions(conditions);
+                }
+                
+                SubjectBean subjectBean = 
+                    new SubjectBean(
+                        subject.getNameID().getValue(), subject.getNameID().getNameQualifier(), confirmationMethod
+                    );
+                subjectBean.setSubjectNameIDFormat(subject.getNameID().getFormat());
+                subjectBean.setSubjectConfirmationData(subjectConfirmationData);
+
+                callback.setSubject(subjectBean);
+                createAndSetStatement(callback);
+            } else {
+                throw new UnsupportedCallbackException(callbacks[i], "Unrecognized Callback");
+            }
+        }
+    }
+    
+    public void setSubjectConfirmationData(SubjectConfirmationDataBean subjectConfirmationData) {
+        this.subjectConfirmationData = subjectConfirmationData;
+    }
+    
+    public void setConditions(ConditionsBean conditionsBean) {
+        this.conditions = conditionsBean;
+    }
+    
+    public void setConfirmationMethod(String confMethod) {
+        confirmationMethod = confMethod;
+    }
+    
+    public void setIssuer(String issuer) {
+        this.issuer = issuer;
+    }
+
+    public Subject getSubject() {
+        return subject;
+    }
+
+    public void setSubject(Subject subject) {
+        this.subject = subject;
+    }
+
+    public List<AttributeStatement> getAttributeStatements() {
+        return attributeStatements;
+    }
+
+    public void setAttributeStatements(List<AttributeStatement> attributeStatements) {
+        this.attributeStatements = attributeStatements;
+    }
+    
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2PResponseComponentBuilder.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2PResponseComponentBuilder.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2PResponseComponentBuilder.java
new file mode 100644
index 0000000..7e64cfa
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAML2PResponseComponentBuilder.java
@@ -0,0 +1,127 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.samlsso;
+
+import java.util.UUID;
+
+import org.joda.time.DateTime;
+import org.opensaml.core.xml.XMLObjectBuilderFactory;
+import org.opensaml.core.xml.config.XMLObjectProviderRegistrySupport;
+import org.opensaml.saml.common.SAMLObjectBuilder;
+import org.opensaml.saml.common.SAMLVersion;
+import org.opensaml.saml.saml2.core.Issuer;
+import org.opensaml.saml.saml2.core.Response;
+import org.opensaml.saml.saml2.core.Status;
+import org.opensaml.saml.saml2.core.StatusCode;
+import org.opensaml.saml.saml2.core.StatusMessage;
+
+/**
+* A (basic) set of utility methods to construct SAML 2.0 Protocol Response statements
+*/
+public final class SAML2PResponseComponentBuilder {
+    
+    private static SAMLObjectBuilder<Response> responseBuilder;
+    
+    private static SAMLObjectBuilder<Issuer> issuerBuilder;
+    
+    private static SAMLObjectBuilder<Status> statusBuilder;
+    
+    private static SAMLObjectBuilder<StatusCode> statusCodeBuilder;
+    
+    private static SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
+    
+    private static XMLObjectBuilderFactory builderFactory = 
+        XMLObjectProviderRegistrySupport.getBuilderFactory();
+    
+    private SAML2PResponseComponentBuilder() {
+        
+    }
+    
+    @SuppressWarnings("unchecked")
+    public static Response createSAMLResponse(
+        String inResponseTo,
+        String issuer,
+        Status status
+    ) {
+        if (responseBuilder == null) {
+            responseBuilder = (SAMLObjectBuilder<Response>)
+                builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
+        }
+        Response response = responseBuilder.buildObject();
+        
+        response.setID(UUID.randomUUID().toString());
+        response.setIssueInstant(new DateTime());
+        response.setInResponseTo(inResponseTo);
+        response.setIssuer(createIssuer(issuer));
+        response.setStatus(status);
+        response.setVersion(SAMLVersion.VERSION_20);
+        
+        return response;
+    }
+    
+    @SuppressWarnings("unchecked")
+    public static Issuer createIssuer(
+        String issuerValue
+    ) {
+        if (issuerBuilder == null) {
+            issuerBuilder = (SAMLObjectBuilder<Issuer>)
+                builderFactory.getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
+        }
+        Issuer issuer = issuerBuilder.buildObject();
+        issuer.setValue(issuerValue);
+        
+        return issuer;
+    }
+    
+    @SuppressWarnings("unchecked")
+    public static Status createStatus(
+        String statusCodeValue,
+        String statusMessage
+    ) {
+        if (statusBuilder == null) {
+            statusBuilder = (SAMLObjectBuilder<Status>)
+                builderFactory.getBuilder(Status.DEFAULT_ELEMENT_NAME);
+        }
+        if (statusCodeBuilder == null) {
+            statusCodeBuilder = (SAMLObjectBuilder<StatusCode>)
+                builderFactory.getBuilder(StatusCode.DEFAULT_ELEMENT_NAME);
+        }
+        if (statusMessageBuilder == null) {
+            statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>)
+                builderFactory.getBuilder(StatusMessage.DEFAULT_ELEMENT_NAME);
+        }
+        
+        Status status = statusBuilder.buildObject();
+        
+        StatusCode statusCode = statusCodeBuilder.buildObject();
+        statusCode.setValue(statusCodeValue);
+        status.setStatusCode(statusCode);
+        
+        if (statusMessage != null) {
+            StatusMessage statusMessageObject = statusMessageBuilder.buildObject();
+            statusMessageObject.setMessage(statusMessage);
+            status.setStatusMessage(statusMessageObject);
+        }
+        
+        return status;
+    }
+    
+    
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAMLAuthnRequest.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAMLAuthnRequest.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAMLAuthnRequest.java
new file mode 100644
index 0000000..c7ded4b
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/samlsso/SAMLAuthnRequest.java
@@ -0,0 +1,74 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.samlsso;
+
+import java.io.Serializable;
+
+import org.opensaml.saml.saml2.core.AuthnRequest;
+
+/**
+ * This class encapsulates a (parsed) SAML AuthnRequest Object. The OpenSAML AuthnRequest Object is not
+ * serializable.
+ */
+public class SAMLAuthnRequest implements Serializable {
+    /**
+     * 
+     */
+    private static final long serialVersionUID = 4353024755428346545L;
+    
+    private String issuer;
+    private String consumerServiceURL;
+    private String requestId;
+    private boolean forceAuthn;
+    private String subjectNameId;
+    
+    public SAMLAuthnRequest(AuthnRequest authnRequest) {
+        if (authnRequest.getIssuer() != null) {
+            issuer = authnRequest.getIssuer().getValue();
+        }
+        
+        consumerServiceURL = authnRequest.getAssertionConsumerServiceURL();
+        requestId = authnRequest.getID();
+        forceAuthn = authnRequest.isForceAuthn().booleanValue();
+        if (authnRequest.getSubject() != null && authnRequest.getSubject().getNameID() != null) {
+            subjectNameId = authnRequest.getSubject().getNameID().getValue();
+        }
+    }
+    
+    public String getIssuer() {
+        return issuer;
+    }
+    
+    public String getConsumerServiceURL() {
+        return consumerServiceURL;
+    }
+    
+    public String getRequestId() {
+        return requestId;
+    }
+    
+    public boolean isForceAuthn() {
+        return forceAuthn;
+    }
+    
+    public String getSubjectNameId() {
+        return subjectNameId;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ApplicationDAO.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ApplicationDAO.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ApplicationDAO.java
new file mode 100644
index 0000000..a519908
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ApplicationDAO.java
@@ -0,0 +1,43 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
+
+public interface ApplicationDAO {
+
+    List<Application> getApplications(int start, int size, List<String> expand);
+
+    Application getApplication(String realm, List<String> expand);
+
+    Application addApplication(Application application);
+
+    void updateApplication(String realm, Application application);
+
+    void deleteApplication(String realm);
+
+    void addClaimToApplication(Application application, RequestClaim claim);
+    
+    void removeClaimFromApplication(Application application, RequestClaim claim);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ClaimDAO.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ClaimDAO.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ClaimDAO.java
new file mode 100644
index 0000000..417a50a
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ClaimDAO.java
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+
+public interface ClaimDAO {
+
+    List<Claim> getClaims(int start, int size);
+    
+    Claim getClaim(String claimType);
+    
+    Claim addClaim(Claim claim);
+    
+    void updateClaim(String claimType, Claim claim);
+    
+    void deleteClaim(String claimType);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigService.java
new file mode 100644
index 0000000..e306ff4
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigService.java
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service;
+
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+
+
+public interface ConfigService {
+
+    Idp getIDP(String realm);
+
+    void setIDP(Idp config);
+
+    void removeIDP(String realm);
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigServiceSpring.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigServiceSpring.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigServiceSpring.java
new file mode 100644
index 0000000..8545af3
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/ConfigServiceSpring.java
@@ -0,0 +1,76 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.model.IDPConfig;
+import org.apache.cxf.fediz.service.idp.model.ServiceConfig;
+
+public class ConfigServiceSpring implements ConfigService {
+
+    private Map<String, Application> serviceConfigs = new HashMap<>();
+    private Map<String, Idp> idpConfigs = new HashMap<>();
+
+
+    @Override
+    public Idp getIDP(String realm) {
+        if (realm == null || realm.length() == 0) {
+            return this.getIdpConfigs().get(0);
+        } else {
+            return idpConfigs.get(realm);
+        }
+    }
+
+    @Override
+    public void setIDP(Idp config) {
+        idpConfigs.put(config.getRealm(), config);
+    }
+
+    @Override
+    public void removeIDP(String realm) {
+        idpConfigs.remove(realm);
+    }
+
+    public List<Application> getServiceConfigs() {
+        return new ArrayList<Application>(serviceConfigs.values());
+    }
+
+    public void setServiceConfigs(List<ServiceConfig> serviceList) {
+        for (ServiceConfig s : serviceList) {
+            serviceConfigs.put(s.getRealm(), s);
+        }
+    }
+    
+    public List<Idp> getIdpConfigs() {
+        return new ArrayList<Idp>(idpConfigs.values());
+    }
+
+    public void setIdpConfigs(List<IDPConfig> idpList) {
+        for (IDPConfig i : idpList) {
+            idpConfigs.put(i.getRealm(), i);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/EntitlementDAO.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/EntitlementDAO.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/EntitlementDAO.java
new file mode 100644
index 0000000..d93cdc0
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/EntitlementDAO.java
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+
+public interface EntitlementDAO {
+
+    List<Entitlement> getEntitlements(int start, int size);
+    
+    Entitlement getEntitlement(String name);
+    
+    Entitlement addEntitlement(Entitlement entitlement);
+    
+    void updateEntitlement(String name, Entitlement entitlement);
+    
+    void deleteEntitlement(String name);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/IdpDAO.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/IdpDAO.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/IdpDAO.java
new file mode 100644
index 0000000..41c5cdf
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/IdpDAO.java
@@ -0,0 +1,53 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+
+public interface IdpDAO {
+
+    List<Idp> getIdps(int start, int size, List<String> expand);
+
+    Idp getIdp(String realm, List<String> expand);
+
+    Idp addIdp(Idp idp);
+
+    void updateIdp(String realm, Idp idp);
+
+    void deleteIdp(String realm);
+
+    void addApplicationToIdp(Idp idp, Application application);
+    
+    void removeApplicationFromIdp(Idp idp, Application application);
+    
+    void addTrustedIdpToIdp(Idp idp, TrustedIdp trustedIdp);
+    
+    void removeTrustedIdpFromIdp(Idp idp, TrustedIdp trustedIdp);
+    
+    void addClaimToIdp(Idp idp, Claim claim);
+    
+    void removeClaimFromIdp(Idp idp, Claim claim);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/RoleDAO.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/RoleDAO.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/RoleDAO.java
new file mode 100644
index 0000000..2d8e7f5
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/RoleDAO.java
@@ -0,0 +1,43 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+import org.apache.cxf.fediz.service.idp.domain.Role;
+
+public interface RoleDAO {
+
+    List<Role> getRoles(int start, int size, List<String> expand);
+
+    Role getRole(String name, List<String> expand);
+
+    Role addRole(Role role);
+
+    void updateRole(String realm, Role role);
+
+    void deleteRole(String name);
+
+    void addEntitlementToRole(Role role, Entitlement entitlement);
+    
+    void removeEntitlementFromRole(Role role, Entitlement entitlement);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/TrustedIdpDAO.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/TrustedIdpDAO.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/TrustedIdpDAO.java
new file mode 100644
index 0000000..54fb634
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/TrustedIdpDAO.java
@@ -0,0 +1,38 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+
+public interface TrustedIdpDAO {
+
+    List<TrustedIdp> getTrustedIDPs(int start, int size);
+
+    TrustedIdp getTrustedIDP(String realm);
+
+    TrustedIdp addTrustedIDP(TrustedIdp trustedIdp);
+
+    void updateTrustedIDP(String realm, TrustedIdp trustedIdp);
+
+    void deleteTrustedIDP(String realm);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationClaimEntity.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationClaimEntity.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationClaimEntity.java
new file mode 100644
index 0000000..e2ca923
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationClaimEntity.java
@@ -0,0 +1,83 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+@Entity(name = "Application_Claim")
+//@IdClass(ApplicationClaimId.class)
+public class ApplicationClaimEntity {
+    
+    @Id
+    private int id;
+    
+    @ManyToOne
+    @JoinColumn(name = "applicationid")
+    private ApplicationEntity application;
+ 
+    @ManyToOne
+    @JoinColumn(name = "claimid")
+    private ClaimEntity claim;
+ 
+    private boolean optional;
+    
+    public ApplicationClaimEntity() {
+    }
+    
+    public ApplicationClaimEntity(ApplicationEntity application, ClaimEntity claim) {
+        super();
+        this.application = application;
+        this.claim = claim;
+    }
+    
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }
+
+    public boolean isOptional() {
+        return optional;
+    }
+
+    public void setOptional(boolean optional) {
+        this.optional = optional;
+    }
+
+    public ApplicationEntity getApplication() {
+        return application;
+    }
+
+    public void setApplication(ApplicationEntity application) {
+        this.application = application;
+    }
+
+    public ClaimEntity getClaim() {
+        return claim;
+    }
+
+    public void setClaim(ClaimEntity claim) {
+        this.claim = claim;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPAImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPAImpl.java
new file mode 100644
index 0000000..307e381
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPAImpl.java
@@ -0,0 +1,254 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityNotFoundException;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
+import org.apache.cxf.fediz.service.idp.service.ApplicationDAO;
+import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+@Repository
+@Transactional
+public class ApplicationDAOJPAImpl implements ApplicationDAO {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(ApplicationDAOJPAImpl.class);
+
+    private EntityManager em;
+    
+    @Autowired
+    private ClaimDAO claimDAO;
+    
+    
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+    
+    @Override
+    public List<Application> getApplications(int start, int size, List<String> expandList) {
+        List<Application> list = new ArrayList<>();
+        
+        Query query = null;
+        query = em.createQuery("select a from Application a");
+        
+        //@SuppressWarnings("rawtypes")
+        List<?> serviceEntities = query
+            .setFirstResult(start)
+            .setMaxResults(size)
+            .getResultList();
+    
+        for (Object obj : serviceEntities) {
+            ApplicationEntity entity = (ApplicationEntity) obj;
+            list.add(entity2domain(entity, expandList));
+        }
+        return list;
+    }
+    
+    @Override
+    public Application getApplication(String realm, List<String> expandList) {
+        return entity2domain(getApplicationEntity(realm, em), expandList);
+    }
+    
+    @Override
+    public Application addApplication(Application application) {
+        ApplicationEntity entity = new ApplicationEntity();
+        
+        domain2entity(application, entity);
+        em.persist(entity);
+        
+        LOG.debug("Application '{}' added", application.getRealm());
+        return entity2domain(entity, Arrays.asList("all"));
+    }
+
+    @Override
+    public void updateApplication(String realm, Application application) {
+        Query query = null;
+        query = em.createQuery("select a from Application a where a.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        ApplicationEntity applicationEntity = (ApplicationEntity)query.getSingleResult();
+        
+        domain2entity(application, applicationEntity);
+        
+        em.persist(applicationEntity);
+        
+        LOG.debug("Application '{}' updated", realm);
+    }
+    
+
+    @Override
+    public void deleteApplication(String realm) {
+        Query query = null;
+        query = em.createQuery("select a from Application a where a.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        Object applObj = query.getSingleResult();
+        em.remove(applObj);
+        
+        LOG.debug("Application '{}' deleted", realm);
+        
+    }
+    
+    @Override
+    public void addClaimToApplication(Application application, RequestClaim claim) {
+        ApplicationEntity applicationEntity = null;
+        if (application.getId() != 0) {
+            applicationEntity = em.find(ApplicationEntity.class, application.getId());
+        } else {
+            Query query = null;
+            query = em.createQuery("select a from Application a where a.realm=:realm");
+            query.setParameter("realm", application.getRealm());
+            
+            applicationEntity = (ApplicationEntity)query.getSingleResult();
+        }
+        
+        Claim c = claimDAO.getClaim(claim.getClaimType().toString());
+        ClaimEntity claimEntity = em.find(ClaimEntity.class, c.getId());
+                
+        ApplicationClaimEntity appClaimEntity = new ApplicationClaimEntity();
+        appClaimEntity.setClaim(claimEntity);
+        appClaimEntity.setApplication(applicationEntity);
+        appClaimEntity.setOptional(claim.isOptional());
+        
+        applicationEntity.getRequestedClaims().add(appClaimEntity);
+    }
+    
+    @Override
+    public void removeClaimFromApplication(Application application, RequestClaim claim) {
+        ApplicationEntity applicationEntity = null;
+        if (application.getId() != 0) {
+            applicationEntity = em.find(ApplicationEntity.class, application.getId());
+        } else {
+            Query query = null;
+            query = em.createQuery("select a from Application a where a.realm=:realm");
+            query.setParameter("realm", application.getRealm());
+            
+            applicationEntity = (ApplicationEntity)query.getSingleResult();
+        }
+        
+        ApplicationClaimEntity foundEntity = null;
+        for (ApplicationClaimEntity acm : applicationEntity.getRequestedClaims()) {
+            if (claim.getClaimType().toString().equals(acm.getClaim().getClaimType())) {
+                foundEntity = acm;
+                break;
+            }
+        }
+        if (foundEntity == null) {
+            throw new EntityNotFoundException("ApplicationClaimEntity not found");
+        }
+        
+        applicationEntity.getRequestedClaims().remove(foundEntity);
+    }
+    
+    
+    static ApplicationEntity getApplicationEntity(String realm, EntityManager em) {
+        Query query = null;
+        query = em.createQuery("select a from Application a where a.realm=:realm");
+        query.setParameter("realm", realm);
+        
+        //@SuppressWarnings("rawtypes")
+        return (ApplicationEntity)query.getSingleResult();
+    }
+        
+    public static void domain2entity(Application application, ApplicationEntity entity) {
+        //The ID must not be updated if the entity has got an id already (update case)
+        if (application.getId() > 0) {
+            entity.setId(application.getId());
+        }
+        
+        entity.setEncryptionCertificate(application.getEncryptionCertificate());
+        entity.setValidatingCertificate(application.getValidatingCertificate());
+        entity.setLifeTime(application.getLifeTime());
+        entity.setProtocol(application.getProtocol());
+        entity.setRealm(application.getRealm());
+        entity.setRole(application.getRole());
+        entity.setServiceDescription(application.getServiceDescription());
+        entity.setServiceDisplayName(application.getServiceDisplayName());
+        entity.setTokenType(application.getTokenType());
+        entity.setPolicyNamespace(application.getPolicyNamespace());
+        entity.setPassiveRequestorEndpoint(application.getPassiveRequestorEndpoint());
+        entity.setPassiveRequestorEndpointConstraint(application.getPassiveRequestorEndpointConstraint());
+        entity.setEnableAppliesTo(application.isEnableAppliesTo());
+    }
+    
+    public static Application entity2domain(ApplicationEntity entity, List<String> expandList) {
+        Application application = new Application();
+        application.setId(entity.getId());
+        application.setEncryptionCertificate(entity.getEncryptionCertificate());
+        application.setValidatingCertificate(entity.getValidatingCertificate());
+        application.setLifeTime(entity.getLifeTime());
+        application.setProtocol(entity.getProtocol());
+        application.setRealm(entity.getRealm());
+        application.setRole(entity.getRole());
+        application.setServiceDescription(entity.getServiceDescription());
+        application.setServiceDisplayName(entity.getServiceDisplayName());
+        application.setTokenType(entity.getTokenType());
+        application.setPolicyNamespace(entity.getPolicyNamespace());
+        application.setPassiveRequestorEndpoint(entity.getPassiveRequestorEndpoint());
+        application.setPassiveRequestorEndpointConstraint(entity.getPassiveRequestorEndpointConstraint());
+        application.setEnableAppliesTo(entity.isEnableAppliesTo());
+        
+        if (expandList != null && (expandList.contains("all") || expandList.contains("claims"))) {
+            for (ApplicationClaimEntity item : entity.getRequestedClaims()) {
+                RequestClaim claim = entity2domain(item);
+                application.getRequestedClaims().add(claim);
+            }
+        }
+        return application;
+    }
+    
+    public static RequestClaim entity2domain(ApplicationClaimEntity entity) {
+        Claim claim = ClaimDAOJPAImpl.entity2domain(entity.getClaim());
+        RequestClaim reqClaim = new RequestClaim(claim);
+        reqClaim.setId(entity.getId());
+        reqClaim.setOptional(entity.isOptional());
+        
+        return reqClaim;
+    }
+    
+    public static void domain2entity(ApplicationEntity application,
+                                     RequestClaim reqClaim, ApplicationClaimEntity entity) {
+        //The ID must not be updated if the entity has got an id already (update case)
+        ClaimEntity claim = new ClaimEntity();
+        ClaimDAOJPAImpl.domain2entity(reqClaim, claim);
+        
+        entity.setApplication(application);
+        entity.setClaim(claim);
+        entity.setOptional(reqClaim.isOptional());
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationEntity.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationEntity.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationEntity.java
new file mode 100644
index 0000000..1397da2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationEntity.java
@@ -0,0 +1,214 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.OneToMany;
+import javax.validation.constraints.Min;
+import javax.validation.constraints.NotNull;
+
+import org.apache.openjpa.persistence.jdbc.Index;
+
+
+@Entity(name = "Application")
+public class ApplicationEntity {
+    
+    @Id
+    private int id;
+    
+    @Index
+    @NotNull
+    private String realm;  //wtrealm, whr
+
+    //Could be read from Metadata, RoleDescriptor protocolSupportEnumeration=
+    // "http://docs.oa14sis-open.org/wsfed/federation/200706"
+    // Metadata could provide more than one but one must be chosen
+    @NotNull
+    @ApplicationProtocolSupported
+    private String protocol;
+ 
+    // Public key only
+    // Could be read from Metadata, md:KeyDescriptor, use="encryption"
+    private String encryptionCertificate;
+    
+    // Certificate for Signature verification
+    private String validatingCertificate;
+    
+    // Could be read from Metadata, fed:ClaimTypesRequested
+    @OneToMany(mappedBy = "application", cascade = CascadeType.ALL, orphanRemoval = true)
+    private List<ApplicationClaimEntity> requestedClaims = new ArrayList<>();
+    
+    //Could be read from Metadata, ServiceDisplayName
+    //usage for list of application where user is logged in
+    @NotNull
+    private String serviceDisplayName;
+    
+    //Could be read from Metadata, ServiceDescription
+    //usage for list of application where user is logged in
+    private String serviceDescription;
+    
+    //Could be read from Metadata, RoleDescriptor
+    //fed:ApplicationServiceType, fed:SecurityTokenServiceType
+    private String role;
+    
+    // Not in Metadata, configured in IDP or passed in wreq parameter
+    @NotNull
+    private String tokenType;
+    
+    // Not in Metadata, configured in IDP or passed in wreq parameter
+    @Min(value = 1)
+    private int lifeTime;
+    
+    // Request audience restriction in token for this application (default is true)
+    private boolean enableAppliesTo = true;
+    
+    // WS-Policy Namespace in SignIn Response
+    private String policyNamespace;
+    
+    private String passiveRequestorEndpoint;
+    
+    // A regular expression constraint on the passiveRequestorEndpoint
+    private String passiveRequestorEndpointConstraint;
+
+
+    public int getId() {
+        return id;
+    }
+
+    public void setId(int id) {
+        this.id = id;
+    }    
+    
+    public String getRealm() {
+        return realm;
+    }
+
+    public void setRealm(String realm) {
+        this.realm = realm;
+    }
+
+    public String getProtocol() {
+        return protocol;
+    }
+
+    public void setProtocol(String protocol) {
+        this.protocol = protocol;
+    }
+
+    public String getEncryptionCertificate() {
+        return encryptionCertificate;
+    }
+
+    public void setEncryptionCertificate(String encryptionCertificate) {
+        this.encryptionCertificate = encryptionCertificate;
+    }
+
+    public List<ApplicationClaimEntity> getRequestedClaims() {
+        return requestedClaims;
+    }
+
+    public void setRequestedClaims(List<ApplicationClaimEntity> requestedClaims) {
+        this.requestedClaims = requestedClaims;
+    }
+
+    public String getServiceDisplayName() {
+        return serviceDisplayName;
+    }
+
+    public void setServiceDisplayName(String serviceDisplayName) {
+        this.serviceDisplayName = serviceDisplayName;
+    }
+
+    public String getServiceDescription() {
+        return serviceDescription;
+    }
+
+    public void setServiceDescription(String serviceDescription) {
+        this.serviceDescription = serviceDescription;
+    }
+
+    public String getRole() {
+        return role;
+    }
+
+    public void setRole(String role) {
+        this.role = role;
+    }
+
+    public String getTokenType() {
+        return tokenType;
+    }
+
+    public void setTokenType(String tokenType) {
+        this.tokenType = tokenType;
+    }
+
+    public int getLifeTime() {
+        return lifeTime;
+    }
+
+    public void setLifeTime(int lifeTime) {
+        this.lifeTime = lifeTime;
+    }
+    
+    public String getPolicyNamespace() {
+        return policyNamespace;
+    }
+
+    public void setPolicyNamespace(String policyNamespace) {
+        this.policyNamespace = policyNamespace;
+    }
+
+    public String getPassiveRequestorEndpoint() {
+        return passiveRequestorEndpoint;
+    }
+
+    public void setPassiveRequestorEndpoint(String passiveRequestorEndpoint) {
+        this.passiveRequestorEndpoint = passiveRequestorEndpoint;
+    }
+    
+    public String getPassiveRequestorEndpointConstraint() {
+        return passiveRequestorEndpointConstraint;
+    }
+
+    public void setPassiveRequestorEndpointConstraint(String passiveRequestorEndpointConstraint) {
+        this.passiveRequestorEndpointConstraint = passiveRequestorEndpointConstraint;
+    }
+
+    public String getValidatingCertificate() {
+        return validatingCertificate;
+    }
+
+    public void setValidatingCertificate(String validatingCertificate) {
+        this.validatingCertificate = validatingCertificate;
+    }
+
+    public boolean isEnableAppliesTo() {
+        return enableAppliesTo;
+    }
+
+    public void setEnableAppliesTo(boolean enableAppliesTo) {
+        this.enableAppliesTo = enableAppliesTo;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationIdpProtocolSupportValidator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationIdpProtocolSupportValidator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationIdpProtocolSupportValidator.java
new file mode 100644
index 0000000..5a999e9
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationIdpProtocolSupportValidator.java
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.List;
+
+import javax.validation.ConstraintValidator;
+import javax.validation.ConstraintValidatorContext;
+
+import org.apache.cxf.fediz.service.idp.protocols.ProtocolController;
+import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Component;
+
+/**
+ * Validate that the protocol is a valid Application protocol
+ */
+@Component
+public class ApplicationIdpProtocolSupportValidator
+    implements ConstraintValidator<ApplicationProtocolSupported, String> {
+
+    @Autowired
+    @Qualifier("applicationProtocolControllerImpl")
+    private ProtocolController<ApplicationProtocolHandler> applicationProtocolHandlers;
+    
+    @Override
+    public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
+        
+        List<String> protocols = applicationProtocolHandlers.getProtocols();
+        return protocols.contains(object);
+    }
+
+    @Override
+    public void initialize(ApplicationProtocolSupported constraintAnnotation) {
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationProtocolSupported.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationProtocolSupported.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationProtocolSupported.java
new file mode 100644
index 0000000..6dc69a5
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationProtocolSupported.java
@@ -0,0 +1,47 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
+import static java.lang.annotation.ElementType.FIELD;
+import static java.lang.annotation.ElementType.METHOD;
+
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+import javax.validation.Constraint;
+import javax.validation.Payload;
+
+@Target({ METHOD, FIELD, ANNOTATION_TYPE })
+@Retention(RUNTIME)
+@Constraint(validatedBy = ApplicationIdpProtocolSupportValidator.class)
+@Documented
+public @interface ApplicationProtocolSupported {
+
+    String message() default "{Protocol not supported}";
+
+    Class<?>[] groups() default { };
+
+    Class<? extends Payload>[] payload() default { };
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPAImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPAImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPAImpl.java
new file mode 100644
index 0000000..dea2b8d
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPAImpl.java
@@ -0,0 +1,143 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+import javax.persistence.Query;
+
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Repository;
+import org.springframework.transaction.annotation.Transactional;
+
+
+@Repository
+@Transactional
+public class ClaimDAOJPAImpl implements ClaimDAO {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(ClaimDAOJPAImpl.class);
+
+    private EntityManager em;
+    
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+    
+    @Override
+    public List<Claim> getClaims(int start, int size) {
+        List<Claim> list = new ArrayList<>();
+        
+        Query query = null;
+        query = em.createQuery("select c from Claim c");
+        
+        //@SuppressWarnings("rawtypes")
+        List<?> claimEntities = query
+            .setFirstResult(start)
+            .setMaxResults(size)
+            .getResultList();
+
+        for (Object obj : claimEntities) {
+            ClaimEntity entity = (ClaimEntity) obj;
+            list.add(entity2domain(entity));
+        }
+        
+        return list;
+    }
+    
+    @Override
+    public Claim addClaim(Claim claim) {
+        ClaimEntity entity = new ClaimEntity();
+        domain2entity(claim, entity);
+        em.persist(entity);
+        
+        LOG.debug("Claim '{}' added", claim.getClaimType());
+        return entity2domain(entity);
+    }
+
+    @Override
+    public Claim getClaim(String claimType) {
+        return entity2domain(getClaimEntity(claimType, em));
+    }
+
+    @Override
+    public void updateClaim(String claimType, Claim claim) {
+        Query query = null;
+        query = em.createQuery("select c from Claim c where c.claimtype=:claimtype");
+        query.setParameter("claimtype", claimType);
+        
+        //@SuppressWarnings("rawtypes")
+        ClaimEntity claimEntity = (ClaimEntity)query.getSingleResult();
+        
+        domain2entity(claim, claimEntity);
+        
+        LOG.debug("Claim '{}' added", claim.getClaimType());
+        em.persist(claimEntity);
+    }
+
+    @Override
+    public void deleteClaim(String claimType) {
+        Query query = null;
+        query = em.createQuery("select c from Claim c where c.claimType=:claimtype");
+        query.setParameter("claimtype", claimType);
+        
+        //@SuppressWarnings("rawtypes")
+        Object claimObj = query.getSingleResult();
+        em.remove(claimObj);
+        
+        LOG.debug("Claim '{}' deleted", claimType);
+    }
+    
+    static ClaimEntity getClaimEntity(String claimType, EntityManager em) {
+        Query query = null;
+        query = em.createQuery("select c from Claim c where c.claimType=:claimtype");
+        query.setParameter("claimtype", claimType);
+        
+        //@SuppressWarnings("rawtypes")
+        return (ClaimEntity)query.getSingleResult();
+    }
+    
+    public static void domain2entity(Claim claim, ClaimEntity entity) {
+        //The ID must not be updated if the entity has got an id already (update case)
+        if (claim.getId() > 0) {
+            entity.setId(claim.getId());
+        }
+        entity.setClaimType(claim.getClaimType().toString());
+        entity.setDisplayName(claim.getDisplayName());
+        entity.setDescription(claim.getDescription());
+    }
+    
+    public static Claim entity2domain(ClaimEntity entity) {
+        Claim claim = new Claim();
+        claim.setId(entity.getId());
+        claim.setClaimType(URI.create(entity.getClaimType()));
+        claim.setDisplayName(entity.getDisplayName());
+        claim.setDescription(entity.getDescription());
+        return claim;
+    }
+
+}


[11/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/security/GrantedAuthorityEntitlements.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/security/GrantedAuthorityEntitlements.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/security/GrantedAuthorityEntitlements.java
new file mode 100644
index 0000000..475ccd7
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/service/security/GrantedAuthorityEntitlements.java
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.security;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+import org.apache.cxf.fediz.service.idp.domain.Role;
+import org.apache.cxf.fediz.service.idp.service.RoleDAO;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.authority.SimpleGrantedAuthority;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.web.filter.GenericFilterBean;
+
+public class GrantedAuthorityEntitlements extends GenericFilterBean {
+
+    private static final Logger LOG = LoggerFactory.getLogger(GrantedAuthorityEntitlements.class);
+    
+    @Autowired
+    private RoleDAO roleDAO;
+    
+    @Override
+    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+        throws IOException, ServletException {
+        
+        try {
+            Authentication currentAuth = SecurityContextHolder.getContext().getAuthentication();
+            if (currentAuth == null) {
+                chain.doFilter(request, response);
+                return;
+            }
+            
+            final Set<GrantedAuthority> authorities = new HashSet<>();
+            if (currentAuth.getAuthorities() != null) {
+                authorities.addAll(currentAuth.getAuthorities());
+            }
+            
+            Iterator<? extends GrantedAuthority> authIt = currentAuth.getAuthorities().iterator();
+            while (authIt.hasNext()) {
+                GrantedAuthority ga = authIt.next();
+                String roleName = ga.getAuthority();
+                
+                try {
+                    Role role = roleDAO.getRole(roleName.substring(5), Arrays.asList("all"));
+                    for (Entitlement e : role.getEntitlements()) {
+                        authorities.add(new SimpleGrantedAuthority(e.getName()));
+                    }
+                } catch (Exception ex) {
+                    LOG.error("Role '{}' not found", roleName);
+                }
+            }
+            LOG.debug("Granted Authorities: {}", authorities);
+            
+            UsernamePasswordAuthenticationToken enrichedAuthentication = new UsernamePasswordAuthenticationToken(
+                currentAuth.getName(), currentAuth.getCredentials(), authorities);
+            enrichedAuthentication.setDetails(currentAuth.getDetails());
+            
+            SecurityContextHolder.getContext().setAuthentication(enrichedAuthentication);
+            LOG.info("Enriched AuthenticationToken added");
+            
+        } catch (Exception ex) {
+            LOG.error("Failed to enrich security context with entitlements", ex);
+        }
+        
+        chain.doFilter(request, response);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/ApplicationProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/ApplicationProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/ApplicationProtocolHandler.java
new file mode 100644
index 0000000..1cd9dc1
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/ApplicationProtocolHandler.java
@@ -0,0 +1,33 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.spi;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.springframework.webflow.execution.RequestContext;
+
+public interface ApplicationProtocolHandler extends ProtocolHandler {
+    
+    boolean canHandleRequest(HttpServletRequest request);
+
+    void mapSignInRequest(RequestContext context);
+    
+    void mapSignInResponse(RequestContext context);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/ProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/ProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/ProtocolHandler.java
new file mode 100644
index 0000000..2c1c8c9
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/ProtocolHandler.java
@@ -0,0 +1,25 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.spi;
+
+public interface ProtocolHandler {
+
+    String getProtocol();
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/TrustedIdpProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/TrustedIdpProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/TrustedIdpProtocolHandler.java
new file mode 100644
index 0000000..a33591b
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/spi/TrustedIdpProtocolHandler.java
@@ -0,0 +1,40 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.spi;
+
+import java.net.URL;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.springframework.webflow.execution.RequestContext;
+
+public interface TrustedIdpProtocolHandler extends ProtocolHandler {
+    
+    boolean canHandleRequest(HttpServletRequest request);
+
+    // Only supports HTTP GET SignIn Requests
+    URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp);
+    
+    //Hook in <action-state id="validateToken"> of federation-signin-response.xml
+    SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/util/WebUtils.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/util/WebUtils.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/util/WebUtils.java
new file mode 100644
index 0000000..4484312
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/util/WebUtils.java
@@ -0,0 +1,209 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.util;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.springframework.util.Assert;
+import org.springframework.webflow.context.servlet.ServletExternalContext;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Utility class to bind with webflow artifacts
+ */
+public final class WebUtils {
+    
+    private WebUtils() {
+        super();
+    }
+
+    public static HttpServletRequest getHttpServletRequest(
+            final RequestContext context) {
+        Assert.isInstanceOf(ServletExternalContext.class,
+                context.getExternalContext(),
+                "Cannot obtain HttpServletRequest from event of type: "
+                        + context.getExternalContext().getClass().getName());
+        return (HttpServletRequest) context.getExternalContext()
+                .getNativeRequest();
+    }
+
+    public static HttpSession getHttpSession(final RequestContext context) {
+        HttpServletRequest httpServletRequest = getHttpServletRequest(context);
+        return httpServletRequest.getSession();
+    }
+
+    public static HttpServletResponse getHttpServletResponse(
+            final RequestContext context) {
+        Assert.isInstanceOf(ServletExternalContext.class,
+                context.getExternalContext(),
+                "Cannot obtain HttpServletResponse from event of type: "
+                        + context.getExternalContext().getClass().getName());
+        return (HttpServletResponse) context.getExternalContext()
+                .getNativeResponse();
+    }
+
+    public static String getHttpHeader(RequestContext requestContext, String headerName) {
+        return getHttpServletRequest(requestContext).getHeader(headerName);
+    }
+
+    public static void putAttributeInRequestScope(final RequestContext context,
+            final String attributeKey, final Object attributeValue) {
+        context.getRequestScope().put(attributeKey, attributeValue);
+    }
+
+    public static void putAttributeInExternalContext(
+            final RequestContext context, final String attributeKey,
+            final Object attributeValue) {
+        context.getExternalContext().getSessionMap()
+                .put(attributeKey, attributeValue);
+    }
+
+    /**
+     * put attribute in request or in session depending on storeInSession.
+     * 
+     * @param context
+     * @param attributeKey
+     */
+    public static void putAttribute(final RequestContext context,
+            final String attributeKey, final Object attributeValue,
+            boolean storeInSession) {
+        if (storeInSession) {
+            putAttributeInExternalContext(context, attributeKey, attributeValue);
+        } else {
+            putAttributeInRequestScope(context, attributeKey, attributeValue);
+        }
+    }
+
+    public static Object getAttributeFromRequestScope(
+            final RequestContext context, final String attributeKey) {
+        return context.getRequestScope().get(attributeKey);
+    }
+
+    public static Object getAttributeFromExternalContext(
+            final RequestContext context, final String attributeKey) {
+        return context.getExternalContext().getSessionMap()
+                .get(attributeKey);
+    }
+
+    /**
+     * get attribute from request; if not found get it from session.
+     * 
+     * @param context
+     * @param attributeKey
+     * @return the attribute from the request or session
+     */
+    public static Object getAttribute(final RequestContext context,
+            final String attributeKey) {
+        Object value = getAttributeFromRequestScope(context, attributeKey);
+        if (value != null) {
+            return value;
+        }
+        return getAttributeFromExternalContext(context, attributeKey);
+    }
+
+    public static Object removeAttributeFromRequestScope(
+            final RequestContext context, final String attributeKey) {
+        return context.getRequestScope().remove(attributeKey);
+    }
+
+    public static Object removeAttributeFromExternalContext(
+            final RequestContext context, final String attributeKey) {
+        return context.getExternalContext().getSessionMap()
+                .remove(attributeKey);
+    }
+
+    /**
+     * remove attribute from request and session.
+     * 
+     * @param context
+     * @param attributeKey
+     * @return the removed attribute
+     */
+    public static Object removeAttribute(final RequestContext context,
+            final String attributeKey) {
+        Object valueReq = removeAttributeFromRequestScope(context, attributeKey);
+        Object valueSes = removeAttributeFromExternalContext(context,
+                attributeKey);
+        if (valueSes != null) {
+            return valueSes; // not clean if request has different value !
+        }
+        if (valueReq != null) {
+            return valueReq;
+        }
+        return null;
+    }
+
+    public static void putAttributeInFlowScope(final RequestContext context,
+            final String attributeKey, final Object attributeValue) {
+        context.getFlowScope().put(attributeKey, attributeValue);
+    }
+
+    public static Object getAttributeFromFlowScope(
+            final RequestContext context, final String attributeKey) {
+        return context.getFlowScope().get(attributeKey);
+    }
+
+    public static Object removeAttributeFromFlowScope(
+            final RequestContext context, final String attributeKey) {
+        return context.getFlowScope().remove(attributeKey);
+    }
+
+    public static String getParamFromRequestParameters(
+            final RequestContext context, final String attributeKey) {
+        return context.getRequestParameters().get(attributeKey);
+    }
+
+    public static Cookie readCookie(
+            final RequestContext context, final String cookieName) {
+        HttpServletRequest httpServletRequest = getHttpServletRequest(context);
+        Cookie[] cookies = httpServletRequest.getCookies();
+        if (cookies != null) {
+            for (int i = 0; i < cookies.length; i++) {
+                if (cookies[i].getName().equals(cookieName)) {
+                    return cookies[i];
+                }
+            }
+        }
+        return null;
+    }
+
+    public static void addCookie(
+            final RequestContext context, final String cookieName, final String cookieValue) {
+        HttpServletResponse httpServletResponse = getHttpServletResponse(context);
+        Cookie cookie = new Cookie(cookieName, cookieValue);
+        cookie.setSecure(true);
+        cookie.setMaxAge(-1);
+        httpServletResponse.addCookie(cookie);
+    }
+
+    public static void removeCookie(
+            final RequestContext context, final String cookieName) {
+        HttpServletResponse httpServletResponse = getHttpServletResponse(context);
+        Cookie cookie = readCookie(context, cookieName);
+        if (cookie != null) {
+            cookie.setMaxAge(0);
+            cookie.setValue("");
+            httpServletResponse.addCookie(cookie);
+        }
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/resources/META-INF/orm.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/resources/META-INF/orm.xml b/services/idp-core/src/main/resources/META-INF/orm.xml
new file mode 100644
index 0000000..e9c2bd6
--- /dev/null
+++ b/services/idp-core/src/main/resources/META-INF/orm.xml
@@ -0,0 +1,183 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<entity-mappings xmlns="http://java.sun.com/xml/ns/persistence/orm"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_2_0.xsd"
+    version="2.0">
+
+    <entity class="org.apache.cxf.fediz.service.idp.service.jpa.ClaimEntity">
+        <table>
+            <unique-constraint>
+                <column-name>claimtype</column-name>
+            </unique-constraint>
+        </table>
+        <attributes>
+            <id name="id">
+                <generated-value generator="SEQ_Claim"
+                    strategy="TABLE" />
+                <table-generator name="SEQ_Claim"
+                    pk-column-value="SEQ_Claim" initial-value="100" />
+            </id>
+        </attributes>
+    </entity>
+
+    <entity class="org.apache.cxf.fediz.service.idp.service.jpa.IdpEntity">
+        <table>
+            <unique-constraint>
+                <column-name>realm</column-name>
+            </unique-constraint>
+        </table>
+        <attributes>
+            <id name="id">
+                <generated-value generator="SEQ_IDP"
+                    strategy="TABLE" />
+                <table-generator name="SEQ_IDP"
+                    pk-column-value="SEQ_IDP" initial-value="100" />
+            </id>
+            <many-to-many name="claimTypesOffered">
+                <join-table name="idp_claims">
+                    <join-column name="idp_id" />
+                    <inverse-join-column name="claim_id" />
+                    <unique-constraint>
+                        <column-name>idp_id</column-name>
+                        <column-name>claim_id</column-name>
+                    </unique-constraint>
+                </join-table>
+            </many-to-many>
+            <many-to-many name="trustedIdps">
+                <join-table name="idp_trustedidps">
+                    <join-column name="idp_id" />
+                    <inverse-join-column name="trustedidp_id" />
+                    <unique-constraint>
+                        <column-name>idp_id</column-name>
+                        <column-name>trustedidp_id</column-name>
+                    </unique-constraint>
+                </join-table>
+            </many-to-many>
+            <many-to-many name="applications">
+                <join-table name="idp_applications">
+                    <join-column name="idp_id" />
+                    <inverse-join-column name="application_id" />
+                    <unique-constraint>
+                        <column-name>idp_id</column-name>
+                        <column-name>application_id</column-name>
+                    </unique-constraint>
+                </join-table>
+            </many-to-many>
+
+        </attributes>
+    </entity>
+
+    <entity
+        class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationEntity">
+        <table>
+            <unique-constraint>
+                <column-name>realm</column-name>
+            </unique-constraint>
+        </table>
+        <attributes>
+            <id name="id">
+                <generated-value generator="SEQ_Application"
+                    strategy="TABLE" />
+                <table-generator name="SEQ_Application"
+                    pk-column-value="SEQ_Application" initial-value="100" />
+            </id>
+        </attributes>
+    </entity>
+
+    <entity
+        class="org.apache.cxf.fediz.service.idp.service.jpa.TrustedIdpEntity">
+        <table>
+            <unique-constraint>
+                <column-name>realm</column-name>
+            </unique-constraint>
+        </table>
+        <attributes>
+            <id name="id">
+                <generated-value generator="SEQ_TrustedIDP"
+                    strategy="TABLE" />
+                <table-generator name="SEQ_TrustedIDP"
+                    pk-column-value="SEQ_TrustedIDP" initial-value="100" />
+            </id>
+        </attributes>
+    </entity>
+
+    <entity
+        class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
+        <table>
+            <unique-constraint>
+                <column-name>claimid</column-name>
+                <column-name>applicationid</column-name>
+            </unique-constraint>
+        </table>
+        <attributes>
+            <id name="id">
+                <generated-value generator="SEQ_ApplicationClaim"
+                    strategy="TABLE" />
+                <table-generator name="SEQ_ApplicationClaim"
+                    pk-column-value="SEQ_ApplicationClaim"
+                    initial-value="100" />
+            </id>
+        </attributes>
+    </entity>
+    
+    <entity class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <table>
+            <unique-constraint>
+                <column-name>name</column-name>
+            </unique-constraint>
+        </table>
+        <attributes>
+            <id name="id">
+                <generated-value generator="SEQ_Entitlement"
+                    strategy="TABLE" />
+                <table-generator name="SEQ_Entitlement"
+                    pk-column-value="SEQ_Entitlement" initial-value="100" />
+            </id>
+        </attributes>
+    </entity>
+    
+    <entity class="org.apache.cxf.fediz.service.idp.service.jpa.RoleEntity">
+        <table>
+            <unique-constraint>
+                <column-name>name</column-name>
+            </unique-constraint>
+        </table>
+        <attributes>
+            <id name="id">
+                <generated-value generator="SEQ_ROLE"
+                    strategy="TABLE" />
+                <table-generator name="SEQ_ROLE"
+                    pk-column-value="SEQ_ROLE" initial-value="100" />
+            </id>
+            <many-to-many name="entitlements">
+                <join-table name="role_entitlements">
+                    <join-column name="role_id" />
+                    <inverse-join-column name="entitlement_id" />
+                    <unique-constraint>
+                        <column-name>role_id</column-name>
+                        <column-name>entitlement_id</column-name>
+                    </unique-constraint>
+                </join-table>
+            </many-to-many>
+        </attributes>
+    </entity>
+    
+</entity-mappings>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/resources/META-INF/spring-persistence.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/resources/META-INF/spring-persistence.xml b/services/idp-core/src/main/resources/META-INF/spring-persistence.xml
new file mode 100644
index 0000000..bf34a76
--- /dev/null
+++ b/services/idp-core/src/main/resources/META-INF/spring-persistence.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<persistence
+    xmlns="http://java.sun.com/xml/ns/persistence"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
+    version="2.0">
+
+    <persistence-unit name="fedizPersistenceUnit">
+        <mapping-file>META-INF/orm.xml</mapping-file>
+        <validation-mode>AUTO</validation-mode>
+    </persistence-unit>
+</persistence>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/applicationContext.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/applicationContext.xml b/services/idp-core/src/main/webapp/WEB-INF/applicationContext.xml
new file mode 100644
index 0000000..68bcb0b
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/applicationContext.xml
@@ -0,0 +1,61 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:cxf="http://cxf.apache.org/core"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:context="http://www.springframework.org/schema/context"
+       xsi:schemaLocation="http://cxf.apache.org/core
+        http://cxf.apache.org/schemas/core.xsd
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd">
+
+    <context:component-scan base-package="org.apache.cxf.fediz.service.idp.protocols" />
+        
+        
+    <!-- Use http://www.baeldung.com/2012/02/06/properties-with-spring/ instead -->
+    <bean
+        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
+        <property name="locations">
+            <list>
+                <value>classpath:persistence.properties</value>
+            </list>
+        </property>
+        <property name="ignoreResourceNotFound" value="true" />
+        <property name="ignoreUnresolvablePlaceholders" value="true" />
+    </bean>
+
+    <import resource="classpath:META-INF/cxf/cxf.xml" />
+
+    <import resource="security-config.xml" />
+    <import resource="${idp-config}" />
+    <import resource="classpath:cxf-tls.xml" />
+    <import resource="classpath:persistenceContext.xml" />
+    <import resource="classpath:restContext.xml" />
+
+    <!--cxf:bus>
+        <cxf:features>
+            <cxf:logging />
+        </cxf:features>
+    </cxf:bus-->
+    
+</beans>
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/config/idp-core-servlet.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/config/idp-core-servlet.xml b/services/idp-core/src/main/webapp/WEB-INF/config/idp-core-servlet.xml
new file mode 100644
index 0000000..3d62ad9
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/config/idp-core-servlet.xml
@@ -0,0 +1,105 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:webflow="http://www.springframework.org/schema/webflow-config"
+    xmlns:p="http://www.springframework.org/schema/p"
+    xmlns:mvc="http://www.springframework.org/schema/mvc"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xsi:schemaLocation="http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd
+        http://www.springframework.org/schema/mvc
+        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
+        http://www.springframework.org/schema/webflow-config
+        http://www.springframework.org/schema/webflow-config/spring-webflow-config-2.0.xsd">
+
+    <context:component-scan base-package="org.apache.cxf.fediz.service.idp.beans" />
+
+    <mvc:resources mapping="/images/**" location="/resources/images/" />
+    
+    <mvc:resources mapping="/swagger/**" location="/resources/swagger/" />
+    
+    <mvc:view-controller path="/" view-name="index" />
+    <mvc:view-controller path="/federation/up/login" view-name="signinform" />
+
+    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
+        <property name="prefix" value="/WEB-INF/views/" />
+        <property name="suffix" value=".jsp" />
+    </bean>
+
+    <bean id="viewFactoryCreator" class="org.springframework.webflow.mvc.builder.MvcViewFactoryCreator">
+        <property name="viewResolvers">
+            <list>
+                <ref bean="viewResolver" />
+            </list>
+        </property>
+    </bean>
+
+    <webflow:flow-builder-services id="builder" view-factory-creator="viewFactoryCreator" />
+
+    <webflow:flow-registry id="flowRegistry" flow-builder-services="builder">
+        <webflow:flow-location path="/WEB-INF/flows/federation-validate-request.xml" id="federation" />
+        <webflow:flow-location path="/WEB-INF/flows/federation-validate-request.xml" id="federation/up" />
+        <webflow:flow-location path="/WEB-INF/flows/federation-validate-request.xml" id="federation/krb" />
+        <webflow:flow-location path="/WEB-INF/flows/federation-validate-request.xml" id="federation/clientcert" />
+        
+        <webflow:flow-location path="/WEB-INF/flows/saml-validate-request.xml" id="saml" />
+        <webflow:flow-location path="/WEB-INF/flows/saml-validate-request.xml" id="saml/up" />
+        <webflow:flow-location path="/WEB-INF/flows/saml-validate-request.xml" id="saml/krb" />
+        <webflow:flow-location path="/WEB-INF/flows/saml-validate-request.xml" id="saml/clientcert" />
+        
+        <webflow:flow-location path="/WEB-INF/flows/signin-request.xml" id="signinRequest" />
+        <webflow:flow-location path="/WEB-INF/flows/signin-response.xml" id="signinResponse" />
+    </webflow:flow-registry>
+
+    <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping" p:flowRegistry-ref="flowRegistry"
+        p:order="2">
+    </bean>
+
+    <webflow:flow-executor id="flowExecutor" flow-registry="flowRegistry">
+        <webflow:flow-execution-attributes>
+            <webflow:always-redirect-on-pause value="false" />
+        </webflow:flow-execution-attributes>
+
+        <webflow:flow-execution-listeners>
+            <webflow:listener ref="securityFlowExecutionListener" />
+        </webflow:flow-execution-listeners>
+    </webflow:flow-executor>
+
+    <bean class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter" p:flowExecutor-ref="flowExecutor" />
+
+    <bean id="securityFlowExecutionListener" class="org.springframework.webflow.security.SecurityFlowExecutionListener">
+        <property name="accessDecisionManager" ref="accessDecisionManager" />
+    </bean>
+
+    <bean id="accessDecisionManager" class="org.springframework.security.access.vote.AffirmativeBased">
+        <property name="decisionVoters">
+            <list>
+                <bean class="org.springframework.security.access.vote.RoleVoter">
+                    <property name="rolePrefix" value="ROLE_" />
+                </bean>
+                <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
+            </list>
+        </property>
+    </bean>
+
+</beans>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/config/security-clientcert-config.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/config/security-clientcert-config.xml b/services/idp-core/src/main/webapp/WEB-INF/config/security-clientcert-config.xml
new file mode 100644
index 0000000..d40d0c9
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/config/security-clientcert-config.xml
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:security="http://www.springframework.org/schema/security"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xmlns:util="http://www.springframework.org/schema/util"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd
+        http://www.springframework.org/schema/security
+        http://www.springframework.org/schema/security/spring-security-3.2.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util-4.3.xsd
+        ">
+
+    <!-- DISABLE in production as it might log confidential information about the user -->
+    <!-- <security:debug /> -->
+
+    <!-- SSL Client Cert entry point for WS-Federation -->
+    <security:http pattern="/federation/clientcert" use-expressions="true">
+        <security:custom-filter after="CHANNEL_FILTER" ref="stsClientCertPortFilter" />
+        <security:custom-filter after="SERVLET_API_SUPPORT_FILTER" ref="entitlementsEnricher" />
+
+        <security:x509 />
+        <security:logout delete-cookies="FEDIZ_HOME_REALM" invalidate-session="true" />
+    </security:http>
+    
+    <!-- SSL Client Cert entry point for SAML SSO -->
+    <security:http pattern="/saml/clientcert" use-expressions="true">
+        <security:custom-filter after="CHANNEL_FILTER" ref="stsClientCertPortFilter" />
+        <security:custom-filter after="SERVLET_API_SUPPORT_FILTER" ref="entitlementsEnricher" />
+
+        <security:x509 />
+        <security:logout delete-cookies="FEDIZ_HOME_REALM" invalidate-session="true" />
+    </security:http>
+
+    <bean id="stsClientCertPortFilter" class="org.apache.cxf.fediz.service.idp.STSPortFilter">
+        <property name="authenticationProvider" ref="stsClientCertAuthProvider" />
+    </bean>
+    
+    <util:map id="securityProperties">
+        <entry key="ws-security.username" value="idp-user" />
+        <entry key="ws-security.password" value="idp-pass" />
+    </util:map>
+    
+    <bean id="stsClientCertAuthProvider" class="org.apache.cxf.fediz.service.idp.STSPreAuthAuthenticationProvider">
+        <property name="wsdlLocation" value="https://localhost:0/fediz-idp-sts/${realm.STS_URI}/STSServiceTransportUT?wsdl" />
+        <property name="wsdlEndpoint" value="TransportUT_Port" />
+        <property name="wsdlService" value="SecurityTokenService" />
+        <property name="appliesTo" value="urn:fediz:idp" />
+        <property name="tokenType" value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
+        <property name="properties" ref="securityProperties" />
+    </bean>
+    
+</beans>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/config/security-krb-config.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/config/security-krb-config.xml b/services/idp-core/src/main/webapp/WEB-INF/config/security-krb-config.xml
new file mode 100644
index 0000000..b66044b
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/config/security-krb-config.xml
@@ -0,0 +1,84 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:security="http://www.springframework.org/schema/security"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xmlns:util="http://www.springframework.org/schema/util"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd
+        http://www.springframework.org/schema/security
+        http://www.springframework.org/schema/security/spring-security-3.2.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util-4.3.xsd
+        ">
+
+    <!-- DISABLE in production as it might log confidential information about the user -->
+    <!-- <security:debug /> -->
+
+    <!-- Kerberos entry point -->
+    <bean id="kerberosEntryPoint"
+          class="org.apache.cxf.fediz.service.idp.kerberos.KerberosEntryPoint" />
+    
+    <bean id="kerberosAuthenticationProcessingFilter"
+          class="org.apache.cxf.fediz.service.idp.kerberos.KerberosAuthenticationProcessingFilter">
+          <property name="authenticationManager" ref="authenticationManagers" />
+    </bean>
+    
+    <security:http pattern="/federation/krb" use-expressions="true" entry-point-ref="kerberosEntryPoint">
+        <security:custom-filter after="CHANNEL_FILTER" ref="stsKrbPortFilter" />
+        <security:custom-filter after="SERVLET_API_SUPPORT_FILTER" ref="entitlementsEnricher" />
+
+        <security:custom-filter ref="kerberosAuthenticationProcessingFilter" position="BASIC_AUTH_FILTER" />
+        <security:logout delete-cookies="FEDIZ_HOME_REALM" invalidate-session="true" />
+    </security:http>
+    
+    <security:http pattern="/saml/krb" use-expressions="true" entry-point-ref="kerberosEntryPoint">
+        <security:custom-filter after="CHANNEL_FILTER" ref="stsKrbPortFilter" />
+        <security:custom-filter after="SERVLET_API_SUPPORT_FILTER" ref="entitlementsEnricher" />
+
+        <security:custom-filter ref="kerberosAuthenticationProcessingFilter" position="BASIC_AUTH_FILTER" />
+        <security:logout delete-cookies="FEDIZ_HOME_REALM" invalidate-session="true" />
+    </security:http>
+    
+    <bean id="stsKrbPortFilter" class="org.apache.cxf.fediz.service.idp.STSPortFilter">
+        <property name="authenticationProvider" ref="stsKrbAuthProvider" />
+    </bean>
+    
+    <!--<bean id="kerberosTokenValidator" class="org.apache.cxf.fediz.service.idp.kerberos.KerberosTokenValidator">
+        <property name="contextName" value="bob" />
+        <property name="serviceName" value="bob@service.ws.apache.org" />
+    </bean>-->
+	
+	<!-- Kerberos authentication provider -->
+    <bean id="stsKrbAuthProvider" class="org.apache.cxf.fediz.service.idp.STSKrbAuthenticationProvider">
+        <property name="wsdlLocation" value="https://localhost:0/fediz-idp-sts/${realm.STS_URI}/STSServiceTransportKerberos?wsdl" />
+        <property name="wsdlEndpoint" value="TransportKerberos_Port" />
+        <property name="wsdlService" value="SecurityTokenService" />
+        <property name="appliesTo" value="urn:fediz:idp" />
+        <property name="tokenType" value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
+        <!-- <property name="kerberosTokenValidator" ref="kerberosTokenValidator" />
+        <property name="requireDelegation" value="true" />-->
+    </bean>
+
+</beans>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/config/security-rs-config.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/config/security-rs-config.xml b/services/idp-core/src/main/webapp/WEB-INF/config/security-rs-config.xml
new file mode 100644
index 0000000..aa859b5
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/config/security-rs-config.xml
@@ -0,0 +1,64 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:security="http://www.springframework.org/schema/security"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xmlns:util="http://www.springframework.org/schema/util"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd
+        http://www.springframework.org/schema/security
+        http://www.springframework.org/schema/security/spring-security-3.2.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util-4.3.xsd
+        ">
+
+    <!-- DISABLE in production as it might log confidential information about the user -->
+    <!-- <security:debug /> -->
+
+    <security:http pattern="/services/rs/**" use-expressions="true" authentication-manager-ref="restAuthenticationManager">
+        <security:custom-filter after="CHANNEL_FILTER" ref="stsUPPortFilter" />
+        <security:custom-filter after="SERVLET_API_SUPPORT_FILTER" ref="entitlementsEnricher" />
+        <security:intercept-url pattern="/services/rs/**" access="isAuthenticated()" />
+        <security:http-basic />
+    </security:http>
+
+    <bean id="bCryptPasswordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" />
+    
+    <bean id="defaultPasswordEncoder" class="org.springframework.security.crypto.password.StandardPasswordEncoder" />
+    
+    <security:authentication-manager id="restAuthenticationManager">
+        <security:authentication-provider>
+          <!-- <security:password-encoder ref="defaultPasswordEncoder" />-->
+          <!-- <security:password-encoder hash="sha-256" base64="true" />-->
+          <!--  
+          <security:password-encoder hash="sha-256" base64="true">
+            <security:salt-source user-property="username" />
+          </security:password-encoder>
+          -->
+          <security:user-service properties="classpath:/users.properties" />
+        </security:authentication-provider>
+        <security:authentication-provider ref="stsUPAuthProvider" />
+    </security:authentication-manager>
+    
+</beans>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/config/security-up-config.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/config/security-up-config.xml b/services/idp-core/src/main/webapp/WEB-INF/config/security-up-config.xml
new file mode 100644
index 0000000..2ba5f86
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/config/security-up-config.xml
@@ -0,0 +1,94 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:security="http://www.springframework.org/schema/security"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xmlns:util="http://www.springframework.org/schema/util"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd
+        http://www.springframework.org/schema/security
+        http://www.springframework.org/schema/security/spring-security-3.2.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util-4.3.xsd
+        ">
+
+    <!-- DISABLE in production as it might log confidential information about the user -->
+    <!-- <security:debug /> -->
+
+    <!-- HTTP/BA entry point for WS-Federation -->
+    <security:http pattern="/federation/up/**" use-expressions="true">
+		<security:intercept-url requires-channel="https" pattern="/federation/up/login*" access="isAnonymous() or isAuthenticated()" />
+        <security:custom-filter after="CHANNEL_FILTER" ref="stsUPPortFilter" />
+        <security:custom-filter after="SERVLET_API_SUPPORT_FILTER" ref="entitlementsEnricher" />
+
+        <security:http-basic />
+	<!--security:form-login login-page='/federation/up/login'
+		login-processing-url="/federation/up/login.do"
+		authentication-failure-url="/federation/up/login?error" 
+		default-target-url="/"
+		username-parameter="username" 
+		password-parameter="password"
+	/-->
+	<security:logout logout-url="/federation/up/logout" 
+		logout-success-url="/federation/up/login?out" 
+		delete-cookies="FEDIZ_HOME_REALM,JSESSIONID" 
+		invalidate-session="true" 
+	/>
+    </security:http>
+    
+    <!-- HTTP/BA entry point for SAML SSO -->
+    <security:http pattern="/saml/up/**" use-expressions="true">
+		<security:intercept-url requires-channel="https" pattern="/saml/up/login*" access="isAnonymous() or isAuthenticated()" />
+        <security:custom-filter after="CHANNEL_FILTER" ref="stsUPPortFilter" />
+        <security:custom-filter after="SERVLET_API_SUPPORT_FILTER" ref="entitlementsEnricher" />
+
+        <security:http-basic />
+	<!--security:form-login login-page='/federation/up/login'
+		login-processing-url="/federation/up/login.do"
+		authentication-failure-url="/federation/up/login?error" 
+		default-target-url="/"
+		username-parameter="username" 
+		password-parameter="password"
+	/-->
+	<security:logout logout-url="/saml/up/logout" 
+		logout-success-url="/saml/up/login?out" 
+		delete-cookies="FEDIZ_HOME_REALM,JSESSIONID" 
+		invalidate-session="true" 
+	/>
+    </security:http>
+    
+    <bean id="stsUPPortFilter" class="org.apache.cxf.fediz.service.idp.STSPortFilter">
+        <property name="authenticationProvider" ref="stsUPAuthProvider" />
+    </bean>
+    
+    <!-- U/P Authentication Provider -->
+    <bean id="stsUPAuthProvider" class="org.apache.cxf.fediz.service.idp.STSUPAuthenticationProvider">
+        <property name="wsdlLocation" value="https://localhost:0/fediz-idp-sts/${realm.STS_URI}/STSServiceTransportUT?wsdl" />
+        <property name="wsdlEndpoint" value="TransportUT_Port" />
+        <property name="wsdlService" value="SecurityTokenService" />
+        <property name="appliesTo" value="urn:fediz:idp" />
+        <property name="tokenType" value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
+    </bean>
+    
+</beans>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/flows/federation-validate-request.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/flows/federation-validate-request.xml b/services/idp-core/src/main/webapp/WEB-INF/flows/federation-validate-request.xml
new file mode 100644
index 0000000..ea9ce68
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/flows/federation-validate-request.xml
@@ -0,0 +1,283 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<flow xmlns="http://www.springframework.org/schema/webflow"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://www.springframework.org/schema/webflow
+                          http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
+
+    <decision-state id="evaluateProtocol">
+        <on-entry>
+            <set name="flowScope.idpConfig" value="config.getIDP(fedizEntryPoint.getRealm())" />
+        </on-entry>
+        <if test="requestParameters.wa == 'wsignin1.0'" then="selectWsFedProcess" />
+        <if test="requestParameters.wa == 'wsignout1.0' or requestParameters.wa == 'wsignoutcleanup1.0'"
+            then="selectWsFedProcess" />
+        <if test="requestParameters.SAMLResponse != null" then="selectSAMLProcess"
+            else="selectOIDCAuthorizationCodeFlowProcess"
+        /> 
+    </decision-state>
+
+    <decision-state id="selectWsFedProcess">
+        <on-entry>
+            <set name="flowScope.wtrealm" value="requestParameters.wtrealm" />
+            <set name="flowScope.wreply" value="requestParameters.wreply" />
+            <set name="flowScope.wctx" value="requestParameters.wctx" />
+            <set name="flowScope.request_context" value="requestParameters.wctx" />
+            <set name="flowScope.wfresh" value="requestParameters.wfresh" />
+            <set name="flowScope.whr" value="requestParameters.whr" />
+            <set name="flowScope.wresult" value="requestParameters.wresult" />
+            <set name="flowScope.wreq" value="requestParameters.wreq" />
+            <evaluate expression="requestScope.getString('wauth','default')"
+                result="flowScope.wauth" />
+        </on-entry>
+        <if test="requestParameters.wa == 'wsignout1.0' or requestParameters.wa == 'wsignoutcleanup1.0'"
+            then="validateWReplyForSignout" />
+        <if test="requestParameters.wresult != null and !requestParameters.wresult.isEmpty()"
+            then="signinResponse" />
+        <if test="requestParameters.wtrealm != null and !requestParameters.wtrealm.isEmpty()"
+            then="signinRequest" else="viewBadRequest" />
+    </decision-state>
+    
+    <decision-state id="selectSAMLProcess">
+        <on-entry>
+            <set name="flowScope.RelayState" value="requestParameters.RelayState" />
+            <set name="flowScope.request_context" value="requestParameters.RelayState" />
+            <set name="flowScope.SAMLResponse" value="requestParameters.SAMLResponse" />
+        </on-entry>
+        <if test="requestParameters.RelayState == null or requestParameters.RelayState.isEmpty()"
+            then="viewBadRequest" />
+        <if test="requestParameters.SAMLResponse == null or requestParameters.SAMLResponse.isEmpty()"
+            then="viewBadRequest" else="signinResponse" />
+    </decision-state>
+    
+    <decision-state id="selectOIDCAuthorizationCodeFlowProcess">
+         <on-entry>
+            <set name="flowScope.state" value="requestParameters.state" />
+            <set name="flowScope.request_context" value="requestParameters.state" />
+            <set name="flowScope.code" value="requestParameters.code" />
+        </on-entry>
+        <if test="requestParameters.code == null or requestParameters.code.isEmpty()"
+            then="viewBadRequest" />
+        <if test="requestParameters.state == null or requestParameters.state.isEmpty()"
+            then="viewBadRequest" else="signinResponse" />
+    </decision-state>
+    
+    <action-state id="validateWReplyForSignout">
+        <evaluate expression="commonsURLValidator.isValid(flowRequestContext, flowScope.wreply)"/>
+        <transition on="yes" to="selectSignOutProcess" />
+        <transition on="no" to="viewBadRequestAndLogout" />
+    </action-state>
+	
+    <decision-state id="selectSignOutProcess">
+        <if test="requestParameters.wa == 'wsignout1.0' and flowScope.idpConfig.rpSingleSignOutConfirmation == true
+            or requestParameters.wa == 'wsignoutcleanup1.0' and flowScope.idpConfig.rpSingleSignOutCleanupConfirmation == true"
+            then="viewSignoutConfirmation" else="invalidateSessionAction" />
+    </decision-state>
+
+    <subflow-state id="signinRequest" subflow="signinRequest">
+        <input name="idpConfig" value="flowScope.idpConfig" />
+        <input name="realm" value="flowScope.wtrealm" />
+        <input name="wctx" value="flowScope.wctx" />
+        <input name="wfresh" value="flowScope.wfresh" />
+        <input name="wauth" value="flowScope.wauth" />
+        <input name="home_realm" value="flowScope.whr" />
+        <input name="protocol" value="'wsfed'" />
+        <input name="return_address" value="flowScope.wreply" />
+        <input name="request_context" value="flowScope.request_context" />
+
+        <output name="home_realm" />
+        <output name="idpToken" />
+        <output name="trusted_idp_context" />
+
+        <transition on="requestRpToken" to="requestRpToken">
+            <set name="flowScope.whr" value="currentEvent.attributes.home_realm" />
+            <set name="flowScope.idpToken" value="currentEvent.attributes.idpToken" />
+        </transition>
+        <transition on="viewBadRequest" to="viewBadRequest" />
+        <transition on="scInternalServerError" to="scInternalServerError" />
+        <transition on="redirectToTrustedIDP" to="processTrustedIdpProtocol">
+            <set name="flowScope.whr" value="currentEvent.attributes.home_realm" />
+            <set name="flowScope.trusted_idp_context" value="currentEvent.attributes.trusted_idp_context"/>
+        </transition>
+        <transition on="redirectToLocalIDP" to="redirectToLocalIDP">
+            <set name="flowScope.wctx" value="currentEvent.attributes.wctx" />
+        </transition>
+    </subflow-state>
+
+    <subflow-state id="signinResponse" subflow="signinResponse">
+        <input name="idpConfig" value="flowScope.idpConfig" />
+        <input name="wfresh" value="flowScope.wfresh" />
+        <input name="request_context" value="flowScope.request_context" />
+        <input name="wresult" value="flowScope.wresult" />
+        <input name="RelayState" value="flowScope.RelayState" />
+        <input name="SAMLResponse" value="flowScope.SAMLResponse" />
+        <input name="state" value="flowScope.state" />
+        <input name="code" value="flowScope.code" />
+        <input name="home_realm" value="flowScope.whr" />
+        <input name="protocol" value="'wsfed'" />
+
+        <output name="realm" />
+        <output name="return_address" />
+        <output name="request_context" />
+        <output name="home_realm" />
+        <output name="idpToken" />
+
+        <transition on="requestRpToken" to="requestRpToken">
+            <set name="flowScope.whr" value="currentEvent.attributes.home_realm" />
+            <set name="flowScope.wctx" value="currentEvent.attributes.request_context" />
+            <set name="flowScope.wtrealm" value="currentEvent.attributes.realm" />
+            <set name="flowScope.wreply" value="currentEvent.attributes.return_address" />
+            <set name="flowScope.idpToken" value="currentEvent.attributes.idpToken" />
+        </transition>
+        <transition on="viewBadRequest" to="viewBadRequest" />
+        <transition on="scInternalServerError" to="scInternalServerError" />
+    </subflow-state>
+    
+    <!-- produce RP security token (as String type) -->
+    <action-state id="requestRpToken">
+        <on-entry>
+            <evaluate expression="stsClientForRpAction.submit(flowRequestContext, flowScope.wtrealm, flowScope.whr)"
+                      result="flowScope.rpTokenElement"/>
+            <evaluate expression="tokenSerializer.serialize(flowRequestContext, flowScope.rpTokenElement)"
+                      result="flowScope.rpToken"/>
+        </on-entry>
+        <evaluate expression="signinParametersCacheAction.storeRPConfigInSession(flowRequestContext)" />
+        <transition to="isWReplyProvided" />
+        <transition on-exception="org.apache.cxf.fediz.core.exception.ProcessingException" to="viewBadRequest" />
+        <transition on-exception="java.lang.Throwable" to="scInternalServerError" />
+    </action-state>
+    
+    <action-state id="processTrustedIdpProtocol">
+        <evaluate expression="trustedIdpProtocolAction.mapSignInRequest(flowRequestContext, flowScope.whr)"
+                      result="flowScope.remoteIdpUrl"/>
+        <transition to="redirectToTrustedIDP" />
+        <transition on-exception="java.lang.Throwable" to="scInternalServerError" />
+    </action-state>
+
+    <action-state id="isWReplyProvided">
+        <evaluate expression="flowScope.wreply != null" />
+        <transition on="yes" to="formResponseView" >
+            <set name="flowScope.signinResponseUrl" value="flowScope.wreply" />
+        </transition>
+        <transition on="no" to="formResponseView" >
+            <set name="flowScope.signinResponseUrl" value="flowScope.wtrealm" />
+        </transition>
+    </action-state>
+
+    <!-- normal exit point for login -->
+    <!-- browser redirection (self-submitted form 'signinresponseform.jsp') -->
+    <end-state id="formResponseView" view="signinresponseform">
+        <on-entry>
+            <evaluate expression="flowScope.signinResponseUrl" result="requestScope.fedAction" />
+            <evaluate expression="flowScope.wtrealm" result="requestScope.fedWTrealm" />
+            <evaluate expression="flowScope.wctx" result="requestScope.fedWCtx" />
+            <evaluate expression="flowScope.rpToken" result="requestScope.fedWResult" />
+        </on-entry>
+    </end-state>
+
+    <!-- abnormal exit point : Http 400 Bad Request -->
+    <end-state id="viewBadRequest" view="genericerror">
+        <on-entry>
+            <evaluate
+                expression="externalContext.nativeResponse.setStatus(400,flowRequestContext.currentTransition.toString())" />
+            <!--<set name="requestScope.reason" value="flowRequestContext.currentTransition" />-->
+        </on-entry>
+    </end-state>
+    
+    <end-state id="viewBadRequestAndLogout" view="genericerror">
+        <on-entry>
+            <evaluate expression="homeRealmReminder.removeCookie(flowRequestContext)" />
+            <evaluate expression="logoutAction.submit(flowRequestContext)" />
+            <evaluate
+                expression="externalContext.nativeResponse.setStatus(400,flowRequestContext.currentTransition.toString())" />
+            <!--<set name="requestScope.reason" value="flowRequestContext.currentTransition" />-->
+        </on-entry>
+    </end-state>
+
+    <!-- abnormal exit point : Http 500 Internal Server Error -->
+    <end-state id="scInternalServerError" view="genericerror">
+        <on-entry>
+            <evaluate
+                expression="externalContext.nativeResponse.setStatus(500,'IDP is unavailable, please contact the administrator')" />
+            <set name="requestScope.reason"
+                value="'IDP is unavailable, please contact the administrator'" />
+            <set name="requestScope.stateException"
+                value="flowScope.stateException" />
+            <set name="requestScope.rootCauseException"
+                value="flowScope.rootCauseException" />
+        </on-entry>
+    </end-state>
+    
+    <!-- normal exit point for logout -->
+    <view-state id="viewSignoutConfirmation" view="signoutconfirmationresponse">
+        <transition on="submit" to="invalidateSessionAction"/>
+        <transition on="cancel" to="redirect" />
+    </view-state>
+
+    <view-state id="redirect" view="externalRedirect:#{flowScope.wreply}" />
+
+    <!-- normal exit point for logout -->
+    <end-state id="invalidateSessionAction" view="signoutresponse">
+        <on-entry>
+            <!-- store the realmConfigMap in the request map before we invalidate the session below.
+            Its needed in the signoutresponse.jsp page -->
+            <set name="externalContext.requestMap.realmConfigMap" 
+                value="externalContext.sessionMap.realmConfigMap"/>
+            <set name="externalContext.requestMap.wreply" value="flowScope.wreply"/>
+            <!-- there is no Saml token canceller in cxf STS...
+            <evaluate expression="stsClientForRpAction.cancelTokens(flowRequestContext)" />
+            -->
+            <evaluate expression="homeRealmReminder.removeCookie(flowRequestContext)" />
+            <evaluate expression="logoutAction.submit(flowRequestContext)" />
+        </on-entry>
+    </end-state>
+
+    <!-- redirect to remote idp -->
+    <end-state id="redirectToTrustedIDP" view="externalRedirect:#{flowScope.remoteIdpUrl}">
+    <!-- 
+        <on-entry>
+            <set name="flowScope.remoteIdpUrl"
+                value="flowScope.idpConfig.findTrustedIdp(flowScope.whr).url
+                +'?wa=wsignin1.0'
+                +'&amp;wtrealm='+flowScope.idpConfig.realm
+                +'&amp;wreply='+flowScope.idpConfig.idpUrl
+                +(flowScope.wfresh != null ? '&amp;wfresh='+flowScope.wfresh : '')
+                +(flowScope.wctx != null ? '&amp;wctx='+flowScope.wctx : '')">
+            </set>
+        </on-entry>
+         --> 
+    </end-state>
+
+    <end-state id="redirectToLocalIDP" view="externalRedirect:#{flowScope.localIdpUrl}">
+        <on-entry>
+            <set name="flowScope.localIdpUrl"
+                value="flowScope.idpConfig.idpUrl
+                +'?wa=wsignin1.0'
+                +'&amp;wreply='+flowScope.wreply
+                +'&amp;wtrealm='+flowScope.wtrealm
+                +(flowScope.wctx != null ? '&amp;wctx='+flowScope.wctx : '')
+                +(flowScope.wfresh != null ? '&amp;wfresh='+flowScope.wfresh : '')
+                +(flowScope.whr != null ? '&amp;whr='+flowScope.whr : '')
+                +(flowScope.wreq != null ? '&amp;wreq='+flowScope.wreq : '')">
+            </set>
+        </on-entry>
+    </end-state>
+
+</flow>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/flows/saml-validate-request.xml b/services/idp-core/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
new file mode 100644
index 0000000..1f12890
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/flows/saml-validate-request.xml
@@ -0,0 +1,259 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<flow xmlns="http://www.springframework.org/schema/webflow"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://www.springframework.org/schema/webflow
+                          http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
+
+    <decision-state id="evaluateProtocol">
+        <on-entry>
+            <set name="flowScope.idpConfig" value="config.getIDP(fedizEntryPoint.getRealm())" />
+        </on-entry>
+        <if test="requestParameters.wa == 'wsignin1.0'" then="selectWsFedProcess" />
+        <if test="requestParameters.SAMLRequest != null or requestParameters.SAMLResponse != null" 
+            then="selectSAMLProcess" else="selectOIDCAuthorizationCodeFlowProcess"
+        />
+    </decision-state>
+    
+    <decision-state id="selectWsFedProcess">
+        <on-entry>
+            <set name="flowScope.wresult" value="requestParameters.wresult" />
+            <set name="flowScope.wctx" value="requestParameters.wctx" />
+            <set name="flowScope.request_context" value="requestParameters.wctx" />
+        </on-entry>
+        <if test="requestParameters.wctx == null or requestParameters.wctx.isEmpty()"
+            then="viewBadRequest" />
+        <if test="requestParameters.wresult == null or requestParameters.wresult.isEmpty()"
+            then="viewBadRequest" />
+        <if test="requestParameters.wtrealm != null and !requestParameters.wtrealm.isEmpty()"
+            then="signinResponse" else="viewBadRequest" />
+    </decision-state>
+    
+    <decision-state id="selectSAMLProcess">
+        <on-entry>
+            <set name="flowScope.RelayState" value="requestParameters.RelayState" />
+            <set name="flowScope.request_context" value="requestParameters.RelayState" />
+            <set name="flowScope.SAMLResponse" value="requestParameters.SAMLResponse" />
+            <set name="flowScope.SAMLRequest" value="requestParameters.SAMLRequest" />
+            <set name="flowScope.Signature" value="requestParameters.Signature" />
+        </on-entry>
+        <if test="requestParameters.RelayState == null or requestParameters.RelayState.isEmpty()"
+            then="viewBadRequest" />
+        <if test="requestParameters.SAMLRequest != null and !requestParameters.SAMLRequest.isEmpty()"
+            then="parseSAMLAuthnRequest" />
+        <if test="requestParameters.SAMLResponse == null or requestParameters.SAMLResponse.isEmpty()"
+            then="viewBadRequest" else="signinResponse" />
+    </decision-state>
+    
+    <decision-state id="selectOIDCAuthorizationCodeFlowProcess">
+        <on-entry>
+            <set name="flowScope.state" value="requestParameters.state" />
+            <set name="flowScope.request_context" value="requestParameters.state" />
+            <set name="flowScope.code" value="requestParameters.code" />
+        </on-entry>
+        <if test="requestParameters.code == null or requestParameters.code.isEmpty()"
+            then="viewBadRequest" />
+        <if test="requestParameters.state == null or requestParameters.state.isEmpty()"
+            then="viewBadRequest" else="signinResponse" />
+    </decision-state>
+    
+    <action-state id="parseSAMLAuthnRequest">
+        <evaluate expression="authnRequestParser.parseSAMLRequest(flowRequestContext, flowScope.idpConfig,
+                                                              flowScope.SAMLRequest, flowScope.Signature,
+                                                              flowScope.RelayState)" />
+        <transition to="retrieveConsumerURL"/>
+        <transition on-exception="org.apache.cxf.fediz.core.exception.ProcessingException" to="viewBadRequest" />
+    </action-state>
+    
+    <action-state id="retrieveConsumerURL">
+        <evaluate expression="authnRequestParser.retrieveConsumerURL(flowRequestContext)" 
+                  result="flowScope.consumerURL"/>
+        <transition to="retrieveRealm"/>
+        <transition on-exception="org.apache.cxf.fediz.core.exception.ProcessingException" to="viewBadRequest" />
+    </action-state>
+    
+    <action-state id="retrieveRealm">
+        <evaluate expression="authnRequestParser.retrieveRealm(flowRequestContext)" 
+                  result="flowScope.realm"/>
+        <transition to="signinRequest"/>
+        <transition on-exception="org.apache.cxf.fediz.core.exception.ProcessingException" to="viewBadRequest" />
+    </action-state>
+    
+    <subflow-state id="signinRequest" subflow="signinRequest">
+        <input name="idpConfig" value="flowScope.idpConfig" />
+        <input name="SAMLRequest" value="flowScope.SAMLRequest" />
+        <input name="RelayState" value="flowScope.RelayState" />
+        <input name="Signature" value="flowScope.Signature" />
+        <input name="protocol" value="'samlsso'" />
+        <input name="saml_authn_request" value="flowScope.saml_authn_request" />
+        <input name="realm" value="flowScope.realm" />
+        <input name="home_realm" value="null" />
+        <input name="wfresh" value="null" />
+        <input name="return_address" value="flowScope.consumerURL" />
+        <input name="request_context" value="flowScope.request_context" />
+
+        <output name="home_realm" />
+        <output name="idpToken" />
+        <output name="trusted_idp_context" />
+
+        <transition on="requestRpToken" to="requestRpToken">
+            <set name="flowScope.home_realm" value="currentEvent.attributes.home_realm" />
+            <set name="flowScope.idpToken" value="currentEvent.attributes.idpToken" />
+        </transition>
+        <transition on="viewBadRequest" to="viewBadRequest" />
+        <transition on="scInternalServerError" to="scInternalServerError" />
+        <transition on="redirectToLocalIDP" to="redirectToLocalIDP" />
+        <transition on="redirectToTrustedIDP" to="processTrustedIdpProtocol">
+            <set name="flowScope.home_realm" value="currentEvent.attributes.home_realm" />
+            <set name="flowScope.trusted_idp_context" value="currentEvent.attributes.trusted_idp_context"/>
+        </transition>
+    </subflow-state>
+    
+     <subflow-state id="signinResponse" subflow="signinResponse">
+        <input name="idpConfig" value="flowScope.idpConfig" />
+        <input name="wfresh" value="flowScope.wfresh" />
+        <input name="request_context" value="flowScope.request_context" />
+        <input name="wresult" value="flowScope.wresult" />
+        <input name="RelayState" value="flowScope.RelayState" />
+        <input name="SAMLResponse" value="flowScope.SAMLResponse" />
+        <input name="state" value="flowScope.state" />
+        <input name="code" value="flowScope.code" />
+        <input name="home_realm" value="flowScope.whr" />
+        <input name="protocol" value="'samlsso'" />
+
+        <output name="home_realm" />
+        <output name="idpToken" />
+        <output name="saml_authn_request" />
+        <output name="request_context" />
+
+        <transition on="requestRpToken" to="requestRpToken">
+            <set name="flowScope.home_realm" value="currentEvent.attributes.home_realm" />
+            <set name="flowScope.idpToken" value="currentEvent.attributes.idpToken" />
+            <set name="flowScope.saml_authn_request" value="currentEvent.attributes.saml_authn_request" />
+            <set name="flowScope.RelayState" value="currentEvent.attributes.request_context" />
+        </transition>
+        <transition on="viewBadRequest" to="viewBadRequest" />
+        <transition on="scInternalServerError" to="scInternalServerError" />
+    </subflow-state>
+    
+    <!-- produce RP security token (as String type) -->
+    <action-state id="requestRpToken">
+        <on-entry>
+            <evaluate expression="authnRequestParser.retrieveRealm(flowRequestContext)" 
+                      result="flowScope.realm"/>
+            <evaluate expression="stsClientForRpAction.submit(flowRequestContext, flowScope.realm, flowScope.home_realm)"
+                      result="flowScope.rpTokenElement"/>
+        </on-entry>
+        <evaluate expression="signinParametersCacheAction.storeRPConfigInSession(flowRequestContext)"/>
+        <transition to="produceSAMLResponse" />
+        <transition on-exception="org.apache.cxf.fediz.core.exception.ProcessingException" to="viewBadRequest" />
+        <transition on-exception="java.lang.Throwable" to="scInternalServerError" />
+    </action-state>
+    
+    <action-state id="produceSAMLResponse">
+        <on-entry>
+            <evaluate expression="authnRequestParser.retrieveConsumerURL(flowRequestContext)" 
+                      result="flowScope.consumerURL"/>
+            <evaluate expression="authnRequestParser.retrieveRequestId(flowRequestContext)" 
+                      result="flowScope.requestId"/>
+            <evaluate expression="authnRequestParser.retrieveRequestIssuer(flowRequestContext)" 
+                      result="flowScope.requestIssuer"/>
+        </on-entry>
+        <evaluate expression="samlResponseCreator.createSAMLResponse(flowRequestContext, flowScope.idpConfig, flowScope.rpTokenElement,
+                                                                     flowScope.consumerURL, flowScope.requestId, flowScope.requestIssuer)"
+                  result="flowScope.rpResponse"/>                                               
+        <transition to="formResponseView" />
+    </action-state>
+    
+    <!-- normal exit point for login -->
+    <!-- browser redirection (self-submitted form 'samlsigninresponseform.jsp') -->
+    <end-state id="formResponseView" view="samlsigninresponseform">
+        <on-entry>
+            <evaluate expression="flowScope.consumerURL" result="requestScope.samlAction" />
+            <evaluate expression="flowScope.RelayState" result="requestScope.relayState" />
+            <evaluate expression="flowScope.rpResponse" result="requestScope.samlResponse" />
+        </on-entry>
+    </end-state>
+    
+    <action-state id="processTrustedIdpProtocol">
+        <evaluate expression="trustedIdpProtocolAction.mapSignInRequest(flowRequestContext, flowScope.home_realm)"
+                      result="flowScope.remoteIdpUrl"/>
+        <transition to="redirectToTrustedIDP" />
+        <transition on-exception="java.lang.Throwable" to="scInternalServerError" />
+    </action-state>
+
+    <!-- abnormal exit point -->
+    <decision-state id="viewBadRequest">
+        <on-entry>
+            <evaluate expression="authnRequestParser.retrieveConsumerURL(flowRequestContext)" 
+                      result="requestScope.samlAction"/>
+        </on-entry>
+        <!-- See if we managed to at least parse the request to get the response URL -->
+        <if test="requestScope.samlAction == null or requestScope.samlAction.isEmpty()"
+            then="viewBadRequestParsingError" else="viewBadRequestResponse"/>
+    </decision-state>
+    
+    <end-state id="viewBadRequestResponse" view="samlsigninresponseform">
+        <on-entry>
+            <evaluate expression="authnRequestParser.retrieveConsumerURL(flowRequestContext)" 
+                      result="requestScope.samlAction"/>
+            <evaluate expression="authnRequestParser.retrieveRequestId(flowRequestContext)" 
+                      result="flowScope.requestId"/>
+            <evaluate expression="flowScope.RelayState" result="requestScope.relayState" />
+            <evaluate expression="samlResponseErrorCreator.createSAMLResponse(flowRequestContext, true, flowScope.idpConfig, 
+                                                                     flowScope.requestId)"
+                      result="requestScope.samlResponse"/>     
+        </on-entry>
+    </end-state>
+    
+    <!-- abnormal exit point : Http 400 Bad Request -->
+    <end-state id="viewBadRequestParsingError" view="genericerror">
+        <on-entry>
+            <evaluate
+                expression="externalContext.nativeResponse.setStatus(400,'Error parsing SAML Request')" />
+            <set name="requestScope.reason" value="'Error parsing SAML Request'" />
+        </on-entry>
+    </end-state>
+
+    <!-- abnormal exit point : Http 500 Internal Server Error -->
+    <end-state id="scInternalServerError" view="genericerror">
+        <on-entry>
+            <evaluate
+                expression="externalContext.nativeResponse.setStatus(500,'IDP is unavailable, please contact the administrator')" />
+            <set name="requestScope.reason"
+                value="'IDP is unavailable, please contact the administrator'" />
+            <set name="requestScope.stateException"
+                value="flowScope.stateException" />
+            <set name="requestScope.rootCauseException"
+                value="flowScope.rootCauseException" />
+        </on-entry>
+    </end-state>
+    
+    <end-state id="redirectToLocalIDP" view="externalRedirect:#{flowScope.localIdpUrl}">
+        <on-entry>
+            <evaluate expression="localRedirectCreator.createRedirectURL(flowRequestContext, flowScope.idpConfig)"
+                      result="flowScope.localIdpUrl"/>
+        </on-entry>
+    </end-state>
+    
+    <!-- redirect to remote idp -->
+    <end-state id="redirectToTrustedIDP" view="externalRedirect:#{flowScope.remoteIdpUrl}" />
+
+</flow>


[14/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
new file mode 100644
index 0000000..7b8c3eb
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpSAMLProtocolHandler.java
@@ -0,0 +1,415 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.PrivateKey;
+import java.security.Signature;
+import java.security.cert.X509Certificate;
+import java.util.zip.DataFormatException;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.UriBuilder;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.apache.cxf.common.util.Base64Exception;
+import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.common.util.StringUtils;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.core.util.DOMUtils;
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.jaxrs.utils.ExceptionUtils;
+import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
+import org.apache.cxf.rs.security.saml.sso.AuthnRequestBuilder;
+import org.apache.cxf.rs.security.saml.sso.DefaultAuthnRequestBuilder;
+import org.apache.cxf.rs.security.saml.sso.EHCacheTokenReplayCache;
+import org.apache.cxf.rs.security.saml.sso.SAMLProtocolResponseValidator;
+import org.apache.cxf.rs.security.saml.sso.SAMLSSOResponseValidator;
+import org.apache.cxf.rs.security.saml.sso.SSOConstants;
+import org.apache.cxf.rs.security.saml.sso.SSOValidatorResponse;
+import org.apache.cxf.rs.security.saml.sso.TokenReplayCache;
+import org.apache.cxf.staxutils.StaxUtils;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.common.saml.OpenSAMLUtil;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.apache.xml.security.stax.impl.util.IDGenerator;
+import org.apache.xml.security.utils.Base64;
+import org.opensaml.core.xml.XMLObject;
+import org.opensaml.saml.saml2.core.AuthnRequest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+@Component
+public class TrustedIdpSAMLProtocolHandler extends AbstractTrustedIdpProtocolHandler {
+    /**
+     * Whether to sign the request or not. The default is "true".
+     */
+    public static final String SIGN_REQUEST = "sign.request";
+    
+    /**
+     * Whether to require a KeyInfo or not when processing a (signed) Response. The default is "true".
+     */
+    public static final String REQUIRE_KEYINFO = "require.keyinfo";
+    
+    /**
+     * Whether the assertions contained in the Response must be signed or not (if the response itself
+     * is not signed). The default is "true".
+     */
+    public static final String REQUIRE_SIGNED_ASSERTIONS = "require.signed.assertions";
+    
+    /**
+     * Whether we have to "know" the issuer of the SAML Response or not. The default is "true".
+     */
+    public static final String REQUIRE_KNOWN_ISSUER = "require.known.issuer";
+    
+    /**
+     * Whether we BASE-64 decode the response or not. The default is "true".
+     */
+    public static final String SUPPORT_BASE64_ENCODING = "support.base64.encoding";
+    
+    /**
+     * Whether we support Deflate encoding or not. The default is "false".
+     */
+    public static final String SUPPORT_DEFLATE_ENCODING = "support.deflate.encoding";
+
+    public static final String PROTOCOL = "urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser";
+
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpSAMLProtocolHandler.class);
+    private static final String SAML_SSO_REQUEST_ID = "saml-sso-request-id";
+
+    private AuthnRequestBuilder authnRequestBuilder = new DefaultAuthnRequestBuilder();
+    private TokenReplayCache<String> replayCache;
+
+    static {
+        OpenSAMLUtil.initSamlEngine();
+    }
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+
+    @Override
+    public URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+
+        try {
+            Document doc = DOMUtils.createDocument();
+            doc.appendChild(doc.createElement("root"));
+            // Create the AuthnRequest
+            AuthnRequest authnRequest = 
+                authnRequestBuilder.createAuthnRequest(
+                    null, idp.getRealm(), idp.getIdpUrl().toString()
+                );
+            
+            boolean signRequest = isBooleanPropertyConfigured(trustedIdp, SIGN_REQUEST, true);
+            if (signRequest) {
+                authnRequest.setDestination(trustedIdp.getUrl());
+            }
+            Element authnRequestElement = OpenSAMLUtil.toDom(authnRequest, doc);
+            String authnRequestEncoded = encodeAuthnRequest(authnRequestElement);
+
+            String urlEncodedRequest = URLEncoder.encode(authnRequestEncoded, "UTF-8");
+
+            UriBuilder ub = UriBuilder.fromUri(trustedIdp.getUrl());
+
+            ub.queryParam(SSOConstants.SAML_REQUEST, urlEncodedRequest);
+            
+            String wctx = context.getFlowScope().getString(IdpConstants.TRUSTED_IDP_CONTEXT);
+            ub.queryParam(SSOConstants.RELAY_STATE, wctx);
+            if (signRequest) {
+                signRequest(urlEncodedRequest, wctx, idp, ub);
+            }
+            
+            // Store the Request ID
+            String authnRequestId = authnRequest.getID();
+            WebUtils.putAttributeInExternalContext(context, SAML_SSO_REQUEST_ID, authnRequestId);
+
+            HttpServletResponse response = WebUtils.getHttpServletResponse(context);
+            response.addHeader("Cache-Control", "no-cache, no-store");
+            response.addHeader("Pragma", "no-cache");
+
+            return ub.build().toURL();
+        } catch (MalformedURLException ex) {
+            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
+            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
+        } catch (UnsupportedEncodingException ex) {
+            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
+            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
+        } catch (Exception ex) {
+            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
+            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
+        }
+    }
+
+    @Override
+    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+
+        try {
+            String encodedSAMLResponse = (String) WebUtils.getAttributeFromFlowScope(context, 
+                                                                                     SSOConstants.SAML_RESPONSE);
+            
+            // Read the response + convert to an OpenSAML Response Object
+            org.opensaml.saml.saml2.core.Response samlResponse = 
+                readSAMLResponse(encodedSAMLResponse, trustedIdp);
+            
+            Crypto crypto = CertsUtils.getCryptoFromCertificate(trustedIdp.getCertificate());
+            validateSamlResponseProtocol(samlResponse, crypto, trustedIdp);
+            // Validate the Response
+            SSOValidatorResponse validatorResponse = 
+                validateSamlSSOResponse(samlResponse, idp, trustedIdp, context);
+
+            // Create new Security token with new id. 
+            // Parameters for freshness computation are copied from original IDP_TOKEN
+            String id = IDGenerator.generateID("_");
+            SecurityToken idpToken = 
+                new SecurityToken(id, validatorResponse.getCreated(), validatorResponse.getSessionNotOnOrAfter());
+
+            idpToken.setToken(validatorResponse.getAssertionElement());
+            String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
+            LOG.info("[IDP_TOKEN={}] created from [RP_TOKEN={}] issued by home realm [{}]",
+                     id, validatorResponse.getResponseId(), whr);
+            LOG.debug("Created date={}", validatorResponse.getCreated());
+            LOG.debug("Expired date={}", validatorResponse.getSessionNotOnOrAfter());
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Validated: "
+                    + System.getProperty("line.separator") + validatorResponse.getAssertion());
+            }
+            return idpToken;
+        } catch (BadRequestException ex) {
+            throw ex;
+        } catch (Exception ex) {
+            LOG.warn("Unexpected exception occured", ex);
+            throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
+        }
+    }
+    
+    private String encodeAuthnRequest(Element authnRequest) throws IOException {
+        String requestMessage = DOM2Writer.nodeToString(authnRequest);
+        
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(requestMessage);
+        }
+
+        DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
+        byte[] deflatedBytes = encoder.deflateToken(requestMessage.getBytes("UTF-8"));
+
+        return Base64Utility.encode(deflatedBytes);
+    }
+    
+    /**
+     * Sign a request according to the redirect binding spec for Web SSO
+     */
+    private void signRequest(
+        String authnRequest,
+        String relayState,
+        Idp config,
+        UriBuilder ub
+    ) throws Exception {
+        Crypto crypto = CertsUtils.getCryptoFromCertificate(config.getCertificate());
+        if (crypto == null) {
+            LOG.error("No crypto instance of properties file configured for signature");
+            throw new IllegalStateException("Invalid IdP configuration");
+        }
+        
+        String alias = crypto.getDefaultX509Identifier();
+        X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, alias);
+        if (cert == null) {
+            LOG.error("No cert was found to sign the request using alias: " + alias);
+            throw new IllegalStateException("Invalid IdP configuration");
+        }
+
+        String sigAlgo = SSOConstants.RSA_SHA1;
+        String pubKeyAlgo = cert.getPublicKey().getAlgorithm();
+        String jceSigAlgo = "SHA1withRSA";
+        LOG.debug("automatic sig algo detection: " + pubKeyAlgo);
+        if (pubKeyAlgo.equalsIgnoreCase("DSA")) {
+            sigAlgo = SSOConstants.DSA_SHA1;
+            jceSigAlgo = "SHA1withDSA";
+        }
+        LOG.debug("Using Signature algorithm " + sigAlgo);
+        
+        ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, "UTF-8"));
+        
+        // Get the password
+        String password = config.getCertificatePassword();
+        
+        // Get the private key
+        PrivateKey privateKey = crypto.getPrivateKey(alias, password);
+        
+        // Sign the request
+        Signature signature = Signature.getInstance(jceSigAlgo);
+        signature.initSign(privateKey);
+       
+        String requestToSign = 
+            SSOConstants.SAML_REQUEST + "=" + authnRequest + "&"
+            + SSOConstants.RELAY_STATE + "=" + relayState + "&"
+            + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, "UTF-8");
+
+        signature.update(requestToSign.getBytes("UTF-8"));
+        byte[] signBytes = signature.sign();
+        
+        String encodedSignature = Base64.encode(signBytes);
+        
+        ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, "UTF-8"));
+    }
+
+    private org.opensaml.saml.saml2.core.Response readSAMLResponse(String samlResponse, TrustedIdp trustedIdp) {
+        if (StringUtils.isEmpty(samlResponse)) {
+            throw ExceptionUtils.toBadRequestException(null, null);
+        }
+
+        String samlResponseDecoded = samlResponse;
+        
+        InputStream tokenStream = null;
+        if (isBooleanPropertyConfigured(trustedIdp, SUPPORT_BASE64_ENCODING, true)) {
+            try {
+                byte[] deflatedToken = Base64Utility.decode(samlResponseDecoded);
+                tokenStream = isBooleanPropertyConfigured(trustedIdp, SUPPORT_DEFLATE_ENCODING, false)
+                    ? new DeflateEncoderDecoder().inflateToken(deflatedToken)
+                    : new ByteArrayInputStream(deflatedToken); 
+            } catch (Base64Exception ex) {
+                throw ExceptionUtils.toBadRequestException(ex, null);
+            } catch (DataFormatException ex) {
+                throw ExceptionUtils.toBadRequestException(ex, null);
+            }
+        } else {
+            try {
+                tokenStream = new ByteArrayInputStream(samlResponseDecoded.getBytes("UTF-8"));
+            } catch (UnsupportedEncodingException ex) {
+                throw ExceptionUtils.toBadRequestException(ex, null);
+            }
+        }
+
+        Document responseDoc = null;
+        try {
+            responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, "UTF-8"));
+        } catch (Exception ex) {
+            throw new WebApplicationException(400);
+        }
+        
+        LOG.debug("Received response: " + DOM2Writer.nodeToString(responseDoc.getDocumentElement()));
+        
+        XMLObject responseObject = null;
+        try {
+            responseObject = OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
+        } catch (WSSecurityException ex) {
+            throw ExceptionUtils.toBadRequestException(ex, null);
+        }
+        if (!(responseObject instanceof org.opensaml.saml.saml2.core.Response)) {
+            throw ExceptionUtils.toBadRequestException(null, null);
+        }
+        return (org.opensaml.saml.saml2.core.Response)responseObject;
+
+    }
+    
+    /**
+     * Validate the received SAML Response as per the protocol
+     */
+    private void validateSamlResponseProtocol(
+        org.opensaml.saml.saml2.core.Response samlResponse, Crypto crypto, TrustedIdp trustedIdp
+    ) {
+        try {
+            SAMLProtocolResponseValidator protocolValidator = new SAMLProtocolResponseValidator();
+            protocolValidator.setKeyInfoMustBeAvailable(
+                isBooleanPropertyConfigured(trustedIdp, REQUIRE_KEYINFO, true));
+            protocolValidator.validateSamlResponse(samlResponse, crypto, null);
+        } catch (WSSecurityException ex) {
+            LOG.debug(ex.getMessage(), ex);
+            throw ExceptionUtils.toBadRequestException(null, null);
+        }
+    }
+    
+    /**
+     * Validate the received SAML Response as per the Web SSO profile
+     */
+    private SSOValidatorResponse validateSamlSSOResponse(
+        org.opensaml.saml.saml2.core.Response samlResponse,
+        Idp idp, 
+        TrustedIdp trustedIdp,
+        RequestContext requestContext
+    ) {
+        try {
+            SAMLSSOResponseValidator ssoResponseValidator = new SAMLSSOResponseValidator();
+            ssoResponseValidator.setAssertionConsumerURL(idp.getIdpUrl().toString());
+
+            HttpServletRequest servletRequest = WebUtils.getHttpServletRequest(requestContext);
+            ssoResponseValidator.setClientAddress(servletRequest.getRemoteAddr());
+
+            String issuer = trustedIdp.getIssuer();
+            if (issuer == null || issuer.isEmpty()) {
+                LOG.debug("Issuer name is not defined in trusted 3rd party configuration. "
+                    + "Using URL instead for issuer validation");
+                issuer = trustedIdp.getUrl();
+            }
+            LOG.debug("Using {} for issuer validation", issuer);
+            ssoResponseValidator.setIssuerIDP(issuer);
+            
+            // Get the stored request ID
+            String requestId = 
+                (String)WebUtils.getAttributeFromExternalContext(requestContext, SAML_SSO_REQUEST_ID);
+            ssoResponseValidator.setRequestId(requestId);
+            ssoResponseValidator.setSpIdentifier(idp.getRealm());
+            ssoResponseValidator.setEnforceAssertionsSigned(
+                isBooleanPropertyConfigured(trustedIdp, REQUIRE_SIGNED_ASSERTIONS, true));
+            ssoResponseValidator.setEnforceKnownIssuer(
+                isBooleanPropertyConfigured(trustedIdp, REQUIRE_KNOWN_ISSUER, true));
+            
+            HttpServletRequest httpServletRequest = WebUtils.getHttpServletRequest(requestContext);
+            boolean post = "POST".equals(httpServletRequest.getMethod());
+            if (post) {
+                ssoResponseValidator.setReplayCache(getReplayCache());
+            }
+
+            return ssoResponseValidator.validateSamlResponse(samlResponse, post);
+        } catch (WSSecurityException ex) {
+            LOG.debug(ex.getMessage(), ex);
+            throw ExceptionUtils.toBadRequestException(ex, null);
+        }
+    }
+    
+    public void setReplayCache(TokenReplayCache<String> replayCache) {
+        this.replayCache = replayCache;
+    }
+    
+    public TokenReplayCache<String> getReplayCache() {
+        if (replayCache == null) {
+            replayCache = new EHCacheTokenReplayCache();
+        }
+        return replayCache;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
new file mode 100644
index 0000000..ea8feb4
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpWSFedProtocolHandler.java
@@ -0,0 +1,231 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.security.cert.X509Certificate;
+import java.util.Collections;
+
+import org.w3c.dom.Element;
+import org.apache.cxf.fediz.core.FederationConstants;
+import org.apache.cxf.fediz.core.config.FedizContext;
+import org.apache.cxf.fediz.core.config.TrustManager;
+import org.apache.cxf.fediz.core.config.jaxb.AudienceUris;
+import org.apache.cxf.fediz.core.config.jaxb.CertificateStores;
+import org.apache.cxf.fediz.core.config.jaxb.ContextConfig;
+import org.apache.cxf.fediz.core.config.jaxb.FederationProtocolType;
+import org.apache.cxf.fediz.core.config.jaxb.KeyStoreType;
+import org.apache.cxf.fediz.core.config.jaxb.TrustManagersType;
+import org.apache.cxf.fediz.core.config.jaxb.TrustedIssuerType;
+import org.apache.cxf.fediz.core.config.jaxb.TrustedIssuers;
+import org.apache.cxf.fediz.core.config.jaxb.ValidationType;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.processor.FederationProcessorImpl;
+import org.apache.cxf.fediz.core.processor.FedizProcessor;
+import org.apache.cxf.fediz.core.processor.FedizRequest;
+import org.apache.cxf.fediz.core.processor.FedizResponse;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.common.crypto.CertificateStore;
+import org.apache.xml.security.stax.impl.util.IDGenerator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+@Component
+public class TrustedIdpWSFedProtocolHandler extends AbstractTrustedIdpProtocolHandler {
+    
+    /**
+     * Whether to add the home realm parameter to the URL for redirection or not. The default is "true".
+     */
+    public static final String HOME_REALM_PROPAGATION = "home.realm.propagation";
+    
+    public static final String PROTOCOL = "http://docs.oasis-open.org/wsfed/federation/200706";
+
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpWSFedProtocolHandler.class);
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+    
+    @Override
+    public URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+        
+        try {
+            StringBuilder sb = new StringBuilder();
+            sb.append(trustedIdp.getUrl());
+            sb.append("?").append(FederationConstants.PARAM_ACTION).append('=');
+            sb.append(FederationConstants.ACTION_SIGNIN);
+            sb.append("&").append(FederationConstants.PARAM_TREALM).append('=');
+            sb.append(URLEncoder.encode(idp.getRealm(), "UTF-8"));
+            sb.append("&").append(FederationConstants.PARAM_REPLY).append('=');
+            sb.append(URLEncoder.encode(idp.getIdpUrl().toString(), "UTF-8"));
+            
+            if (isBooleanPropertyConfigured(trustedIdp, HOME_REALM_PROPAGATION, true)) {
+                sb.append("&").append(FederationConstants.PARAM_HOME_REALM).append('=');
+                sb.append(trustedIdp.getRealm());
+            }
+            
+            String wfresh = context.getFlowScope().getString(FederationConstants.PARAM_FRESHNESS);
+            if (wfresh != null) {
+                sb.append("&").append(FederationConstants.PARAM_FRESHNESS).append('=');
+                sb.append(URLEncoder.encode(wfresh, "UTF-8"));
+            }
+            String wctx = context.getFlowScope().getString(IdpConstants.TRUSTED_IDP_CONTEXT);
+            sb.append("&").append(FederationConstants.PARAM_CONTEXT).append('=');
+            sb.append(wctx);
+        
+            return new URL(sb.toString());
+        } catch (MalformedURLException ex) {
+            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
+            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
+        } catch (UnsupportedEncodingException ex) {
+            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
+            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
+        }
+    }
+    
+    @Override
+    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+
+        try {
+            String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
+    
+            if (whr == null) {
+                LOG.warn("Home realm is null");
+                throw new IllegalStateException("Home realm is null");
+            }
+    
+            String wresult = (String) WebUtils.getAttributeFromFlowScope(context,
+                                                                         FederationConstants.PARAM_RESULT);
+    
+            if (wresult == null) {
+                LOG.warn("Parameter wresult not found");
+                throw new IllegalStateException("No security token issued");
+            }
+    
+            FedizContext fedContext = getFedizContext(idp, trustedIdp);
+    
+            FedizRequest wfReq = new FedizRequest();
+            wfReq.setAction(FederationConstants.ACTION_SIGNIN);
+            wfReq.setResponseToken(wresult);
+    
+            FedizProcessor wfProc = new FederationProcessorImpl();
+            FedizResponse wfResp = wfProc.processRequest(wfReq, fedContext);
+    
+            fedContext.close();
+    
+            Element e = wfResp.getToken();
+    
+            // Create new Security token with new id. 
+            // Parameters for freshness computation are copied from original IDP_TOKEN
+            String id = IDGenerator.generateID("_");
+            SecurityToken idpToken = new SecurityToken(id,
+                                                       wfResp.getTokenCreated(), wfResp.getTokenExpires());
+    
+            idpToken.setToken(e);
+            LOG.info("[IDP_TOKEN={}] for user '{}' created from [RP_TOKEN={}] issued by home realm [{}/{}]",
+                     id, wfResp.getUsername(), wfResp.getUniqueTokenId(), whr, wfResp.getIssuer());
+            LOG.debug("Created date={}", wfResp.getTokenCreated());
+            LOG.debug("Expired date={}", wfResp.getTokenExpires());
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Validated 'wresult' : "
+                    + System.getProperty("line.separator") + wresult);
+            }
+            return idpToken;
+        } catch (IllegalStateException ex) {
+            throw ex;
+        } catch (Exception ex) {
+            LOG.warn("Unexpected exception occured", ex);
+            throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
+        }
+    }
+    
+    
+    private FedizContext getFedizContext(Idp idpConfig,
+            TrustedIdp trustedIdpConfig) throws ProcessingException {
+
+        ContextConfig config = new ContextConfig();
+
+        config.setName("whatever");
+
+        // Configure certificate store
+        String certificate = trustedIdpConfig.getCertificate();
+        boolean isCertificateLocation = !certificate.startsWith("-----BEGIN CERTIFICATE");
+        if (isCertificateLocation) {
+            CertificateStores certStores = new CertificateStores();
+            TrustManagersType tm0 = new TrustManagersType();
+            KeyStoreType ks0 = new KeyStoreType();
+            ks0.setType("PEM");
+            // ks0.setType("JKS");
+            // ks0.setPassword("changeit");
+            ks0.setFile(trustedIdpConfig.getCertificate());
+            tm0.setKeyStore(ks0);
+            certStores.getTrustManager().add(tm0);
+            config.setCertificateStores(certStores);
+        }
+        
+        // Configure trusted IDP
+        TrustedIssuers trustedIssuers = new TrustedIssuers();
+        TrustedIssuerType ti0 = new TrustedIssuerType();
+        ti0.setCertificateValidation(ValidationType.PEER_TRUST);
+        ti0.setName(trustedIdpConfig.getName());
+        // ti0.setSubject(".*CN=www.sts.com.*");
+        trustedIssuers.getIssuer().add(ti0);
+        config.setTrustedIssuers(trustedIssuers);
+
+        FederationProtocolType protocol = new FederationProtocolType();
+        config.setProtocol(protocol);
+
+        AudienceUris audienceUris = new AudienceUris();
+        audienceUris.getAudienceItem().add(idpConfig.getRealm());
+        config.setAudienceUris(audienceUris);
+
+        FedizContext fedContext = new FedizContext(config);
+        if (!isCertificateLocation) {
+            CertificateStore cs = null;
+            
+            X509Certificate cert;
+            try {
+                cert = CertsUtils.parseX509Certificate(trustedIdpConfig.getCertificate());
+            } catch (Exception ex) {
+                LOG.error("Failed to parse trusted certificate", ex);
+                throw new ProcessingException("Failed to parse trusted certificate");
+            }
+            cs = new CertificateStore(Collections.singletonList(cert).toArray(new X509Certificate[0]));
+            
+            TrustManager tm = new TrustManager(cs);
+            fedContext.getCertificateStores().add(tm);
+        }
+        
+        fedContext.init();
+        return fedContext;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
new file mode 100644
index 0000000..2034dca
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationService.java
@@ -0,0 +1,88 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.List;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
+
+import org.springframework.security.access.prepost.PreAuthorize;
+
+
+@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Path("applications")
+public interface ApplicationService {
+
+    @GET
+    @PreAuthorize("hasRole('APPLICATION_LIST')")
+    Applications getApplications(@QueryParam("start") int start,
+                                 @QueryParam("size") @DefaultValue("2") int size,
+                                 @QueryParam("expand") @DefaultValue("all")  List<String> expand,
+                                 @Context UriInfo uriInfo);
+
+    @GET
+    @Path("{realm}")
+    @PreAuthorize("hasRole('APPLICATION_LIST')")
+    Application getApplication(@PathParam("realm") String realm,
+                               @QueryParam("expand") @DefaultValue("all")  List<String> expand);
+
+    @POST
+    @PreAuthorize("hasRole('APPLICATION_CREATE')")
+    Response addApplication(@Context UriInfo ui, Application service);
+    
+    @PUT
+    @Path("{realm}")
+    @PreAuthorize("hasRole('APPLICATION_UPDATE')")
+    Response updateApplication(@Context UriInfo ui, @PathParam("realm") String realm, Application application);
+    
+    @DELETE
+    @Path("{realm}")
+    @PreAuthorize("hasRole('APPLICATION_DELETE')")
+    Response deleteApplication(@PathParam("realm") String realm);
+    
+    @POST
+    @Path("{realm}/claims")
+    @PreAuthorize("hasRole('APPLICATION_UPDATE')")
+    Response addClaimToApplication(@Context UriInfo ui, @PathParam("realm") String realm, RequestClaim claim);
+    
+    @DELETE
+    @Path("{realm}/claims/{claimType}")
+    @PreAuthorize("hasRole('APPLICATION_UPDATE')")
+    Response removeClaimFromApplication(@Context UriInfo ui, @PathParam("realm") String realm,
+                                        @PathParam("claimType") String claimType);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
new file mode 100644
index 0000000..1b2f6ff
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ApplicationServiceImpl.java
@@ -0,0 +1,151 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.net.URI;
+import java.util.List;
+
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.UriBuilder;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
+import org.apache.cxf.fediz.service.idp.service.ApplicationDAO;
+import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ApplicationServiceImpl implements ApplicationService {
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(ApplicationServiceImpl.class);
+
+    @Autowired
+    private ApplicationDAO applicationDAO;
+    
+    @Autowired
+    private ClaimDAO claimDAO;
+           
+    @Override
+    public Applications getApplications(int start, int size, List<String> expand, UriInfo uriInfo) {
+        List<Application> applications = applicationDAO.getApplications(start, size, expand);
+        
+        for (Application a : applications) {
+            URI self = uriInfo.getAbsolutePathBuilder().path(a.getRealm()).build();
+            a.setHref(self);
+        }
+        
+        Applications list = new Applications();
+        list.setApplications(applications);
+        return list;
+    }
+    
+    @Override
+    public Application getApplication(String realm, List<String> expand) {
+        Application application = applicationDAO.getApplication(realm, expand);
+        if (application == null) {
+            throw new NotFoundException();
+        } else {
+            return application;
+        }
+    }
+    
+    @Override
+    public Response addApplication(UriInfo ui, Application application) {
+        LOG.info("add Service config");
+        if (application.getRequestedClaims() != null && application.getRequestedClaims().size() > 0) {
+            LOG.warn("Application resource contains sub resource 'claims'");
+            throw new WebApplicationException(Status.BAD_REQUEST);
+        }
+        Application createdApplication = applicationDAO.addApplication(application);
+        
+        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
+        uriBuilder.path("{index}");
+        URI location = uriBuilder.build(createdApplication.getRealm());
+        return Response.created(location).entity(application).build();
+    }
+    
+    @Override
+    public Response updateApplication(UriInfo ui, String realm, Application application) {
+        if (!realm.equals(application.getRealm().toString())) {
+            throw new BadRequestException();
+        }
+        if (application.getRequestedClaims() != null && application.getRequestedClaims().size() > 0) {
+            LOG.warn("Application resource contains sub resource 'claims'");
+            throw new WebApplicationException(Status.BAD_REQUEST);
+        }
+        applicationDAO.updateApplication(realm, application);
+        
+        return Response.noContent().build();
+    }
+ 
+    @Override
+    public Response deleteApplication(String realm) {
+        applicationDAO.deleteApplication(realm);
+        
+        return Response.noContent().build();
+    }
+    
+    @Override
+    public Response addClaimToApplication(UriInfo ui, String realm, RequestClaim claim) {
+        Application application = applicationDAO.getApplication(realm, null);
+        if (application.getRequestedClaims().contains(claim)) {
+            LOG.warn("Claim '" + claim.getClaimType() + "' already added");
+            //[TODO] Status.CONFLICT correct if the relation to with Claim already exists
+            throw new WebApplicationException(Status.CONFLICT);
+        }
+        Claim foundClaim = claimDAO.getClaim(claim.getClaimType().toString());
+        RequestClaim rc = new RequestClaim(foundClaim);
+        application.getRequestedClaims().add(rc);
+        applicationDAO.addClaimToApplication(application, claim);
+        
+        return Response.noContent().build();
+    }
+    
+    @Override
+    public Response removeClaimFromApplication(UriInfo ui, String realm,  String claimType) {
+        Application application = applicationDAO.getApplication(realm, null);
+        
+        RequestClaim foundItem = null; 
+        for (RequestClaim item : application.getRequestedClaims()) {
+            if (item.getClaimType().toString().equals(claimType)) {
+                foundItem = item;
+                break;
+            }
+        }
+        if (foundItem == null) {
+            LOG.warn("Claim '" + claimType + "' not found");
+            throw new WebApplicationException(Status.NOT_FOUND);
+        }
+        application.getRequestedClaims().remove(foundItem);
+        applicationDAO.removeClaimFromApplication(application, foundItem);
+        
+        return Response.noContent().build();
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Applications.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Applications.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Applications.java
new file mode 100644
index 0000000..5773a07
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Applications.java
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.Collection;
+
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+
+@XmlRootElement(name = "applications", namespace = "http://org.apache.cxf.fediz/")
+public class Applications {
+
+    private Collection<Application> applications;
+
+    public Applications() {
+    }
+
+    public Applications(Collection<Application> applications) {
+        this.applications = applications;
+    }
+
+    @XmlElementRef
+    public Collection<Application> getApplications() {
+        return applications;
+    }
+
+    public void setApplications(Collection<Application> applications) {
+        this.applications = applications;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
new file mode 100644
index 0000000..47dac60
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimService.java
@@ -0,0 +1,72 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+
+import org.springframework.security.access.prepost.PreAuthorize;
+
+
+@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Path("claims")
+public interface ClaimService {
+
+    @GET
+    @PreAuthorize("hasRole('CLAIM_LIST')")
+    Response getClaims(@QueryParam("start") int start,
+                       @QueryParam("size") @DefaultValue("2") int size,
+                       @Context UriInfo uriInfo);
+    
+    @GET
+    @Path("{claimType}")
+    @PreAuthorize("hasRole('CLAIM_READ')")
+    Claim getClaim(@PathParam("claimType") String claimType);
+
+    @POST
+    @PreAuthorize("hasRole('CLAIM_CREATE')")
+    Response addClaim(@Context UriInfo ui, Claim claim);
+    
+    @PUT
+    @Path("{claimType}")
+    @PreAuthorize("hasRole('CLAIM_UPDATE')")
+    Response updateClaim(@Context UriInfo ui, @PathParam("claimType") String claimType, Claim claim);
+    
+    @DELETE
+    @Path("{claimType}")
+    @PreAuthorize("hasRole('CLAIM_DELETE')")
+    Response deleteClaim(@PathParam("claimType") String claimType);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
new file mode 100644
index 0000000..141bfab
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/ClaimServiceImpl.java
@@ -0,0 +1,106 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.net.URI;
+import java.util.List;
+
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ClaimServiceImpl implements ClaimService {
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(ClaimServiceImpl.class);
+
+    @Autowired
+    private ClaimDAO claimDAO;
+
+    @Override
+    public Response getClaims(int start, int size, UriInfo uriInfo) {
+        List<Claim> claims = claimDAO.getClaims(start, size);
+        
+        for (Claim c : claims) {
+            URI self = uriInfo.getAbsolutePathBuilder().path(c.getClaimType().toString()).build();
+            c.setHref(self);
+        }
+        
+        Claims list = new Claims();
+        list.setClaims(claims);
+        
+        
+        //return Response.ok(list).type(MediaType.APPLICATION_JSON_TYPE).build();
+        return Response.ok(list).build();
+    }
+    
+    @Override
+    public Response addClaim(UriInfo ui, Claim claim) {
+        LOG.info("add Claim config");
+        
+        Claim createdClaim = claimDAO.addClaim(claim);
+        
+        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
+        uriBuilder.path("{index}");
+        URI location = uriBuilder.build(createdClaim.getClaimType().toString());
+        return Response.created(location).entity(claim).build();
+    }
+    
+    @Override
+    public Claim getClaim(String claimType) {
+        Claim claim = claimDAO.getClaim(claimType);
+        if (claim == null) {
+            throw new NotFoundException();
+        } else {
+            return claim;
+        }
+    }
+
+    @Override
+    public Response updateClaim(UriInfo ui, String claimType, Claim claim) {
+        if (!claimType.equals(claim.getClaimType().toString())) {
+            throw new BadRequestException();
+        }
+        claimDAO.updateClaim(claimType, claim);
+        
+        return Response.noContent().build();
+    }
+
+    @Override
+    public Response deleteClaim(String claimType) {
+        claimDAO.deleteClaim(claimType);
+        
+        return Response.noContent().build();
+    }
+           
+    
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Claims.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Claims.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Claims.java
new file mode 100644
index 0000000..891effd
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Claims.java
@@ -0,0 +1,50 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.Collection;
+
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+
+@XmlRootElement(name = "claims", namespace = "http://org.apache.cxf.fediz/")
+public class Claims {
+
+    private Collection<Claim> claims;
+
+    public Claims() {
+    }
+
+    public Claims(Collection<Claim> claims) {
+        this.claims = claims;
+    }
+
+    @XmlElementRef
+    public Collection<Claim> getClaims() {
+        return claims;
+    }
+
+    public void setClaims(Collection<Claim> claims) {
+        this.claims = claims;
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
new file mode 100644
index 0000000..4bc392c
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementService.java
@@ -0,0 +1,73 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+
+import org.springframework.security.access.prepost.PreAuthorize;
+
+
+@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Path("entitlements")
+public interface EntitlementService {
+
+    @GET
+    @PreAuthorize("hasRole('ENTITLEMENT_LIST')")
+    Entitlements getEntitlements(@QueryParam("start") int start,
+                                 @QueryParam("size") @DefaultValue("5") int size,
+                                 @Context UriInfo uriInfo);
+
+    @GET
+    @Path("{name}")
+    @PreAuthorize("hasRole('ENTITLEMENT_READ')")
+    Entitlement getEntitlement(@PathParam("name") String name);
+
+    @POST
+    @PreAuthorize("hasRole('ENTITLEMENT_CREATE')")
+    Response addEntitlement(@Context UriInfo ui, Entitlement entitlement);
+    
+    @PUT
+    @Path("{name}")
+    @PreAuthorize("hasRole('ENTITLEMENT_UPDATE')")
+    Response updateEntitlement(@Context UriInfo ui, @PathParam("name") String name, Entitlement entitlement);
+    
+    @DELETE
+    @Path("{name}")
+    @PreAuthorize("hasRole('ENTITLEMENT_DELETE')")
+    Response deleteEntitlement(@PathParam("name") String name);
+    
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
new file mode 100644
index 0000000..9c89c04
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/EntitlementServiceImpl.java
@@ -0,0 +1,98 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.net.URI;
+import java.util.List;
+
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriBuilder;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+import org.apache.cxf.fediz.service.idp.service.EntitlementDAO;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class EntitlementServiceImpl implements EntitlementService {
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(EntitlementServiceImpl.class);
+
+    @Autowired
+    private EntitlementDAO entitlementDAO;
+
+    @Override
+    public Entitlements getEntitlements(int start, int size, UriInfo uriInfo) {
+        List<Entitlement> entitlements = entitlementDAO.getEntitlements(start, size);
+        
+        Entitlements list = new Entitlements();
+        list.setEntitlements(entitlements);
+        
+        return list;
+    }
+    
+    @Override
+    public Response addEntitlement(UriInfo ui, Entitlement entitlement) {
+        Entitlement createdEntitlement = entitlementDAO.addEntitlement(entitlement);
+        
+        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
+        uriBuilder.path("{index}");
+        URI location = uriBuilder.build(createdEntitlement.getName());
+        
+        LOG.debug("Entitlement '" + createdEntitlement.getName() + "' added");
+        return Response.created(location).entity(entitlement).build();
+    }
+    
+    @Override
+    public Entitlement getEntitlement(String name) {
+        Entitlement entitlement = entitlementDAO.getEntitlement(name);
+        if (entitlement == null) {
+            throw new NotFoundException();
+        } else {
+            return entitlement;
+        }
+    }
+
+    @Override
+    public Response updateEntitlement(UriInfo ui, String name, Entitlement entitlement) {
+        if (!name.equals(entitlement.getName())) {
+            throw new BadRequestException();
+        }
+        entitlementDAO.updateEntitlement(name, entitlement);
+        
+        LOG.debug("Entitlement '" + entitlement.getName() + "' updated");
+        return Response.noContent().build();
+    }
+
+    @Override
+    public Response deleteEntitlement(String name) {
+        entitlementDAO.deleteEntitlement(name);
+        
+        LOG.debug("Entitlement '" + name + "' deleted");
+        return Response.noContent().build();
+    }
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Entitlements.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Entitlements.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Entitlements.java
new file mode 100644
index 0000000..8f2e91a
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Entitlements.java
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.Collection;
+
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+
+@XmlRootElement(name = "entitlements", namespace = "http://org.apache.cxf.fediz/")
+public class Entitlements {
+
+    private Collection<Entitlement> entitlements;
+
+    public Entitlements() {
+    }
+
+    public Entitlements(Collection<Entitlement> entitlements) {
+        this.entitlements = entitlements;
+    }
+
+    @XmlElementRef
+    public Collection<Entitlement> getEntitlements() {
+        return entitlements;
+    }
+
+    public void setEntitlements(Collection<Entitlement> entitlements) {
+        this.entitlements = entitlements;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
new file mode 100644
index 0000000..b4692e8
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpService.java
@@ -0,0 +1,114 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.List;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+
+import org.springframework.security.access.prepost.PreAuthorize;
+
+@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
+@Path("idps")
+public interface IdpService {
+
+    @GET
+    @PreAuthorize("hasRole('IDP_LIST')")
+    Idps getIdps(@QueryParam("start") int start,
+                 @QueryParam("size") @DefaultValue("2") int size,
+                 @QueryParam("expand") @DefaultValue("all")  List<String> expand,
+                 @Context UriInfo uriInfo);
+
+    @GET
+    @Path("{realm}")
+    @PreAuthorize("hasRole('IDP_READ')")
+    Idp getIdp(@PathParam("realm") String realm,
+               @QueryParam("expand") @DefaultValue("all")  List<String> expand);
+
+    @POST
+    @PreAuthorize("hasRole('IDP_CREATE')")
+    Response addIdp(@Context UriInfo ui, Idp idp);
+    
+    @PUT
+    @Path("{realm}")
+    @PreAuthorize("hasRole('IDP_UPDATE')")
+    Response updateIdp(@Context UriInfo ui, @PathParam("realm") String realm, Idp idp);
+    
+    @DELETE
+    @Path("{realm}")
+    @PreAuthorize("hasRole('IDP_DELETE')")
+    Response deleteIdp(@PathParam("realm") String realm);
+    
+    @POST
+    @Path("{realm}/applications")
+    @PreAuthorize("hasRole('IDP_UPDATE')")
+    Response addApplicationToIdp(@Context UriInfo ui, @PathParam("realm") String realm,
+                                 Application application);
+    
+    @DELETE
+    @Path("{realm}/applications/{realmApplication}")
+    @PreAuthorize("hasRole('IDP_UPDATE')")
+    Response removeApplicationFromIdp(@Context UriInfo ui, @PathParam("realm") String realm,
+                                      @PathParam("realmApplication") String applicationRealm);
+    
+    @POST
+    @Path("{realm}/trusted-idps")
+    @PreAuthorize("hasRole('IDP_UPDATE')")
+    Response addTrustedIdpToIdp(@Context UriInfo ui, @PathParam("realm") String realm,
+                                TrustedIdp trustedIdp);
+    
+    @DELETE
+    @Path("{realm}/trusted-idps/{realmTrustedIdp}")
+    @PreAuthorize("hasRole('IDP_UPDATE')")
+    Response removeTrustedIdpFromIdp(@Context UriInfo ui, @PathParam("realm") String realm,
+                                     @PathParam("realmTrustedIdp") String trustedIdpRealm);
+    
+    @POST
+    @Path("{realm}/claims")
+    @PreAuthorize("hasRole('IDP_UPDATE')")
+    Response addClaimToIdp(@Context UriInfo ui, @PathParam("realm") String realm,
+                           Claim claim);
+    
+    @DELETE
+    @Path("{realm}/claims/{claimType}")
+    @PreAuthorize("hasRole('IDP_UPDATE')")
+    Response removeClaimFromIdp(@Context UriInfo ui, @PathParam("realm") String realm,
+                                @PathParam("claimType") String claimType);    
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
new file mode 100644
index 0000000..d4b5c40
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/IdpServiceImpl.java
@@ -0,0 +1,240 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.net.URI;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.ws.rs.BadRequestException;
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.core.UriBuilder;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.service.ApplicationDAO;
+import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
+import org.apache.cxf.fediz.service.idp.service.IdpDAO;
+import org.apache.cxf.fediz.service.idp.service.TrustedIdpDAO;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class IdpServiceImpl implements IdpService {
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(IdpServiceImpl.class);
+
+    @Autowired
+    private IdpDAO idpDAO;
+    
+    @Autowired
+    private ApplicationDAO applicationDAO;
+    
+    @Autowired
+    private TrustedIdpDAO trustedIdpDAO;
+    
+    @Autowired
+    private ClaimDAO claimDAO;
+           
+    @Override
+    public Idps getIdps(int start, int size, List<String> expand, UriInfo uriInfo) {
+        List<Idp> idps = idpDAO.getIdps(start, size, expand);
+        
+        Idps list = new Idps();
+        list.setIdps(idps);
+        return list;
+    }
+    
+    @Override
+    public Idp getIdp(String realm, List<String> expand) {
+        Idp idp = idpDAO.getIdp(realm, expand);
+        if (idp == null) {
+            LOG.warn("IdP not found for realm {}", realm);
+            throw new NotFoundException();
+        } else {
+            return idp;
+        }
+    }
+    
+    @Override
+    public Response addIdp(UriInfo ui, Idp idp) {
+        LOG.info("add IDP config");
+        if (idp.getApplications() != null && idp.getApplications().size() > 0) {
+            LOG.warn("IDP resource contains sub resource 'applications'");
+            throw new WebApplicationException(Status.BAD_REQUEST);
+        }
+        if (idp.getTrustedIdps() != null && idp.getTrustedIdps().size() > 0) {
+            LOG.warn("IDP resource contains sub resource 'trusted-idps'");
+            throw new WebApplicationException(Status.BAD_REQUEST);
+        }
+        Idp createdIdp = idpDAO.addIdp(idp);
+        
+        UriBuilder uriBuilder = UriBuilder.fromUri(ui.getRequestUri());
+        uriBuilder.path("{index}");
+        URI location = uriBuilder.build(createdIdp.getRealm());
+        return Response.created(location).entity(idp).build();
+    }
+    
+    @Override
+    public Response updateIdp(UriInfo ui, String realm, Idp idp) {
+        if (!realm.equals(idp.getRealm().toString())) {
+            throw new BadRequestException();
+        }
+        if (idp.getApplications() != null && idp.getApplications().size() > 0) {
+            LOG.warn("IDP resource contains sub resource 'applications'");
+            throw new WebApplicationException(Status.BAD_REQUEST);
+        }
+        if (idp.getTrustedIdps() != null && idp.getTrustedIdps().size() > 0) {
+            LOG.warn("IDP resource contains sub resource 'trusted-idps'");
+            throw new WebApplicationException(Status.BAD_REQUEST);
+        }
+        idpDAO.updateIdp(realm, idp);
+        
+        return Response.noContent().build();
+    }
+
+    @Override
+    public Response deleteIdp(String realm) {
+        idpDAO.deleteIdp(realm);
+        
+        return Response.noContent().build();
+    }
+
+    @Override
+    public Response addApplicationToIdp(UriInfo ui, String realm, Application application) {
+        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        for (Application idpApplication : idp.getApplications()) {
+            if (idpApplication.getRealm() != null && idpApplication.getRealm().equals(application.getRealm())) {
+                LOG.warn("Application '" + application.getRealm() + "' already added");
+                throw new WebApplicationException(Status.CONFLICT);
+            }
+        }
+        Application application2 = applicationDAO.getApplication(application.getRealm(), null);
+        idpDAO.addApplicationToIdp(idp, application2);
+        
+        return Response.noContent().build();
+    }
+    
+    @Override
+    public Response removeApplicationFromIdp(UriInfo ui, String realm,  String applicationRealm) {
+        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        
+        Application foundItem = null; 
+        for (Application item : idp.getApplications()) {
+            if (item.getRealm().equals(applicationRealm)) {
+                foundItem = item;
+                break;
+            }
+        }
+        if (foundItem == null) {
+            LOG.warn("Application '" + applicationRealm + "' not found");
+            throw new WebApplicationException(Status.NOT_FOUND);
+        }
+        idpDAO.removeApplicationFromIdp(idp, foundItem);
+        
+        return Response.noContent().build();
+    }
+    
+    
+    
+    
+    @Override
+    public Response addTrustedIdpToIdp(UriInfo ui, String realm, TrustedIdp trustedIdp) {
+        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        for (TrustedIdp idpTrustedIdp : idp.getTrustedIdps()) {
+            if (idpTrustedIdp.getRealm() != null && idpTrustedIdp.getRealm().equals(trustedIdp.getRealm())) {
+                LOG.warn("Trusted IDP '" + trustedIdp.getRealm() + "' already added");
+                throw new WebApplicationException(Status.CONFLICT);
+            }
+        }
+        TrustedIdp trustedIpd2 = trustedIdpDAO.getTrustedIDP(trustedIdp.getRealm());
+        
+        idpDAO.addTrustedIdpToIdp(idp, trustedIpd2);
+        
+        return Response.noContent().build();
+    }
+    
+    @Override
+    public Response removeTrustedIdpFromIdp(UriInfo ui, String realm, String trustedIdpRealm) {
+        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        
+        TrustedIdp foundItem = null; 
+        for (TrustedIdp item : idp.getTrustedIdps()) {
+            if (item.getRealm().equals(trustedIdpRealm)) {
+                foundItem = item;
+                break;
+            }
+        }
+        if (foundItem == null) {
+            LOG.warn("Trusted IDP '" + trustedIdpRealm + "' not found");
+            throw new WebApplicationException(Status.NOT_FOUND);
+        }
+        idpDAO.removeTrustedIdpFromIdp(idp, foundItem);
+        
+        return Response.noContent().build();
+    }   
+    
+    @Override
+    public Response addClaimToIdp(UriInfo ui, String realm, Claim claim) {
+        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        for (Claim idpClaim : idp.getClaimTypesOffered()) {
+            if (idpClaim.getClaimType() != null 
+                && idpClaim.getClaimType().toString().equals(claim.getClaimType().toString())) {
+                LOG.warn("Claim '" + claim.getClaimType() + "' already added");
+                throw new WebApplicationException(Status.CONFLICT);
+            }
+        }
+        Claim claim2 = claimDAO.getClaim(claim.getClaimType().toString());
+        idpDAO.addClaimToIdp(idp, claim2);
+        
+        return Response.noContent().build();
+    }
+    
+    @Override
+    public Response removeClaimFromIdp(UriInfo ui, String realm, String claimType) {
+        Idp idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        
+        Claim foundItem = null; 
+        for (Claim item : idp.getClaimTypesOffered()) {
+            if (item.getClaimType().toString().equals(claimType)) {
+                foundItem = item;
+                break;
+            }
+        }
+        if (foundItem == null) {
+            LOG.warn("Claim '" + claimType + "' not found");
+            throw new WebApplicationException(Status.NOT_FOUND);
+        }
+        idpDAO.removeClaimFromIdp(idp, foundItem);
+                
+        return Response.noContent().build();
+    }
+
+
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Idps.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Idps.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Idps.java
new file mode 100644
index 0000000..08d7f50
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/Idps.java
@@ -0,0 +1,49 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.Collection;
+
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+
+@XmlRootElement(name = "idps", namespace = "http://org.apache.cxf.fediz/")
+public class Idps {
+
+    private Collection<Idp> idps;
+
+    public Idps() {
+    }
+
+    public Idps(Collection<Idp> idps) {
+        this.idps = idps;
+    }
+
+    @XmlElementRef
+    public Collection<Idp> getIdps() {
+        return idps;
+    }
+
+    public void setIdps(Collection<Idp> idps) {
+        this.idps = idps;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
new file mode 100644
index 0000000..1e87bfc
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/QueryResourceInfoComparator.java
@@ -0,0 +1,114 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.cxf.jaxrs.ext.ResourceComparator;
+import org.apache.cxf.jaxrs.model.ClassResourceInfo;
+import org.apache.cxf.jaxrs.model.OperationResourceInfo;
+import org.apache.cxf.jaxrs.model.OperationResourceInfoComparator;
+import org.apache.cxf.jaxrs.model.Parameter;
+import org.apache.cxf.jaxrs.utils.JAXRSUtils;
+import org.apache.cxf.message.Message;
+
+public class QueryResourceInfoComparator extends OperationResourceInfoComparator implements ResourceComparator {
+
+    public QueryResourceInfoComparator() {
+        super(null, null);
+    }
+
+    @Override
+    public int compare(final ClassResourceInfo cri1, final ClassResourceInfo cri2, final Message message) {
+        // Leave Class selection to CXF
+        return 0;
+    }
+
+    @Override
+    public int compare(final OperationResourceInfo oper1, final OperationResourceInfo oper2, final Message message) {
+        // Check if CXF can make a decision
+        int cxfResult = super.compare(oper1, oper2);
+        if (cxfResult != 0) {
+            return cxfResult;
+        }
+
+        int op1Counter = getMatchingRate(oper1, message);
+        int op2Counter = getMatchingRate(oper2, message);
+
+        return op1Counter == op2Counter
+                ? 0
+                : op1Counter < op2Counter
+                ? 1
+                : -1;
+    }
+
+    /**
+     * This method calculates a number indicating a good or bad match between values provided within the request and
+     * expected method parameters. A higher number means a better match.
+     *
+     * @param operation The operation to be rated, based on contained parameterInfo values.
+     * @param message A message containing query and header values from user request
+     * @return A positive or negative number, indicating a good match between query and method
+     */
+    protected int getMatchingRate(final OperationResourceInfo operation, final Message message) {
+        List<Parameter> params = operation.getParameters();
+        if (params == null || params.isEmpty()) {
+            return 0;
+        }
+
+        // Get Request QueryParams
+        String query = (String) message.get(Message.QUERY_STRING);
+        String path = (String) message.get(Message.REQUEST_URI);
+        Map<String, List<String>> qParams = JAXRSUtils.getStructuredParams(query, "&", true, false);
+        Map<String, List<String>> mParams = JAXRSUtils.getMatrixParams(path, true);
+        // Get Request Headers
+        Map<?, ?> qHeader = (java.util.Map<?, ?>) message.get(Message.PROTOCOL_HEADERS);
+
+        int rate = 0;
+        for (Parameter p : params) {
+            switch (p.getType()) {
+            case QUERY:
+                if (qParams.containsKey(p.getName())) {
+                    rate += 2;
+                } else if (p.getDefaultValue() == null) {
+                    rate -= 1;
+                }
+                break;
+            case MATRIX:
+                if (mParams.containsKey(p.getName())) {
+                    rate += 2;
+                } else if (p.getDefaultValue() == null) {
+                    rate -= 1;
+                }
+                break;
+            case HEADER:
+                if (qHeader.containsKey(p.getName())) {
+                    rate += 2;
+                } else if (p.getDefaultValue() == null) {
+                    rate -= 1;
+                }
+                break;
+            default:
+                break;
+            }
+        }
+        return rate;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
new file mode 100644
index 0000000..c7a1e1e
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/rest/RestServiceExceptionMapper.java
@@ -0,0 +1,83 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.rest;
+
+import javax.validation.ConstraintViolationException;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.Response.Status;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.DataRetrievalFailureException;
+import org.springframework.dao.EmptyResultDataAccessException;
+import org.springframework.security.access.AccessDeniedException;
+
+@Provider
+public class RestServiceExceptionMapper implements ExceptionMapper<Exception> {
+
+    public static final String APPLICATION_ERROR_CODE = "X-Application-Error-Code";
+    
+    public static final String APPLICATION_ERROR_INFO = "X-Application-Error-Info";
+    
+    private static final String BASIC_REALM_UNAUTHORIZED = "Basic realm=\"Apache Fediz authentication\"";
+
+    private static final Logger LOG = LoggerFactory.getLogger(RestServiceExceptionMapper.class);
+
+    @Override
+    public Response toResponse(final Exception ex) {
+        LOG.warn("Exception occured processing REST request: " + ex.getMessage(), ex);
+
+        if (ex instanceof AccessDeniedException) {
+            return Response.status(Response.Status.UNAUTHORIZED).
+                    header(HttpHeaders.WWW_AUTHENTICATE, BASIC_REALM_UNAUTHORIZED).
+                    build();
+        }
+        if (ex instanceof ConstraintViolationException) {
+            ConstraintViolationException cve = (ConstraintViolationException)ex;
+            LOG.debug("{}\n{}", ex.getMessage(), cve.getConstraintViolations().toString());
+            return buildResponse(Response.Status.BAD_REQUEST, ex);
+        }
+        if (ex instanceof DataIntegrityViolationException) {
+            return buildResponse(Response.Status.CONFLICT, ex);
+        }
+        
+        if (ex instanceof EmptyResultDataAccessException) {
+            return buildResponse(Response.Status.NOT_FOUND, ex);
+        }
+        
+        if (ex instanceof DataRetrievalFailureException) {
+            return buildResponse(Response.Status.NOT_FOUND, ex);
+        }
+
+        // Rest is interpreted as InternalServerError
+        return buildResponse(Response.Status.INTERNAL_SERVER_ERROR, ex);
+    }
+
+    Response buildResponse(final Status status, final Exception ex) {
+        ResponseBuilder responseBuilder = Response.status(status);
+        return responseBuilder.header(APPLICATION_ERROR_CODE, ex.getClass().getName())
+                              .header(APPLICATION_ERROR_INFO, ex.getMessage())
+                              .status(status).build();
+    }
+
+}


[09/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPATest.java b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPATest.java
new file mode 100644
index 0000000..1d63fde
--- /dev/null
+++ b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/EntitlementDAOJPATest.java
@@ -0,0 +1,115 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.domain.Entitlement;
+import org.apache.cxf.fediz.service.idp.service.EntitlementDAO;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.EmptyResultDataAccessException;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.util.Assert;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = { "classpath:testContext.xml" })
+public class EntitlementDAOJPATest {
+
+    @Autowired
+    private EntitlementDAO entitlementDAO;
+    
+    
+    @BeforeClass
+    public static void init() {
+        System.setProperty("spring.profiles.active", "jpa");
+    }
+    
+    
+    @Test
+    public void testReadAllEntitlements() {
+        List<Entitlement> entitlements = entitlementDAO.getEntitlements(0, 999);
+        Assert.isTrue(30 == entitlements.size(), "Size doesn't match");
+    }
+    
+    @Test
+    public void testReadExistingEntitlement() {
+        Entitlement entitlement = entitlementDAO.getEntitlement("CLAIM_LIST");
+        Assert.isTrue("CLAIM_LIST".equals(entitlement.getName()),
+                      "Entitlement name doesn't match");
+        Assert.isTrue("Description for CLAIM_LIST".equals(entitlement.getDescription()),
+                      "Entitlement Description doesn't match");
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryReadNonexistingEntitlement() {
+        entitlementDAO.getEntitlement("CLAIM_NOT_EXIST");
+    }
+    
+    
+    @Test
+    public void testAddNewEntitlement() {
+        Entitlement entitlement5 = new Entitlement();
+        entitlement5.setName("GUGUS_CREATE");
+        entitlement5.setDescription("Any entitlement");
+        entitlementDAO.addEntitlement(entitlement5);
+        
+        List<Entitlement> entitlements = entitlementDAO.getEntitlements(0, 999);
+        Assert.isTrue(31 == entitlements.size(), "Size doesn't match. Entitlement not added");
+    }
+    
+    
+    @Test(expected = DataIntegrityViolationException.class)
+    public void testTryAddExistingEntitlement() {
+        Entitlement entitlement5 = new Entitlement();
+        entitlement5.setName("CLAIM_DELETE");
+        entitlement5.setDescription("Description for CLAIM_DELETE");
+        entitlementDAO.addEntitlement(entitlement5);
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryRemoveUnknownEntitlement() {
+        entitlementDAO.deleteEntitlement("GUGUS_NOT_EXIST");
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testRemoveExistingEntitlement() {
+        
+        Entitlement entitlement5 = new Entitlement();
+        entitlement5.setName("CLAIM_TO_DELETE");
+        entitlement5.setDescription("Description for CLAIM_TO_DELETE");
+        entitlementDAO.addEntitlement(entitlement5);
+        
+        entitlementDAO.deleteEntitlement("CLAIM_TO_DELETE");
+        
+        entitlementDAO.getEntitlement("CLAIM_TO_DELETE");
+    }
+    
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPATest.java b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPATest.java
new file mode 100644
index 0000000..6256371
--- /dev/null
+++ b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/IdpDAOJPATest.java
@@ -0,0 +1,653 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.service.IdpDAO;
+import org.apache.wss4j.dom.WSConstants;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.EmptyResultDataAccessException;
+import org.springframework.orm.jpa.JpaObjectRetrievalFailureException;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.util.Assert;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = { "classpath:testContext.xml" })
+public class IdpDAOJPATest {
+
+    @Autowired
+    private IdpDAO idpDAO;
+    
+    
+    @BeforeClass
+    public static void init() {
+        System.setProperty("spring.profiles.active", "jpa");
+    }
+    
+    
+    @Test
+    public void testReadAllIdps() {
+        List<Idp> idps = idpDAO.getIdps(0, 999, null);
+        // Idp could have been removed, Order not given as per JUnit design
+        Assert.isTrue(0 < idps.size(), "Size doesn't match [" + idps.size() + "]");
+    }
+    
+    
+    @Test
+    public void testReadExistingIdpEmbeddedAll() throws MalformedURLException {
+        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A", Arrays.asList("all"));
+        
+        Assert.isTrue("stsKeystoreA.properties".equals(idp.getCertificate()),
+                      "Certificate doesn't match");
+        Assert.isTrue("realma".equals(idp.getCertificatePassword()),
+                      "Certificate password doesn't match");
+        Assert.isTrue("urn:org:apache:cxf:fediz:idp:realm-A".equals(idp.getRealm()),
+                      "Realm doesn't match");
+        Assert.isTrue("IDP of Realm A".equals(idp.getServiceDescription()),
+                      "ServiceDescription doesn't match");
+        Assert.isTrue("REALM A".equals(idp.getServiceDisplayName()),
+                      "ServiceDisplayName doesn't match");        
+        Assert.isTrue(new URL("https://localhost:9443/fediz-idp/federation").equals(idp.getIdpUrl()),
+                      "IdpUrl doesn't match");
+        Assert.isTrue(new URL("https://localhost:9443/fediz-idp-sts/REALMA").equals(idp.getStsUrl()),
+                      "StsUrl doesn't match");
+        Assert.isTrue("realma".equals(idp.getUri()),
+                      "Uri doesn't match");
+        Assert.isTrue(idp.isProvideIdpList(),
+                      "ProvideIDPList doesn't match");
+        Assert.isTrue(idp.isUseCurrentIdp(),
+                      "UseCurrentIDP doesn't match");
+        Assert.isTrue(4 == idp.getAuthenticationURIs().size(),
+                      "Number of AuthenticationURIs doesn't match");
+        Assert.isTrue(2 == idp.getSupportedProtocols().size(),
+                      "Number of SupportedProtocols doesn't match");
+        Assert.isTrue(2 == idp.getTokenTypesOffered().size(),
+                      "Number of TokenTypesOffered doesn't match");
+        Assert.isTrue(2 == idp.getApplications().size(),
+                      "Number of applications doesn't match");
+        Assert.isTrue(1 == idp.getTrustedIdps().size(),
+                      "Number of trusted IDPs doesn't match");
+        Assert.isTrue(4 == idp.getClaimTypesOffered().size(),
+                      "Number of claims doesn't match");
+    }
+    
+    @Test
+    public void testReadExistingIdpEmbeddedTrustedIdps() {
+        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A",
+                                                                Arrays.asList("trusted-idps"));
+        
+        Assert.isTrue(1 == idp.getTrustedIdps().size(),
+                      "Number of trusted IDPs doesn't match");
+    }
+    
+    @Test
+    public void testReadExistingIdpEmbeddedClaims() {
+        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A",
+                                                                Arrays.asList("claims"));
+        
+        Assert.isTrue(4 == idp.getClaimTypesOffered().size(),
+                      "Number of claims doesn't match");
+    }
+    
+    @Test
+    public void testReadExistingIdpEmbeddedApplications() {
+        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A", Arrays.asList("applications"));
+        
+        Assert.isTrue(2 == idp.getApplications().size(), "Number of applications doesn't match");
+    }
+    
+    @Test
+    public void testReadExistingIdpEmbeddedNull() {
+        Idp idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:realm-A",
+                                                                null);
+        
+        Assert.isTrue(0 == idp.getClaimTypesOffered().size(),
+                      "Number of claims doesn't match");
+        Assert.isTrue(0 == idp.getApplications().size(),
+                      "Number of applications doesn't match");
+        Assert.isTrue(0 == idp.getTrustedIdps().size(),
+                      "Number of trusted IDPs doesn't match");
+       
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryReadNonexistingIdp() {
+        idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:NOTEXIST", null);
+    }
+    
+    
+    @Test
+    public void testAddNewIdp() throws MalformedURLException {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:testadd");
+        idp.setCertificate("stsKeystoreA.properties");
+        idp.setCertificatePassword("realma");
+        idp.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federation"));
+        idp.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMN"));
+        idp.setServiceDisplayName("NEW REALM");
+        idp.setServiceDescription("IDP of New Realm");
+        idp.setUri("realmn");
+        idp.setProvideIdpList(true);
+        Map<String, String> authUris = new HashMap<>();
+        authUris.put("default", "/login/default");
+        idp.setAuthenticationURIs(authUris);
+        List<String> protocols = new ArrayList<>();
+        protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
+        protocols.add("http://docs.oasis-open.org/ws-sx/ws-trust/200512");
+        idp.setSupportedProtocols(protocols);
+        List<String> tokenTypes = new ArrayList<>();
+        tokenTypes.add(WSConstants.SAML2_NS);
+        tokenTypes.add(WSConstants.SAML_NS);
+        idp.setTokenTypesOffered(tokenTypes);
+        idp.setUseCurrentIdp(true);
+        
+        idpDAO.addIdp(idp);
+        
+        idp = idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:testadd", null);
+        
+        Assert.isTrue("stsKeystoreA.properties".equals(idp.getCertificate()),
+                      "Certificate doesn't match");
+        Assert.isTrue("realma".equals(idp.getCertificatePassword()),
+                      "Certificate password doesn't match");
+        Assert.isTrue("urn:org:apache:cxf:fediz:idp:testadd".equals(idp.getRealm()),
+                      "Realm doesn't match");
+        Assert.isTrue("IDP of New Realm".equals(idp.getServiceDescription()),
+                      "ServiceDescription doesn't match");
+        Assert.isTrue("NEW REALM".equals(idp.getServiceDisplayName()),
+                      "ServiceDisplayName doesn't match");        
+        Assert.isTrue(new URL("https://localhost:9443/fediz-idp/federation").equals(idp.getIdpUrl()),
+                      "IdpUrl doesn't match");
+        Assert.isTrue(new URL("https://localhost:9443/fediz-idp-sts/REALMN").equals(idp.getStsUrl()),
+                      "StsUrl doesn't match");
+        Assert.isTrue("realmn".equals(idp.getUri()),
+                      "Uri doesn't match");
+        Assert.isTrue(idp.isProvideIdpList(),
+                      "ProvideIDPList doesn't match");
+        Assert.isTrue(idp.isUseCurrentIdp(),
+                      "UseCurrentIDP doesn't match");
+        Assert.isTrue(1 == idp.getAuthenticationURIs().size(),
+                      "Number of AuthenticationURIs doesn't match");
+        Assert.isTrue(2 == idp.getSupportedProtocols().size(),
+                      "Number of SupportedProtocols doesn't match");
+        Assert.isTrue(2 == idp.getTokenTypesOffered().size(),
+                      "Number of TokenTypesOffered doesn't match");
+        Assert.isTrue(0 == idp.getApplications().size(),
+                      "Number of applications doesn't match");
+        Assert.isTrue(0 == idp.getTrustedIdps().size(),
+                      "Number of trusted IDPs doesn't match");
+        Assert.isTrue(0 == idp.getClaimTypesOffered().size(),
+                      "Number of claims doesn't match");
+
+    }
+    
+    
+    @Test(expected = DataIntegrityViolationException.class)
+    public void testTryAddExistingIdp() throws MalformedURLException {
+        Idp idp = createIdp("urn:org:apache:cxf:fediz:idp:realm-A");
+        idpDAO.addIdp(idp);
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryRemoveUnknownIdp() {
+        idpDAO.deleteIdp("urn:org:apache:cxf:fediz:idp:NOTEXIST");
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testRemoveExistingIdp() throws MalformedURLException {
+        Idp idp = createIdp("urn:org:apache:cxf:fediz:idp:testdelete");
+        
+        idpDAO.addIdp(idp);
+        
+        idpDAO.deleteIdp("urn:org:apache:cxf:fediz:idp:testdelete");
+        
+        idpDAO.getIdp("urn:org:apache:cxf:fediz:idp:testdelete", null);
+    }
+    
+    @Test
+    public void testUpdateIdp() throws MalformedURLException {
+        String realm = "urn:org:apache:cxf:fediz:idp:testupdate";
+        //Prepare
+        Idp idp = createIdp(realm);
+        idpDAO.addIdp(idp);
+        
+        //Testcase
+        idp = new Idp();
+        idp.setRealm(realm);
+        idp.setCertificate("UstsKeystoreA.properties");
+        idp.setCertificatePassword("Urealma");
+        idp.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federationUU"));
+        idp.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMAUU"));
+        idp.setServiceDisplayName("UNEW REALM");
+        idp.setServiceDescription("UIDP of New Realm");
+        idp.setUri("Urealmn");
+        idp.setProvideIdpList(true);
+        Map<String, String> authUris = new HashMap<>();
+        authUris.put("default", "/login/default");
+        idp.setAuthenticationURIs(authUris);
+        List<String> protocols = new ArrayList<>();
+        protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
+        idp.setSupportedProtocols(protocols);
+        List<String> tokenTypes = new ArrayList<>();
+        tokenTypes.add(WSConstants.SAML2_NS);
+        idp.setTokenTypesOffered(tokenTypes);
+        idp.setUseCurrentIdp(false);
+        idpDAO.updateIdp(realm, idp);
+        
+        idp = idpDAO.getIdp(realm, null);
+        
+        Assert.isTrue("UstsKeystoreA.properties".equals(idp.getCertificate()),
+                      "Certificate doesn't match");
+        Assert.isTrue("Urealma".equals(idp.getCertificatePassword()),
+                      "Certificate password doesn't match");
+        Assert.isTrue(realm.equals(idp.getRealm()),
+                      "Realm doesn't match");
+        Assert.isTrue("UIDP of New Realm".equals(idp.getServiceDescription()),
+                      "ServiceDescription doesn't match");
+        Assert.isTrue("UNEW REALM".equals(idp.getServiceDisplayName()),
+                      "ServiceDisplayName doesn't match");        
+        Assert.isTrue(new URL("https://localhost:9443/fediz-idp/federationUU").equals(idp.getIdpUrl()),
+                      "IdpUrl doesn't match");
+        Assert.isTrue(new URL("https://localhost:9443/fediz-idp-sts/REALMAUU").equals(idp.getStsUrl()),
+                      "StsUrl doesn't match");
+        Assert.isTrue("Urealmn".equals(idp.getUri()),
+                      "Uri doesn't match");
+        Assert.isTrue(idp.isProvideIdpList(),
+                      "ProvideIDPList doesn't match");
+        Assert.isTrue(!idp.isUseCurrentIdp(),
+                      "UseCurrentIDP doesn't match");
+        Assert.isTrue(1 == idp.getAuthenticationURIs().size(),
+                      "Number of AuthenticationURIs doesn't match");
+        Assert.isTrue(1 == idp.getSupportedProtocols().size(),
+                      "Number of SupportedProtocols doesn't match");
+        Assert.isTrue(1 == idp.getTokenTypesOffered().size(),
+                      "Number of TokenTypesOffered doesn't match");
+        Assert.isTrue(0 == idp.getApplications().size(),
+                      "Number of applications doesn't match");
+        Assert.isTrue(0 == idp.getTrustedIdps().size(),
+                      "Number of trusted IDPs doesn't match");
+        Assert.isTrue(0 == idp.getClaimTypesOffered().size(),
+                      "Number of claims doesn't match");
+        
+    }
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testUpdateUnknownIdp() throws MalformedURLException {
+        String realm = "urn:org:apache:cxf:fediz:idp:testupdate2";
+        
+        //Prepare
+        Idp idp = createIdp(realm);
+        idpDAO.addIdp(idp);
+        
+        //Testcase
+        idp = new Idp();
+        idp.setRealm(realm);
+        idp.setCertificate("UstsKeystoreA.properties");
+        idp.setCertificatePassword("Urealma");
+        idp.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federationUU"));
+        idp.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMNUU"));
+        idp.setServiceDisplayName("UNEW REALM");
+        idp.setServiceDescription("UIDP of New Realm");
+        idp.setUri("Urealmn");
+        idp.setProvideIdpList(true);
+        Map<String, String> authUris = new HashMap<>();
+        authUris.put("default", "/login/default");
+        idp.setAuthenticationURIs(authUris);
+        List<String> protocols = new ArrayList<>();
+        protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
+        idp.setSupportedProtocols(protocols);
+        List<String> tokenTypes = new ArrayList<>();
+        tokenTypes.add(WSConstants.SAML2_NS);
+        idp.setTokenTypesOffered(tokenTypes);
+        idp.setUseCurrentIdp(false);
+        idpDAO.updateIdp("urn:UNKNOWN", idp);
+    }
+    
+    @Test
+    public void testAddClaimToIdp() throws MalformedURLException {
+        String realm = "urn:org:apache:cxf:fediz:idp:testaddclaim";
+        
+        //Prepare
+        Idp idp = createIdp(realm);
+        idpDAO.addIdp(idp);
+        
+        //Testcase
+        Claim claim = new Claim();
+        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
+        
+        idpDAO.addClaimToIdp(idp, claim);
+               
+        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        
+        Assert.isTrue(1 == idp.getClaimTypesOffered().size(), "claimTypesOffered size doesn't match");
+    }
+    
+    @Test(expected = DataIntegrityViolationException.class)
+    public void testTryAddExistingClaimToIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+        
+        Claim claim = new Claim();
+        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
+        
+        idpDAO.addClaimToIdp(idp, claim);
+    }
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryAddUnknownClaimToIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+        
+        Claim claim = new Claim();
+        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/UNKOWN"));
+        
+        idpDAO.addClaimToIdp(idp, claim);
+        
+    }
+    
+    @Test
+    public void testRemoveClaimFromIdp() throws MalformedURLException {
+        String realm = "urn:org:apache:cxf:fediz:fedizhelloworld:testremoveclaim";
+        //Prepare step
+        Idp idp = createIdp(realm);
+        idpDAO.addIdp(idp);
+        
+        Claim claim = new Claim();
+        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
+        idpDAO.addClaimToIdp(idp, claim);
+               
+        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        Assert.isTrue(1 == idp.getClaimTypesOffered().size(),
+                      "claimTypesOffered size doesn't match [" + idp.getClaimTypesOffered().size() + "]");
+        
+        //Testcase
+        idpDAO.removeClaimFromIdp(idp, claim);
+        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        Assert.isTrue(0 == idp.getClaimTypesOffered().size(),
+                      "claimTypesOffered size doesn't match [" + idp.getClaimTypesOffered().size() + "]");
+    }
+    
+    @Test(expected = JpaObjectRetrievalFailureException.class)
+    public void testTryRemoveNotAssignedClaimFromIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+                
+        Claim claim = new Claim();
+        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/city"));
+        
+        idpDAO.removeClaimFromIdp(idp, claim);
+    }
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryRemoveUnknownClaimFromIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+                
+        Claim claim = new Claim();
+        claim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/UNKNOWN"));
+        
+        idpDAO.removeClaimFromIdp(idp, claim);
+    }
+    
+    @Test
+    public void testAddApplicationToIdp() throws MalformedURLException {
+        String realm = "urn:org:apache:cxf:fediz:app:testaddApplication";
+        
+        //Prepare
+        Idp idp = createIdp(realm);
+        idpDAO.addIdp(idp);
+        
+        //Testcase
+        //Application app = createApplication(realm);
+        Application app = new Application();
+        app.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
+        idpDAO.addApplicationToIdp(idp, app);
+               
+        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        
+        Assert.isTrue(1 == idp.getApplications().size(), "applications size doesn't match");
+    }
+    
+    
+    @Test(expected = DataIntegrityViolationException.class)
+    public void testTryAddExistingApplicationToIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+        
+        Application app = new Application();
+        app.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
+        
+        idpDAO.addApplicationToIdp(idp, app);
+    }
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryAddUnknownApplicationToIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+        
+        Application app = new Application();
+        app.setRealm("urn:org:apache:cxf:fediz:UNKNOWN");
+        
+        idpDAO.addApplicationToIdp(idp, app);
+        
+    }
+    
+    @Test
+    public void testRemoveApplicationFromIdp() throws MalformedURLException {
+        String realm = "urn:org:apache:cxf:fediz:fedizhelloworld:testremoveapp";
+        //Prepare step
+        Idp idp = createIdp(realm);
+        idpDAO.addIdp(idp);
+        
+        Application app = new Application();
+        app.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
+        idpDAO.addApplicationToIdp(idp, app);
+               
+        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        Assert.isTrue(1 == idp.getApplications().size(),
+                      "applications size doesn't match [" + idp.getApplications().size() + "]");
+        
+        //Testcase
+        idpDAO.removeApplicationFromIdp(idp, app);
+        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        Assert.isTrue(0 == idp.getApplications().size(),
+                      "applications size doesn't match [" + idp.getApplications().size() + "]");
+    }
+    
+    
+    @Test(expected = JpaObjectRetrievalFailureException.class)
+    public void testTryRemoveNotAssignedApplicationFromIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+                
+        Application app = new Application();
+        app.setRealm("myrealm2");
+        
+        idpDAO.removeApplicationFromIdp(idp, app);
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryRemoveUnknownApplicationFromIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+                
+        Application app = new Application();
+        app.setRealm("urn:org:apache:cxf:fediz:UNKNOWN");
+        
+        idpDAO.removeApplicationFromIdp(idp, app);
+    }
+    
+    
+    
+    
+    
+    
+    @Test
+    public void testAddTrustedIdpToIdp() throws MalformedURLException {
+        String realm = "urn:org:apache:cxf:fediz:trusted-idp:testaddTrustedIdp";
+        
+        //Prepare
+        Idp idp = createIdp(realm);
+        idpDAO.addIdp(idp);
+        
+        //Testcase
+        //Application app = createApplication(realm);
+        TrustedIdp trustedIdp = new TrustedIdp();
+        trustedIdp.setRealm("urn:org:apache:cxf:fediz:idp:realm-B");
+        idpDAO.addTrustedIdpToIdp(idp, trustedIdp);
+               
+        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        
+        Assert.isTrue(1 == idp.getTrustedIdps().size(), "applications size doesn't match");
+    }
+    
+    /*
+    @Test(expected = DataIntegrityViolationException.class)
+    public void testTryAddExistingTrustedIdpToIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+        
+        TrustedIdp trustedIdp = new TrustedIdp();
+        trustedIdp.setRealm("urn:org:apache:cxf:fediz:idp:realm-B");
+        
+        idpDAO.addTrustedIdpToIdp(idp, trustedIdp);
+    }
+    
+    @Test(expected = NoResultException.class)
+    public void testTryAddUnknownTrustedIdpToIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+        
+        TrustedIdp trustedIdp = new TrustedIdp();
+        trustedIdp.setRealm("urn:org:apache:cxf:fediz:UNKNOWN");
+        
+        idpDAO.addTrustedIdpToIdp(idp, trustedIdp);
+    }
+    
+    @Test
+    public void testRemoveTrustedIdpFromIdp() {
+        String realm = "urn:org:apache:cxf:fediz:trustedidp:testremove";
+        //Prepare step
+        Idp idp = createIdp(realm);
+        idpDAO.addIdp(idp);
+        
+        TrustedIdp trustedIdp = new TrustedIdp();
+        trustedIdp.setRealm("urn:org:apache:cxf:fediz:idp:realm-B");
+        idpDAO.addTrustedIdpToIdp(idp, trustedIdp);
+               
+        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        Assert.isTrue(1 == idp.getTrustedIdps().size(),
+                      "trustedIdps size doesn't match [" + idp.getTrustedIdps().size() + "]");
+        
+        //Testcase
+        idpDAO.removeTrustedIdpFromIdp(idp, trustedIdp);
+        idp = idpDAO.getIdp(realm, Arrays.asList("all"));
+        Assert.isTrue(0 == idp.getTrustedIdps().size(),
+                      "trustedIdps size doesn't match [" + idp.getTrustedIdps().size() + "]");
+    }
+    
+    
+    @Test(expected = EntityNotFoundException.class)
+    public void testTryRemoveNotAssignedTrustedIdpFromIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+                
+        TrustedIdp trustedIdp = new TrustedIdp();
+        trustedIdp.setRealm("trustedidp2realm");
+        
+        idpDAO.removeTrustedIdpFromIdp(idp, trustedIdp);
+    }
+    
+    
+    @Test(expected = NoResultException.class)
+    public void testTryRemoveUnknownTrustedIdpFromIdp() {
+        Idp idp = new Idp();
+        idp.setRealm("urn:org:apache:cxf:fediz:idp:realm-A");
+                
+        TrustedIdp trustedIdp = new TrustedIdp();
+        trustedIdp.setRealm("urn:org:apache:cxf:fediz:UNKNOWN");
+        
+        idpDAO.removeTrustedIdpFromIdp(idp, trustedIdp);
+    }
+    */
+    
+    
+    private static Idp createIdp(String realm) throws MalformedURLException {
+        Idp idp = new Idp();
+        idp.setRealm(realm);
+        idp.setCertificate("stsKeystoreA.properties");
+        idp.setCertificatePassword("realma");
+        idp.setIdpUrl(new URL("https://localhost:9443/fediz-idp/federation"));
+        idp.setStsUrl(new URL("https://localhost:9443/fediz-idp-sts/REALMA"));
+        idp.setServiceDisplayName("NEW REALM");
+        idp.setServiceDescription("IDP of New Realm");
+        idp.setUri("realma");
+        idp.setProvideIdpList(true);
+        Map<String, String> authUris = new HashMap<>();
+        authUris.put("default", "/login/default");
+        idp.setAuthenticationURIs(authUris);
+        List<String> protocols = new ArrayList<>();
+        protocols.add("http://docs.oasis-open.org/wsfed/federation/200706");
+        protocols.add("http://docs.oasis-open.org/ws-sx/ws-trust/200512");
+        idp.setSupportedProtocols(protocols);
+        List<String> tokenTypes = new ArrayList<>();
+        tokenTypes.add(WSConstants.SAML2_NS);
+        tokenTypes.add(WSConstants.SAML_NS);
+        idp.setTokenTypesOffered(tokenTypes);
+        idp.setUseCurrentIdp(true);
+        return idp;
+    }
+    /*
+    private static Application createApplication(String realm) {
+        Application application = new Application();
+        application.setRealm(realm);
+        application.setEncryptionCertificate("");
+        application.setLifeTime("3600");
+        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+        application.setRole("ApplicationServiceType");
+        application.setServiceDescription("Fedizhelloworld description");
+        application.setServiceDisplayName("Fedizhelloworld");
+        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
+        return application;
+    }
+    */
+    
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TestDBLoader.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TestDBLoader.java b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TestDBLoader.java
new file mode 100644
index 0000000..222277a
--- /dev/null
+++ b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TestDBLoader.java
@@ -0,0 +1,93 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import javax.persistence.EntityManager;
+import javax.persistence.PersistenceContext;
+
+import org.apache.cxf.fediz.service.idp.domain.FederationType;
+import org.apache.cxf.fediz.service.idp.domain.TrustType;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.transaction.annotation.Transactional;
+
+@Transactional
+public class TestDBLoader implements DBLoader {
+    
+    public static final String NAME = "UNITTESTDBLOADER";
+    
+    private static final Logger LOG = LoggerFactory.getLogger(TestDBLoader.class);
+    
+    private EntityManager em;
+
+    @PersistenceContext
+    public void setEntityManager(EntityManager entityManager) {
+        this.em = entityManager;
+    }
+    
+    @Override
+    public String getName() {
+        return NAME;
+    }
+    
+    public void load() {
+        
+        try {
+            ClaimEntity claimEntity5 = new ClaimEntity();
+            claimEntity5.setClaimType("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/city");
+            claimEntity5.setDisplayName("city");
+            claimEntity5.setDescription("Description for city");
+            em.persist(claimEntity5);
+                        
+            ApplicationEntity entity2 = new ApplicationEntity();
+            entity2.setEncryptionCertificate("my encryption cert2");
+            entity2.setLifeTime(1800);
+            entity2.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+            entity2.setRealm("myrealm2");
+            entity2.setRole("myrole");
+            entity2.setServiceDescription("service description2");
+            entity2.setServiceDisplayName("service displayname2");
+            entity2.setTokenType("my tokentype");
+            // must be persistet here already as the ApplicationClaimEntity requires the Application Id
+            em.persist(entity2);
+            ApplicationClaimEntity ace5 = new ApplicationClaimEntity(entity2, claimEntity5);
+            ace5.setOptional(false);
+            em.persist(ace5);
+            entity2.getRequestedClaims().add(ace5);
+            em.persist(entity2);
+            
+            TrustedIdpEntity entity4 = new TrustedIdpEntity();
+            entity4.setCacheTokens(true);
+            entity4.setCertificate("trusted cert");
+            entity4.setDescription("Realm B description");
+            entity4.setFederationType(FederationType.FEDERATE_IDENTITY);
+            entity4.setName("Realm B");
+            entity4.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+            entity4.setRealm("trustedidp2realm");
+            entity4.setTrustType(TrustType.PEER_TRUST);
+            entity4.setUrl("https://localhost:${realmB.port}/fediz-idp-remote/federation");
+            em.persist(entity4);
+            
+            em.flush();
+            
+        } catch (Exception ex) {
+            LOG.warn("Failed to initialize DB with data", ex);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPATest.java b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPATest.java
new file mode 100644
index 0000000..2ebe5ba
--- /dev/null
+++ b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/TrustedIdpDAOJPATest.java
@@ -0,0 +1,202 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.domain.FederationType;
+import org.apache.cxf.fediz.service.idp.domain.TrustType;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.service.TrustedIdpDAO;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.EmptyResultDataAccessException;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.util.Assert;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = { "classpath:testContext.xml" })
+public class TrustedIdpDAOJPATest {
+
+    @Autowired
+    private TrustedIdpDAO trustedIdpDAO;
+        
+    
+    @BeforeClass
+    public static void init() {
+        System.setProperty("spring.profiles.active", "jpa");
+    }
+    
+    
+    @Test
+    public void testReadAllTrustedIdps() {
+        List<TrustedIdp> trustedIdps = trustedIdpDAO.getTrustedIDPs(0, 999);
+        Assert.isTrue(2 <= trustedIdps.size(), "Size doesn't match");
+    }
+    
+    @Test
+    public void testReadExistingTrustedIdp() {
+        TrustedIdp trustedIdp = trustedIdpDAO.getTrustedIDP("urn:org:apache:cxf:fediz:idp:realm-B");
+        Assert.isTrue("realmb.cert".equals(trustedIdp.getCertificate()),
+                      "Certificate name doesn't match");
+        Assert.isTrue("Realm B description".equals(trustedIdp.getDescription()),
+                      "Description name doesn't match");
+        Assert.isTrue(FederationType.FEDERATE_IDENTITY.equals(trustedIdp.getFederationType()),
+                      "FederationType doesn't match");        
+        Assert.isTrue("Realm B".equals(trustedIdp.getName()),
+                      "Name doesn't match");      
+        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(trustedIdp.getProtocol()),
+                      "Protocol doesn't match");          
+        Assert.isTrue("urn:org:apache:cxf:fediz:idp:realm-B".equals(trustedIdp.getRealm()),
+                      "Realm doesn't match");          
+        Assert.isTrue(TrustType.PEER_TRUST.equals(trustedIdp.getTrustType()),
+                      "TrustType doesn't match");
+        Assert.isTrue("https://localhost:12443/fediz-idp-remote/federation".equals(trustedIdp.getUrl()),
+                      "Url doesn't match"); 
+        Assert.isTrue(trustedIdp.isCacheTokens(), "CacheTokens doesn't match"); 
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryReadNonexistingTrustedIdp() {
+        trustedIdpDAO.getTrustedIDP("urn:org:apache:cxf:fediz:idp:NOTEXIST");
+    }
+    
+    
+    @Test
+    public void testAddNewTrustedIdp() {
+        String realm = "urn:org:apache:cxf:fediz:trusted-idp:testadd";
+        TrustedIdp trustedIdp = createTrustedIdp(realm);
+        trustedIdpDAO.addTrustedIDP(trustedIdp);
+        
+        trustedIdp = trustedIdpDAO.getTrustedIDP(realm);
+        
+        Assert.isTrue("realmb.cert".equals(trustedIdp.getCertificate()),
+                      "Certificate name doesn't match");
+        Assert.isTrue("Realm B description".equals(trustedIdp.getDescription()),
+                      "Description name doesn't match");
+        Assert.isTrue(FederationType.FEDERATE_IDENTITY.equals(trustedIdp.getFederationType()),
+                      "FederationType doesn't match");        
+        Assert.isTrue("Realm B".equals(trustedIdp.getName()),
+                      "Name doesn't match");      
+        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(trustedIdp.getProtocol()),
+                      "Protocol doesn't match");          
+        Assert.isTrue(realm.equals(trustedIdp.getRealm()),
+                      "Realm doesn't match");          
+        Assert.isTrue(TrustType.PEER_TRUST.equals(trustedIdp.getTrustType()),
+                      "TrustType doesn't match");
+        Assert.isTrue("https://localhost:12443/fediz-idp-remote/federation".equals(trustedIdp.getUrl()),
+                      "Url doesn't match"); 
+        Assert.isTrue(!trustedIdp.isCacheTokens(), "CacheTokens doesn't match"); 
+    }
+    
+    
+    @Test
+    public void testUpdateTrustedIdp() {
+        String realm = "urn:org:apache:cxf:fediz:trusted-idp:testupdate";
+        //Prepare
+        TrustedIdp trustedIdp = createTrustedIdp(realm);
+        trustedIdpDAO.addTrustedIDP(trustedIdp);
+        
+        //Testcase
+        trustedIdp = new TrustedIdp();
+        trustedIdp.setRealm(realm);
+        trustedIdp.setCacheTokens(true);
+        trustedIdp.setCertificate("Utrusted cert");
+        trustedIdp.setDescription("URealm B description");
+        trustedIdp.setFederationType(FederationType.FEDERATE_CLAIMS);
+        trustedIdp.setName("URealm B");
+        trustedIdp.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+        trustedIdp.setTrustType(TrustType.INDIRECT_TRUST);
+        trustedIdp.setUrl("Uhttps://localhost:12443/fediz-idp-remote/federation");
+        
+        trustedIdpDAO.updateTrustedIDP(realm, trustedIdp);
+        
+        trustedIdp = trustedIdpDAO.getTrustedIDP(realm);
+        
+        Assert.isTrue("Utrusted cert".equals(trustedIdp.getCertificate()),
+                      "Certificate name doesn't match");
+        Assert.isTrue("URealm B description".equals(trustedIdp.getDescription()),
+                      "Description name doesn't match");
+        Assert.isTrue(FederationType.FEDERATE_CLAIMS.equals(trustedIdp.getFederationType()),
+                      "FederationType doesn't match");        
+        Assert.isTrue("URealm B".equals(trustedIdp.getName()),
+                      "Name doesn't match");      
+        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(trustedIdp.getProtocol()),
+                      "Protocol doesn't match");          
+        Assert.isTrue(realm.equals(trustedIdp.getRealm()),
+                      "Realm doesn't match");          
+        Assert.isTrue(TrustType.INDIRECT_TRUST.equals(trustedIdp.getTrustType()),
+                      "TrustType doesn't match");
+        Assert.isTrue("Uhttps://localhost:12443/fediz-idp-remote/federation".equals(trustedIdp.getUrl()),
+                      "Url doesn't match"); 
+        Assert.isTrue(trustedIdp.isCacheTokens(), "CacheTokens doesn't match");
+        
+    }
+    
+    
+    @Test(expected = DataIntegrityViolationException.class)
+    public void testTryAddExistingTrustedIdp() {
+        TrustedIdp trustedIdp = createTrustedIdp("urn:org:apache:cxf:fediz:idp:realm-B");
+        trustedIdpDAO.addTrustedIDP(trustedIdp);
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryRemoveUnknownTrustedIdp() {
+        trustedIdpDAO.deleteTrustedIDP("urn:org:apache:cxf:fediz:trusted-idp:NOTEXIST");
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testRemoveExistingTrustedIdp() {
+        String realm = "urn:org:apache:cxf:fediz:trusted-idp:testdelete";
+        TrustedIdp trustedIdp = createTrustedIdp(realm);
+        
+        trustedIdpDAO.addTrustedIDP(trustedIdp);
+        
+        trustedIdpDAO.deleteTrustedIDP(realm);
+        
+        trustedIdpDAO.getTrustedIDP(realm);
+    }
+    
+    
+    private static TrustedIdp createTrustedIdp(String realm) {
+        TrustedIdp trustedIdp = new TrustedIdp();
+        trustedIdp.setRealm(realm);
+        trustedIdp.setCacheTokens(false);
+        trustedIdp.setCertificate("realmb.cert");
+        trustedIdp.setDescription("Realm B description");
+        trustedIdp.setFederationType(FederationType.FEDERATE_IDENTITY);
+        trustedIdp.setName("Realm B");
+        trustedIdp.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+        trustedIdp.setTrustType(TrustType.PEER_TRUST);
+        trustedIdp.setUrl("https://localhost:12443/fediz-idp-remote/federation");
+        return trustedIdp;
+    }
+    
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/util/MetadataWriterTest.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/util/MetadataWriterTest.java b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/util/MetadataWriterTest.java
new file mode 100644
index 0000000..85c369b
--- /dev/null
+++ b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/util/MetadataWriterTest.java
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.util;
+
+import org.w3c.dom.Document;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.metadata.IdpMetadataWriter;
+import org.apache.cxf.fediz.service.idp.service.ConfigService;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.ClassPathXmlApplicationContext;
+import org.springframework.util.Assert;
+
+public class MetadataWriterTest {
+
+    private static ApplicationContext applicationContext;
+    
+    @BeforeClass
+    public static void init() {
+        applicationContext = new ClassPathXmlApplicationContext("/idp-config.xml");
+    }
+    
+    @Test
+    public void testWriteIDPMetadata() {
+        ConfigService config = (ConfigService)applicationContext.getBean("config");
+        Assert.notNull(config, "ConfigService must not be null");
+        Idp idpConfig = config.getIDP("urn:org:apache:cxf:fediz:idp:realm-A");
+        Assert.notNull(idpConfig, "IDPConfig must not be null");
+        
+        IdpMetadataWriter writer = new IdpMetadataWriter();
+        Document doc = writer.getMetaData(idpConfig);
+        Assert.notNull(doc, "doc must not be null");
+        
+        System.out.println(DOM2Writer.nodeToString(doc));
+        
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/resources/entities-realma.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/resources/entities-realma.xml b/services/idp-core/src/test/resources/entities-realma.xml
new file mode 100644
index 0000000..61cfa0d
--- /dev/null
+++ b/services/idp-core/src/test/resources/entities-realma.xml
@@ -0,0 +1,504 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:util="http://www.springframework.org/schema/util"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util-4.3.xsd">
+
+    <bean id="idp-realmA" class="org.apache.cxf.fediz.service.idp.service.jpa.IdpEntity">
+        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-A" />
+        <property name="uri" value="realma" />
+        <property name="provideIdpList" value="true" />
+        <property name="useCurrentIdp" value="true" />
+        <property name="certificate" value="stsKeystoreA.properties" />
+        <property name="certificatePassword" value="realma" />
+        <property name="stsUrl" value="https://localhost:9443/fediz-idp-sts/REALMA" />
+        <property name="idpUrl" value="https://localhost:9443/fediz-idp/federation" />
+        <property name="rpSingleSignOutConfirmation" value="true"/>
+        <property name="supportedProtocols">
+            <util:list>
+                <value>http://docs.oasis-open.org/wsfed/federation/200706</value>
+                <value>http://docs.oasis-open.org/ws-sx/ws-trust/200512</value>
+            </util:list>
+        </property>
+        <property name="tokenTypesOffered">
+            <util:list>
+                <value>urn:oasis:names:tc:SAML:1.0:assertion</value>
+                <value>urn:oasis:names:tc:SAML:2.0:assertion</value>
+            </util:list>
+        </property>
+        <property name="authenticationURIs">
+            <util:map>
+                <entry key="default"
+                       value="federation/up" />
+                <entry key="http://docs.oasis-open.org/wsfed/authorization/200706/authntypes/SslAndKey" 
+                       value="federation/krb" />
+                <entry key="http://docs.oasis-open.org/wsfed/authorization/200706/authntypes/default"
+                       value="federation/up" />
+                <entry key="http://docs.oasis-open.org/wsfed/authorization/200706/authntypes/Ssl"
+                       value="federation/clientcert" />
+            </util:map>
+        </property>
+        <property name="serviceDisplayName" value="REALM A" />
+        <property name="serviceDescription" value="IDP of Realm A" />
+        <property name="applications">
+            <util:list>
+                <ref bean="srv-fedizhelloworld" />
+				<ref bean="srv-oidc" />
+            </util:list>
+        </property>
+        <property name="trustedIdps">
+            <util:list>
+                <ref bean="trusted-idp-realmB" />
+            </util:list>
+        </property>
+        <property name="claimTypesOffered">
+            <util:list>
+                <ref bean="claim_role" />
+                <ref bean="claim_surname" />
+                <ref bean="claim_givenname" />
+                <ref bean="claim_email" />
+            </util:list>
+        </property>
+    </bean>
+
+    <bean id="trusted-idp-realmB"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.TrustedIdpEntity">
+        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-B" />
+        <property name="cacheTokens" value="true" />
+        <property name="url" value="https://localhost:12443/fediz-idp-remote/federation" />
+        <property name="certificate" value="realmb.cert" />
+        <property name="trustType" value="PEER_TRUST" />
+        <property name="protocol" value="http://docs.oasis-open.org/wsfed/federation/200706" />
+        <property name="federationType" value="FEDERATE_IDENTITY" />
+        <property name="name" value="Realm B" />
+        <property name="description" value="Realm B description" />
+    </bean>
+
+    <bean id="srv-fedizhelloworld" class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationEntity">
+        <property name="realm" value="urn:org:apache:cxf:fediz:fedizhelloworld" />
+        <property name="protocol" value="http://docs.oasis-open.org/wsfed/federation/200706" />
+        <property name="serviceDisplayName" value="Fedizhelloworld" />
+        <property name="serviceDescription" value="Web Application to illustrate WS-Federation" />
+        <property name="role" value="ApplicationServiceType" />
+        <property name="tokenType" value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
+        <property name="lifeTime" value="3600" />
+        <property name="passiveRequestorEndpointConstraint" value="https://localhost:?(\d)*/.*" />
+    </bean>
+	
+	<bean id="srv-oidc" class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationEntity">
+        <property name="realm" value="urn:org:apache:cxf:fediz:oidc" />
+        <property name="protocol" value="http://docs.oasis-open.org/wsfed/federation/200706" />
+        <property name="serviceDisplayName" value="OIDC Provider" />
+        <property name="serviceDescription" value="OpenID Connect Provider" />
+        <property name="role" value="ApplicationServiceType" />
+        <property name="tokenType" value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
+        <property name="lifeTime" value="3600" />
+        <property name="passiveRequestorEndpointConstraint" value="https://localhost:?(\d)*/fediz-oidc/.*" />
+    </bean>
+    
+    <bean class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
+        <property name="application" ref="srv-fedizhelloworld" />
+        <property name="claim" ref="claim_role" />
+        <property name="optional" value="false" />
+    </bean>
+    <bean class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
+        <property name="application" ref="srv-fedizhelloworld" />
+        <property name="claim" ref="claim_givenname" />
+        <property name="optional" value="false" />
+    </bean>
+    <bean class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
+        <property name="application" ref="srv-fedizhelloworld" />
+        <property name="claim" ref="claim_surname" />
+        <property name="optional" value="false" />
+    </bean>
+    <bean class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
+        <property name="application" ref="srv-fedizhelloworld" />
+        <property name="claim" ref="claim_email" />
+        <property name="optional" value="false" />
+    </bean>
+    
+    <bean class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
+        <property name="application" ref="srv-oidc" />
+        <property name="claim" ref="claim_role" />
+        <property name="optional" value="false" />
+    </bean>
+    <bean class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
+        <property name="application" ref="srv-oidc" />
+        <property name="claim" ref="claim_givenname" />
+        <property name="optional" value="false" />
+    </bean>
+    <bean class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
+        <property name="application" ref="srv-oidc" />
+        <property name="claim" ref="claim_surname" />
+        <property name="optional" value="false" />
+    </bean>
+    <bean class="org.apache.cxf.fediz.service.idp.service.jpa.ApplicationClaimEntity">
+        <property name="application" ref="srv-oidc" />
+        <property name="claim" ref="claim_email" />
+        <property name="optional" value="false" />
+    </bean>
+    
+    <bean id="claim_role"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.ClaimEntity">
+        <property name="claimType"
+            value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role" />
+        <property name="displayName"
+            value="role" />
+        <property name="description"
+            value="Description for role" />
+    </bean>
+    <bean id="claim_givenname"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.ClaimEntity">
+        <property name="claimType"
+            value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" />
+        <property name="displayName"
+            value="firstname" />
+        <property name="description"
+            value="Description for firstname" />
+    </bean>
+    <bean id="claim_surname"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.ClaimEntity">
+        <property name="claimType"
+            value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" />
+        <property name="displayName"
+            value="lastname" />
+        <property name="description"
+            value="Description for lastname" />
+    </bean>
+    <bean id="claim_email"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.ClaimEntity">
+        <property name="claimType"
+            value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" />
+        <property name="displayName"
+            value="email" />
+        <property name="description"
+            value="Description for email" />
+    </bean>
+    
+    
+    <bean id="entitlement_claim_list"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="CLAIM_LIST" />
+        <property name="description"
+            value="Description for CLAIM_LIST" />
+    </bean>
+    <bean id="entitlement_claim_create"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="CLAIM_CREATE" />
+        <property name="description"
+            value="Description for CLAIM_CREATE" />
+    </bean>
+    <bean id="entitlement_claim_read"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="CLAIM_READ" />
+        <property name="description"
+            value="Description for CLAIM_READ" />
+    </bean>
+    <bean id="entitlement_claim_update"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="CLAIM_UPDATE" />
+        <property name="description"
+            value="Description for CLAIM_UPDATE" />
+    </bean>
+    <bean id="entitlement_claim_delete"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="CLAIM_DELETE" />
+        <property name="description"
+            value="Description for CLAIM_DELETE" />
+    </bean>
+
+    <bean id="entitlement_application_list"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="APPLICATION_LIST" />
+        <property name="description"
+            value="Description for APPLICATION_LIST" />
+    </bean>
+    <bean id="entitlement_application_create"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="APPLICATION_CREATE" />
+        <property name="description"
+            value="Description for APPLICATION_CREATE" />
+    </bean>
+    <bean id="entitlement_application_read"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="APPLICATION_READ" />
+        <property name="description"
+            value="Description for APPLICATION_READ" />
+    </bean>
+    <bean id="entitlement_application_update"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="APPLICATION_UPDATE" />
+        <property name="description"
+            value="Description for APPLICATION_UPDATE" />
+    </bean>
+    <bean id="entitlement_application_delete"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="APPLICATION_DELETE" />
+        <property name="description"
+            value="Description for APPLICATION_DELETE" />
+    </bean>
+    
+    <bean id="entitlement_trustedidp_list"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="TRUSTEDIDP_LIST" />
+        <property name="description"
+            value="Description for TRUSTEDIDP_LIST" />
+    </bean>
+    <bean id="entitlement_trustedidp_create"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="TRUSTEDIDP_CREATE" />
+        <property name="description"
+            value="Description for TRUSTEDIDP_CREATE" />
+    </bean>
+    <bean id="entitlement_trustedidp_read"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="TRUSTEDIDP_READ" />
+        <property name="description"
+            value="Description for TRUSTEDIDP_READ" />
+    </bean>
+    <bean id="entitlement_trustedidp_update"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="TRUSTEDIDP_UPDATE" />
+        <property name="description"
+            value="Description for TRUSTEDIDP_UPDATE" />
+    </bean>
+    <bean id="entitlement_trustedidp_delete"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="TRUSTEDIDP_DELETE" />
+        <property name="description"
+            value="Description for TRUSTEDIDP_DELETE" />
+    </bean>
+
+    <bean id="entitlement_idp_list"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="IDP_LIST" />
+        <property name="description"
+            value="Description for IDP_LIST" />
+    </bean>
+    <bean id="entitlement_idp_create"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="IDP_CREATE" />
+        <property name="description"
+            value="Description for IDP_CREATE" />
+    </bean>
+    <bean id="entitlement_idp_read"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="IDP_READ" />
+        <property name="description"
+            value="Description for IDP_READ" />
+    </bean>
+    <bean id="entitlement_idp_update"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="IDP_UPDATE" />
+        <property name="description"
+            value="Description for IDP_UPDATE" />
+    </bean>
+    <bean id="entitlement_idp_delete"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="IDP_DELETE" />
+        <property name="description"
+            value="Description for IDP_DELETE" />
+    </bean>
+    
+    <bean id="entitlement_role_list"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ROLE_LIST" />
+        <property name="description"
+            value="Description for ROLE_LIST" />
+    </bean>
+    <bean id="entitlement_role_create"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ROLE_CREATE" />
+        <property name="description"
+            value="Description for ROLE_CREATE" />
+    </bean>
+    <bean id="entitlement_role_read"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ROLE_READ" />
+        <property name="description"
+            value="Description for ROLE_READ" />
+    </bean>
+    <bean id="entitlement_role_update"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ROLE_UPDATE" />
+        <property name="description"
+            value="Description for ROLE_UPDATE" />
+    </bean>
+    <bean id="entitlement_role_delete"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ROLE_DELETE" />
+        <property name="description"
+            value="Description for ROLE_DELETE" />
+    </bean>
+    
+    <bean id="entitlement_entitlement_list"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ENTITLEMENT_LIST" />
+        <property name="description"
+            value="Description for ENTITLEMENT_LIST" />
+    </bean>
+    <bean id="entitlement_entitlement_create"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ENTITLEMENT_CREATE" />
+        <property name="description"
+            value="Description for ENTITLEMENT_CREATE" />
+    </bean>
+    <bean id="entitlement_entitlement_read"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ENTITLEMENT_READ" />
+        <property name="description"
+            value="Description for ENTITLEMENT_READ" />
+    </bean>
+    <bean id="entitlement_entitlement_update"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ENTITLEMENT_UPDATE" />
+        <property name="description"
+            value="Description for ENTITLEMENT_UPDATE" />
+    </bean>
+    <bean id="entitlement_entitlement_delete"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.EntitlementEntity">
+        <property name="name"
+            value="ENTITLEMENT_DELETE" />
+        <property name="description"
+            value="Description for ENTITLEMENT_DELETE" />
+    </bean>
+    
+    <bean id="role_admin"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.RoleEntity">
+        <property name="name"
+            value="ADMIN" />
+        <property name="description"
+            value="This is the administrator role with full access" />
+        <property name="entitlements">
+            <util:list>
+                <ref bean="entitlement_claim_list" />
+                <ref bean="entitlement_claim_create" />
+                <ref bean="entitlement_claim_read" />
+                <ref bean="entitlement_claim_update" />
+                <ref bean="entitlement_claim_delete" />
+                <ref bean="entitlement_idp_list" />
+                <ref bean="entitlement_idp_create" />
+                <ref bean="entitlement_idp_read" />
+                <ref bean="entitlement_idp_update" />
+                <ref bean="entitlement_idp_delete" />
+                <ref bean="entitlement_trustedidp_list" />
+                <ref bean="entitlement_trustedidp_create" />
+                <ref bean="entitlement_trustedidp_read" />
+                <ref bean="entitlement_trustedidp_update" />
+                <ref bean="entitlement_trustedidp_delete" />
+                <ref bean="entitlement_application_list" />
+                <ref bean="entitlement_application_create" />
+                <ref bean="entitlement_application_read" />
+                <ref bean="entitlement_application_update" />
+                <ref bean="entitlement_application_delete" />
+                <ref bean="entitlement_role_list" />
+                <ref bean="entitlement_role_create" />
+                <ref bean="entitlement_role_read" />
+                <ref bean="entitlement_role_update" />
+                <ref bean="entitlement_role_delete" />
+                <ref bean="entitlement_entitlement_list" />
+                <ref bean="entitlement_entitlement_create" />
+                <ref bean="entitlement_entitlement_read" />
+                <ref bean="entitlement_entitlement_update" />
+                <ref bean="entitlement_entitlement_delete" />
+            </util:list>
+        </property>
+    </bean>
+    <bean id="role_user"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.RoleEntity">
+        <property name="name"
+            value="USER" />
+        <property name="description"
+            value="This is the user role with read access" />
+        <property name="entitlements">
+            <util:list>
+                <ref bean="entitlement_claim_list" />
+                <ref bean="entitlement_claim_read" />
+                <ref bean="entitlement_idp_list" />
+                <ref bean="entitlement_idp_read" />
+                <ref bean="entitlement_trustedidp_list" />
+                <ref bean="entitlement_trustedidp_read" />
+                <ref bean="entitlement_application_list" />
+                <ref bean="entitlement_application_read" />
+                <ref bean="entitlement_role_list" />
+                <ref bean="entitlement_role_read" />
+                <ref bean="entitlement_entitlement_list" />
+                <ref bean="entitlement_entitlement_read" />
+            </util:list>
+        </property>
+    </bean>
+    <bean id="role_idp_login"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.RoleEntity">
+        <property name="name"
+            value="IDP_LOGIN" />
+        <property name="description"
+            value="This is the IDP login role which is applied to Users during the IDP SSO" />
+        <property name="entitlements">
+            <util:list>
+                <ref bean="entitlement_claim_list" />
+                <ref bean="entitlement_claim_read" />
+                <ref bean="entitlement_idp_list" />
+                <ref bean="entitlement_idp_read" />
+                <ref bean="entitlement_trustedidp_list" />
+                <ref bean="entitlement_trustedidp_read" />
+                <ref bean="entitlement_application_list" />
+                <ref bean="entitlement_application_read" />
+            </util:list>
+        </property>
+    </bean>
+    
+
+
+</beans>
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/resources/idp-config.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/resources/idp-config.xml b/services/idp-core/src/test/resources/idp-config.xml
new file mode 100644
index 0000000..61d0bbd
--- /dev/null
+++ b/services/idp-core/src/test/resources/idp-config.xml
@@ -0,0 +1,152 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:util="http://www.springframework.org/schema/util"
+       xmlns:http="http://cxf.apache.org/transports/http/configuration"
+       xmlns:context="http://www.springframework.org/schema/context"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util-4.3.xsd
+        http://cxf.apache.org/transports/http/configuration
+        http://cxf.apache.org/schemas/configuration/http-conf.xsd">
+
+    <context:property-placeholder location="classpath:realm.properties" />
+
+    <bean id="config"
+        class="org.apache.cxf.fediz.service.idp.service.ConfigServiceSpring">
+        <property name="idpConfigs">
+            <util:list>
+                <ref bean="idp-realmA" />
+            </util:list>
+        </property>
+        <property name="serviceConfigs">
+            <util:list>
+                <ref bean="srv-fedizhelloworld" />
+            </util:list>
+        </property>
+    </bean>
+
+    <bean id="idp-realmA" class="org.apache.cxf.fediz.service.idp.model.IDPConfig">
+        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-A" />
+        <property name="uri" value="realma" />
+        <!--<property name="hrds" value="" /> --> <!-- TBD, not defined, provide list if enabled -->
+        <property name="provideIdpList" value="true" />
+        <property name="useCurrentIdp" value="true" />
+        <!-- <property name="certificate" value="realma.cert" /> -->   <!-- STS will sign token, IDP signs Metadata -->
+        <property name="certificate" value="stsKeystoreA.properties" />
+        <property name="certificatePassword" value="realma" />
+        <property name="stsUrl"
+            value="https://localhost:0/fediz-idp-sts/REALMA" />
+        <property name="idpUrl"
+            value="https://localhost:${realmA.port}/fediz-idp/federation" />
+        <property name="supportedProtocols">
+            <util:list>
+                <value>http://docs.oasis-open.org/wsfed/federation/200706
+                </value>
+                <value>http://docs.oasis-open.org/ws-sx/ws-trust/200512
+                </value>
+            </util:list>
+        </property>
+        <property name="services">
+            <util:map>
+                <entry key="urn:org:apache:cxf:fediz:fedizhelloworld"
+                    value-ref="srv-fedizhelloworld" />
+            </util:map>
+        </property>
+        <property name="authenticationURIs">
+            <util:map>
+                <entry key="default" value="/login/default" />
+            </util:map>
+        </property>
+        <property name="trustedIdps">
+            <util:map>
+                <entry key="urn:org:apache:cxf:fediz:idp:realm-B"
+                    value-ref="trusted-idp-realmB" />
+            </util:map>
+        </property>
+        <property name="serviceDisplayName" value="REALM A" />
+        <property name="serviceDescription" value="IDP of Realm A" />
+    </bean>
+
+    <bean id="trusted-idp-realmB"
+        class="org.apache.cxf.fediz.service.idp.model.TrustedIDPConfig">
+        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-B" />
+        <property name="cacheTokens" value="true" />
+        <property name="url"
+            value="https://localhost:${realmB.port}/fediz-idp-remote/federation" />
+        <property name="certificate" value="realmb.cert" />
+        <property name="trustType" value="PEER_TRUST" />  <!-- Required for Fediz Core, Process SignInResponse -->
+        <property name="protocol"
+            value="http://docs.oasis-open.org/wsfed/federation/200706" />
+        <property name="federationType" value="FEDERATE_IDENTITY" /> <!-- Required for STS Relationship -->
+        <property name="name" value="REALM B" />
+        <property name="description" value="IDP of Realm B" />
+        <!--<property name="logo" value="true" /> -->
+    </bean>
+
+    <bean id="srv-fedizhelloworld" class="org.apache.cxf.fediz.service.idp.model.ServiceConfig">
+        <property name="realm"
+            value="urn:org:apache:cxf:fediz:fedizhelloworld" />
+        <property name="protocol"
+            value="http://docs.oasis-open.org/wsfed/federation/200706" />
+        <property name="serviceDisplayName" value="Fedizhelloworld" />
+        <property name="serviceDescription"
+            value="Web Application to illustrate WS-Federation" />
+        <property name="role" value="ApplicationServiceType" />
+        <property name="tokenType"
+            value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
+        <property name="lifeTime" value="3600" />
+        <!-- <property name="encryptionCertificate" value="" /> -->
+        <property name="requestedClaims">
+            <util:list>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" />
+                    <property name="optional" value="false" />
+                </bean>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" />
+                    <property name="optional" value="false" />
+                </bean>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" />
+                    <property name="optional" value="false" />
+                </bean>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role" />
+                    <property name="optional" value="true" />
+                </bean>
+            </util:list>
+        </property>
+    </bean>
+
+</beans>
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/resources/persistence.properties
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/resources/persistence.properties b/services/idp-core/src/test/resources/persistence.properties
new file mode 100644
index 0000000..b4e0320
--- /dev/null
+++ b/services/idp-core/src/test/resources/persistence.properties
@@ -0,0 +1,14 @@
+#jpa.driverClassName=org.apache.derby.jdbc.ClientDriver
+#jpa.url=jdbc:derby://localhost:1527/Fediz
+#jpa.username=admin
+#jpa.password=admin
+#jpa.defaultData=true
+#jpa.platform=DerbyDictionary
+
+
+jpa.driverClassName=org.hsqldb.jdbcDriver
+jpa.url=jdbc:hsqldb:target/db/unit/myDB;shutdown=true
+jpa.username=sa
+jpa.password=
+jpa.defaultData=true
+jpa.platform=HSQLDictionary

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/resources/persistenceContext.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/resources/persistenceContext.xml b/services/idp-core/src/test/resources/persistenceContext.xml
new file mode 100644
index 0000000..f0b3586
--- /dev/null
+++ b/services/idp-core/src/test/resources/persistenceContext.xml
@@ -0,0 +1,107 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans profile="jpa" xmlns="http://www.springframework.org/schema/beans"
+       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+       xmlns:tx="http://www.springframework.org/schema/tx"
+       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
+       xmlns:context="http://www.springframework.org/schema/context"
+       xsi:schemaLocation="http://www.springframework.org/schema/beans
+    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+    http://www.springframework.org/schema/context
+    http://www.springframework.org/schema/context/spring-context-4.3.xsd
+    http://www.springframework.org/schema/tx
+    http://www.springframework.org/schema/tx/spring-tx.xsd
+    http://www.springframework.org/schema/jdbc
+    http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd"
+       default-autowire="byName">
+    
+    <context:component-scan base-package="org.apache.cxf.fediz.service.idp.service" />
+    <context:component-scan base-package="org.apache.cxf.fediz.service.idp.rest" />
+
+    <bean id="entityManagerFactory"
+        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
+        <property name="persistenceXmlLocation"
+            value="classpath*:META-INF/spring-persistence.xml" />
+        <property name="persistenceUnitName" value="fedizPersistenceUnit" />
+        <property name="dataSource" ref="dataSource" />
+        <property name="jpaVendorAdapter">
+            <bean
+                class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
+                <property name="showSql" value="false" />
+                <property name="generateDdl" value="true" />
+                <property name="databasePlatform" value="org.apache.openjpa.jdbc.sql.${jpa.platform}" />
+            </bean>
+        </property>
+        <property name="jpaPropertyMap">
+            <map>
+                <entry key="javax.persistence.validation.factory" value-ref="validator" />
+            </map>
+        </property>
+    </bean>
+
+    <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
+        <property name="jndiName" value="java:comp/env/jdbc/fedizDataSource" />
+        <property name="defaultObject" ref="localDataSource" />
+    </bean>
+
+    <bean id="localDataSource" class="org.apache.commons.dbcp2.BasicDataSource"
+        destroy-method="close">
+        <property name="driverClassName" value="${jpa.driverClassName}" />
+        <property name="url" value="${jpa.url}" />
+        <property name="username" value="${jpa.username}" />
+        <property name="password" value="${jpa.password}" />
+    </bean>
+
+    <bean id="entityManager"
+        class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
+        <property name="entityManagerFactory" ref="entityManagerFactory" />
+    </bean>
+
+    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
+        <property name="entityManagerFactory" ref="entityManagerFactory" />
+    </bean>
+
+    <!-- Support annotation Transactional http://docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/#tx-decl-explained -->
+    <tx:annotation-driven />
+
+    <!-- Support annotation PersistenceContext http://docs.spring.io/spring/docs/3.1.4.RELEASE/spring-framework-reference/htmlsingle/#orm-jpa-straight -->
+    <bean
+        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
+
+    <!-- Requires updates to unit testing as no JPA exceptions are returned -->
+    <bean
+        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
+
+    <bean id="config"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.ConfigServiceJPA">
+        <property name="idpService" ref="idpServiceImpl" />
+    </bean>
+
+    <bean id="dbLoader"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.DBLoaderSpring">
+        <property name="resource" value="${db-load-config}" />
+    </bean>
+
+    <bean id="dbListener"
+        class="org.apache.cxf.fediz.service.idp.service.jpa.DBInitApplicationListener" />
+        
+    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
+
+</beans>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/resources/realm.properties
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/resources/realm.properties b/services/idp-core/src/test/resources/realm.properties
new file mode 100644
index 0000000..9414fc0
--- /dev/null
+++ b/services/idp-core/src/test/resources/realm.properties
@@ -0,0 +1,4 @@
+realm.STS_URI=REALMA
+realmA.port=8443
+realmB.port=12443
+db-load-config=entities-realma.xml


[19/19] cxf-fediz git commit: Fixing failing test

Posted by co...@apache.org.
Fixing failing test


Project: http://git-wip-us.apache.org/repos/asf/cxf-fediz/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf-fediz/commit/15690cad
Tree: http://git-wip-us.apache.org/repos/asf/cxf-fediz/tree/15690cad
Diff: http://git-wip-us.apache.org/repos/asf/cxf-fediz/diff/15690cad

Branch: refs/heads/master
Commit: 15690cad1de1b7e7505f3129edf05648109ce9a9
Parents: bf30940
Author: Colm O hEigeartaigh <co...@apache.org>
Authored: Fri Jan 27 11:22:30 2017 +0000
Committer: Colm O hEigeartaigh <co...@apache.org>
Committed: Fri Jan 27 11:22:30 2017 +0000

----------------------------------------------------------------------
 systests/custom/pom.xml | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/15690cad/systests/custom/pom.xml
----------------------------------------------------------------------
diff --git a/systests/custom/pom.xml b/systests/custom/pom.xml
index e90d7ff..697ca3d 100644
--- a/systests/custom/pom.xml
+++ b/systests/custom/pom.xml
@@ -191,7 +191,8 @@
                                     </includes>
                                     <filtering>false</filtering>
                                 </resource>
-                            </resources>              
+                            </resources>       
+                             <overwrite>true</overwrite>       
                         </configuration>            
                     </execution>
                     <execution>


[15/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
new file mode 100644
index 0000000..7c5baec
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
@@ -0,0 +1,180 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.metadata;
+
+import java.security.cert.X509Certificate;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.w3c.dom.Document;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.core.util.SignatureUtils;
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.staxutils.W3CDOMStreamWriter;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.apache.xml.security.stax.impl.util.IDGenerator;
+import org.apache.xml.security.utils.Base64;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.cxf.fediz.core.FedizConstants.SAML2_METADATA_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.SCHEMA_INSTANCE_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.WS_ADDRESSING_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.WS_FEDERATION_NS;
+
+public class IdpMetadataWriter {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(IdpMetadataWriter.class);
+    
+    //CHECKSTYLE:OFF
+    public Document getMetaData(Idp config) throws RuntimeException {
+        try {
+            //Return as text/xml
+            Crypto crypto = CertsUtils.getCryptoFromFile(config.getCertificate());
+
+            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
+
+            writer.writeStartDocument("UTF-8", "1.0");
+
+            String referenceID = IDGenerator.generateID("_");
+            writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS);
+            writer.writeAttribute("ID", referenceID);
+
+            writer.writeAttribute("entityID", config.getIdpUrl().toString());
+
+            writer.writeNamespace("md", SAML2_METADATA_NS);
+            writer.writeNamespace("fed", WS_FEDERATION_NS);
+            writer.writeNamespace("wsa", WS_ADDRESSING_NS);
+            writer.writeNamespace("auth", WS_FEDERATION_NS);
+            writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
+
+            writeFederationMetadata(writer, config, crypto);
+
+            writer.writeEndElement(); // EntityDescriptor
+
+            writer.writeEndDocument();
+
+            writer.close();
+
+            if (LOG.isDebugEnabled()) {
+                String out = DOM2Writer.nodeToString(writer.getDocument());
+                LOG.debug("***************** unsigned ****************");
+                LOG.debug(out);
+                LOG.debug("***************** unsigned ****************");
+            }
+
+            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), 
+                                                          writer.getDocument(), referenceID);
+            if (result != null) {
+                return result;
+            } else {
+                throw new RuntimeException("Failed to sign the metadata document: result=null");
+            }
+        } catch (Exception e) {
+            LOG.error("Error creating service metadata information ", e);
+            throw new RuntimeException("Error creating service metadata information: " + e.getMessage());
+        }
+
+    }
+    
+    private void writeFederationMetadata(
+        XMLStreamWriter writer, Idp config, Crypto crypto
+    ) throws XMLStreamException {
+
+        writer.writeStartElement("md", "RoleDescriptor", WS_FEDERATION_NS);
+        writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType");
+        writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
+        if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) {
+            writer.writeAttribute("ServiceDescription", config.getServiceDescription());
+        }
+        if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) {
+            writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName());
+        }
+
+        //http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd
+        //missing organization, contactperson
+
+        //KeyDescriptor
+        writer.writeStartElement("", "KeyDescriptor", SAML2_METADATA_NS);
+        writer.writeAttribute("use", "signing");
+        writer.writeStartElement("", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
+        writer.writeStartElement("", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
+        writer.writeStartElement("", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");
+
+        try {
+            String keyAlias = crypto.getDefaultX509Identifier();
+            X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
+            writer.writeCharacters(Base64.encode(cert.getEncoded()));
+        } catch (Exception ex) {
+            LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex);
+        }
+
+        writer.writeEndElement(); // X509Certificate
+        writer.writeEndElement(); // X509Data
+        writer.writeEndElement(); // KeyInfo
+        writer.writeEndElement(); // KeyDescriptor
+
+
+        // SecurityTokenServiceEndpoint
+        writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS);
+        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
+
+        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
+        writer.writeCharacters(config.getStsUrl().toString());
+
+        writer.writeEndElement(); // Address
+        writer.writeEndElement(); // EndpointReference
+        writer.writeEndElement(); // SecurityTokenServiceEndpoint
+
+
+        // PassiveRequestorEndpoint
+        writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
+        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
+
+        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
+        writer.writeCharacters(config.getIdpUrl().toString());
+
+        writer.writeEndElement(); // Address
+        writer.writeEndElement(); // EndpointReference
+        writer.writeEndElement(); // PassiveRequestorEndpoint
+
+
+        // create ClaimsType section
+        if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) {
+            writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS);
+            for (Claim claim : config.getClaimTypesOffered()) {
+
+                writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS);
+                writer.writeAttribute("Uri", claim.getClaimType().toString());
+                writer.writeAttribute("Optional", "true");
+                writer.writeEndElement(); // ClaimType
+
+            }
+            writer.writeEndElement(); // ClaimTypesOffered
+        }
+
+        writer.writeEndElement(); // RoleDescriptor
+    }
+
+ 
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
new file mode 100644
index 0000000..3118d8f
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
@@ -0,0 +1,214 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.metadata;
+
+import java.security.cert.X509Certificate;
+import java.util.Map;
+
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
+
+import org.w3c.dom.Document;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.core.util.SignatureUtils;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler;
+import org.apache.cxf.staxutils.W3CDOMStreamWriter;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.apache.xml.security.stax.impl.util.IDGenerator;
+import org.apache.xml.security.utils.Base64;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.cxf.fediz.core.FedizConstants.SAML2_METADATA_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.SCHEMA_INSTANCE_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.WS_ADDRESSING_NS;
+import static org.apache.cxf.fediz.core.FedizConstants.WS_FEDERATION_NS;
+
+public class ServiceMetadataWriter {
+    
+    private static final Logger LOG = LoggerFactory.getLogger(ServiceMetadataWriter.class);
+
+    //CHECKSTYLE:OFF
+    public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException {
+
+        try {
+            Crypto crypto = CertsUtils.getCryptoFromFile(config.getCertificate());
+            
+            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
+
+            writer.writeStartDocument("UTF-8", "1.0");
+
+            String referenceID = IDGenerator.generateID("_");
+            writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS);
+            writer.writeAttribute("ID", referenceID);
+            
+            String serviceURL = config.getIdpUrl().toString();
+            writer.writeAttribute("entityID", config.getRealm());
+            
+            writer.writeNamespace("md", SAML2_METADATA_NS);
+            writer.writeNamespace("fed", WS_FEDERATION_NS);
+            writer.writeNamespace("wsa", WS_ADDRESSING_NS);
+            writer.writeNamespace("auth", WS_FEDERATION_NS);
+            writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
+
+            if ("http://docs.oasis-open.org/wsfed/federation/200706".equals(serviceConfig.getProtocol())) {
+                writeFederationMetadata(writer, serviceConfig, serviceURL);
+            } else if ("urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser".equals(serviceConfig.getProtocol())) {
+                writeSAMLMetadata(writer, serviceConfig, serviceURL, crypto);
+            }
+            
+            writer.writeEndElement(); // EntityDescriptor
+
+            writer.writeEndDocument();
+            
+            writer.close();
+
+            if (LOG.isDebugEnabled()) {
+                String out = DOM2Writer.nodeToString(writer.getDocument());
+                LOG.debug("***************** unsigned ****************");
+                LOG.debug(out);
+                LOG.debug("***************** unsigned ****************");
+            }
+
+            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), 
+                                                          writer.getDocument(), referenceID);
+            if (result != null) {
+                return result;
+            } else {
+                throw new RuntimeException("Failed to sign the metadata document: result=null");
+            }
+        } catch (ProcessingException e) {
+            throw e;
+        } catch (Exception e) {
+            LOG.error("Error creating service metadata information ", e);
+            throw new ProcessingException("Error creating service metadata information: " + e.getMessage());
+        }
+
+    }
+
+    private void writeFederationMetadata(
+        XMLStreamWriter writer, 
+        TrustedIdp config,
+        String serviceURL
+    ) throws XMLStreamException {
+
+        writer.writeStartElement("md", "RoleDescriptor", WS_FEDERATION_NS);
+        writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:ApplicationServiceType");
+        writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
+
+        writer.writeStartElement("fed", "ApplicationServiceEndpoint", WS_FEDERATION_NS);
+        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
+
+        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
+        writer.writeCharacters(serviceURL);
+        
+        writer.writeEndElement(); // Address
+        writer.writeEndElement(); // EndpointReference
+        writer.writeEndElement(); // ApplicationServiceEndpoint
+
+        // create target scope element
+        writer.writeStartElement("fed", "TargetScope", WS_FEDERATION_NS);
+        writer.writeEndElement(); // TargetScope
+
+        // create sign in endpoint section
+
+        writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
+        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
+        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
+
+        writer.writeCharacters(serviceURL);
+
+        // writer.writeCharacters("http://host:port/url Issuer from config");
+        writer.writeEndElement(); // Address
+        writer.writeEndElement(); // EndpointReference
+
+        writer.writeEndElement(); // PassiveRequestorEndpoint
+        writer.writeEndElement(); // RoleDescriptor
+    }
+    
+    private void writeSAMLMetadata(
+        XMLStreamWriter writer, 
+        TrustedIdp config,
+        String serviceURL,
+        Crypto crypto
+    ) throws Exception {
+        
+        writer.writeStartElement("md", "SPSSODescriptor", SAML2_METADATA_NS);
+        boolean signRequest = 
+            isPropertyConfigured(config, TrustedIdpSAMLProtocolHandler.SIGN_REQUEST, true);
+        writer.writeAttribute("AuthnRequestsSigned", Boolean.toString(signRequest));
+        writer.writeAttribute("WantAssertionsSigned", "true");
+        writer.writeAttribute("protocolSupportEnumeration", "urn:oasis:names:tc:SAML:2.0:protocol");
+        
+        writer.writeStartElement("md", "AssertionConsumerService", SAML2_METADATA_NS);
+        writer.writeAttribute("Location", serviceURL);
+        writer.writeAttribute("index", "0");
+        writer.writeAttribute("isDefault", "true");
+        writer.writeAttribute("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
+        writer.writeEndElement(); // AssertionConsumerService
+        
+        if (signRequest) {
+            writer.writeStartElement("md", "KeyDescriptor", SAML2_METADATA_NS);
+            writer.writeAttribute("use", "signing");
+            
+            writer.writeStartElement("ds", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
+            writer.writeNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
+            writer.writeStartElement("ds", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
+            writer.writeStartElement("ds", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");
+
+            // Write the Base-64 encoded certificate
+            
+            String keyAlias = crypto.getDefaultX509Identifier();
+            X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
+            
+            if (cert == null) {
+                throw new ProcessingException(
+                    "No signing certs were found to insert into the metadata using name: " 
+                        + keyAlias);
+            }
+            byte data[] = cert.getEncoded();
+            String encodedCertificate = Base64.encode(data);
+            writer.writeCharacters(encodedCertificate);
+            
+            writer.writeEndElement(); // X509Certificate
+            writer.writeEndElement(); // X509Data
+            writer.writeEndElement(); // KeyInfo
+            writer.writeEndElement(); // KeyDescriptor
+        }
+        
+        writer.writeEndElement(); // SPSSODescriptor
+    }
+    
+    // Is a property configured. Defaults to "true" if not
+    private boolean isPropertyConfigured(TrustedIdp trustedIdp, String property, boolean defaultValue) {
+        Map<String, String> parameters = trustedIdp.getParameters();
+        
+        if (parameters != null && parameters.containsKey(property)) {
+            return Boolean.parseBoolean(parameters.get(property));
+        }
+        
+        return defaultValue;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java
new file mode 100644
index 0000000..9b9c5cd
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java
@@ -0,0 +1,44 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.model;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+
+public class IDPConfig extends Idp {
+
+    private static final long serialVersionUID = -5570301342547139039L;
+
+    public void setServices(Map<String, Application> applications) {
+        this.applications = new ArrayList<>(applications.values());
+    }
+    
+    public void setTrustedIdps(Map<String, TrustedIDPConfig> trustedIdps) {
+        this.trustedIdpList = new ArrayList<TrustedIdp>(trustedIdps.values());
+    }
+    
+    @Deprecated
+    public void setTrustedIDPs(Map<String, TrustedIDPConfig> trustedIdps) {
+        setTrustedIdps(trustedIdps);
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java
new file mode 100644
index 0000000..6fd3d05
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/RequestClaim.java
@@ -0,0 +1,26 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.model;
+
+//@XmlRootElement(name = "Claim", namespace = "http://org.apache.cxf.fediz")
+public class RequestClaim extends org.apache.cxf.fediz.service.idp.domain.RequestClaim {
+    
+    private static final long serialVersionUID = 2635896159019665467L;
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java
new file mode 100644
index 0000000..fdae8f5
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/ServiceConfig.java
@@ -0,0 +1,35 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.model;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+
+//import javax.persistence.Column;
+//import javax.persistence.Entity;
+//import javax.persistence.Id;
+//import javax.persistence.Table;
+
+//@Entity
+//@Table(name = "SERVICE")
+//@XmlRootElement(name = "Service", namespace = "http://org.apache.cxf.fediz")
+public class ServiceConfig extends Application {
+        
+    private static final long serialVersionUID = 585676715065240699L;       
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java
new file mode 100644
index 0000000..89c2bbb
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPConfig.java
@@ -0,0 +1,30 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.model;
+
+
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+
+//@XmlRootElement(name = "TrustedIDP", namespace = "http://org.apache.cxf.fediz")
+public class TrustedIDPConfig extends TrustedIdp {
+
+    private static final long serialVersionUID = -1182000443945024801L;
+
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java
new file mode 100644
index 0000000..44cb3a2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/model/TrustedIDPSelection.java
@@ -0,0 +1,36 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.model;
+
+import java.io.Serializable;
+
+public class TrustedIDPSelection implements Serializable {
+
+    private static final long serialVersionUID = 1L;
+    
+    private String homeRealm;
+
+    public String getHomeRealm() {
+        return homeRealm;
+    }
+
+    public void setHomeRealm(String homeRealm) {
+        this.homeRealm = homeRealm;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java
new file mode 100644
index 0000000..84a70ca
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpOAuth2ProtocolHandler.java
@@ -0,0 +1,207 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.Date;
+
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.saml.SAMLCallback;
+import org.apache.wss4j.common.saml.SAMLUtil;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.wss4j.common.saml.bean.ConditionsBean;
+import org.apache.wss4j.common.saml.bean.SubjectBean;
+import org.apache.wss4j.common.saml.bean.Version;
+import org.apache.wss4j.common.saml.builder.SAML2Constants;
+import org.joda.time.DateTime;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.webflow.execution.RequestContext;
+
+public abstract class AbstractTrustedIdpOAuth2ProtocolHandler extends AbstractTrustedIdpProtocolHandler {
+    
+    /**
+     * The client_id value to send to the IdP.
+     */
+    public static final String CLIENT_ID = "client.id";
+    
+    /**
+     * The secret associated with the client to authenticate to the IdP.
+     */
+    public static final String CLIENT_SECRET = "client.secret";
+    
+    /**
+     * The Token endpoint. The authorization endpoint is specified by TrustedIdp.url.
+     */
+    public static final String TOKEN_ENDPOINT = "token.endpoint";
+    
+    /**
+     * Additional (space-separated) parameters to be sent in the "scope" to the authorization endpoint.
+     * The default value depends on the subclass.
+     */
+    public static final String SCOPE = "scope";
+    
+    private static final Logger LOG = LoggerFactory.getLogger(AbstractTrustedIdpOAuth2ProtocolHandler.class);
+
+    @Override
+    public URL mapSignInRequest(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+        
+        String clientId = getProperty(trustedIdp, CLIENT_ID);
+        if (clientId == null || clientId.isEmpty()) {
+            LOG.warn("A CLIENT_ID must be configured for OAuth 2.0");
+            throw new IllegalStateException("No CLIENT_ID specified");
+        }
+        
+        String scope = getScope(trustedIdp);
+        LOG.debug("Using scope: {}", scope);
+        
+        try {
+            StringBuilder sb = new StringBuilder();
+            sb.append(trustedIdp.getUrl());
+            sb.append("?");
+            sb.append("response_type").append('=');
+            sb.append("code");
+            sb.append("&");
+            sb.append("client_id").append('=');
+            sb.append(clientId);
+            sb.append("&");
+            sb.append("redirect_uri").append('=');
+            sb.append(URLEncoder.encode(idp.getIdpUrl().toString(), "UTF-8"));
+            sb.append("&");
+            sb.append("scope").append('=');
+            sb.append(URLEncoder.encode(scope, "UTF-8"));
+            
+            String state = context.getFlowScope().getString(IdpConstants.TRUSTED_IDP_CONTEXT);
+            sb.append("&").append("state").append('=');
+            sb.append(state);
+            
+            return new URL(sb.toString());
+        } catch (MalformedURLException ex) {
+            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
+            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
+        } catch (UnsupportedEncodingException ex) {
+            LOG.error("Invalid Redirect URL for Trusted Idp", ex);
+            throw new IllegalStateException("Invalid Redirect URL for Trusted Idp");
+        }
+    }
+    
+    protected SamlAssertionWrapper createSamlAssertion(Idp idp, TrustedIdp trustedIdp, String subjectName,
+                                                     Date notBefore,
+                                                     Date expires) throws Exception {
+        SamlCallbackHandler callbackHandler = new SamlCallbackHandler();
+        String issuer = idp.getServiceDisplayName();
+        if (issuer == null) {
+            issuer = idp.getRealm();
+        }
+        if (issuer != null) {
+            callbackHandler.setIssuer(issuer);
+        }
+        
+        // Subject
+        SubjectBean subjectBean =
+            new SubjectBean(subjectName, SAML2Constants.NAMEID_FORMAT_UNSPECIFIED, SAML2Constants.CONF_BEARER);
+        callbackHandler.setSubjectBean(subjectBean);
+        
+        // Conditions
+        ConditionsBean conditionsBean = new ConditionsBean();
+        conditionsBean.setNotAfter(new DateTime(expires));
+        if (notBefore != null) {
+            DateTime notBeforeDT = new DateTime(notBefore);
+            conditionsBean.setNotBefore(notBeforeDT);
+        } else {
+            conditionsBean.setNotBefore(new DateTime());
+        }
+        callbackHandler.setConditionsBean(conditionsBean);
+        
+        SAMLCallback samlCallback = new SAMLCallback();
+        SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
+        
+        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
+        
+        Crypto crypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
+        assertion.signAssertion(crypto.getDefaultX509Identifier(), idp.getCertificatePassword(), 
+                                crypto, false);
+        
+        return assertion;
+    }
+    
+    private static class SamlCallbackHandler implements CallbackHandler {
+        private ConditionsBean conditionsBean;
+        private SubjectBean subjectBean;
+        private String issuer;
+        
+        /**
+         * Set the SubjectBean
+         */
+        public void setSubjectBean(SubjectBean subjectBean) {
+            this.subjectBean = subjectBean;
+        }
+        
+        /**
+         * Set the ConditionsBean
+         */
+        public void setConditionsBean(ConditionsBean conditionsBean) {
+            this.conditionsBean = conditionsBean;
+        }
+        
+        /**
+         * Set the issuer name
+         */
+        public void setIssuer(String issuerName) {
+            this.issuer = issuerName;
+        }
+        
+        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
+            for (Callback callback : callbacks) {
+                if (callback instanceof SAMLCallback) {
+                    SAMLCallback samlCallback = (SAMLCallback) callback;
+
+                    // Set the Subject
+                    if (subjectBean != null) {
+                        samlCallback.setSubject(subjectBean);
+                    }
+                    samlCallback.setSamlVersion(Version.SAML_20);
+                    
+                    // Set the issuer
+                    samlCallback.setIssuer(issuer);
+
+                    // Set the conditions
+                    samlCallback.setConditions(conditionsBean);
+                }
+            }
+        }
+        
+    }
+    
+    abstract String getScope(TrustedIdp trustedIdp);
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
new file mode 100644
index 0000000..2329eb2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/AbstractTrustedIdpProtocolHandler.java
@@ -0,0 +1,58 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
+
+public abstract class AbstractTrustedIdpProtocolHandler implements TrustedIdpProtocolHandler {
+    
+    @Override
+    public boolean canHandleRequest(HttpServletRequest request) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    protected String getProperty(TrustedIdp trustedIdp, String property) {
+        Map<String, String> parameters = trustedIdp.getParameters();
+        
+        if (parameters != null && parameters.containsKey(property)) {
+            return parameters.get(property);
+        }
+        
+        return null;
+    }
+    
+    // Is a property configured. Defaults to the boolean "defaultValue" if not
+    protected boolean isBooleanPropertyConfigured(TrustedIdp trustedIdp, String property, boolean defaultValue) {
+        Map<String, String> parameters = trustedIdp.getParameters();
+        
+        if (parameters != null && parameters.containsKey(property)) {
+            return Boolean.parseBoolean(parameters.get(property));
+        }
+        
+        return defaultValue;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java
new file mode 100644
index 0000000..c2be3eb
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationProtocolControllerImpl.java
@@ -0,0 +1,60 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class ApplicationProtocolControllerImpl implements ProtocolController<ApplicationProtocolHandler> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ApplicationProtocolControllerImpl.class);
+    
+    @Autowired
+    private List<ApplicationProtocolHandler> protocolHandlers;
+    
+    @Override
+    public ApplicationProtocolHandler getProtocolHandler(String protocol) {
+        for (ApplicationProtocolHandler protocolHandler : protocolHandlers) {
+            if (protocolHandler.getProtocol() != null && protocolHandler.getProtocol().equals(protocol)) {
+                return protocolHandler;
+            }
+        }
+        LOG.warn("No protocol handler found for {}", protocol);
+        return null;
+    }
+    
+    @Override
+    public List<String> getProtocols() {
+        List<String> protocols = new ArrayList<>();
+        for (ApplicationProtocolHandler protocolHandler : protocolHandlers) {
+            protocols.add(protocolHandler.getProtocol());
+        }
+        return Collections.unmodifiableList(protocols);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java
new file mode 100644
index 0000000..ebab362
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationSAMLSSOProtocolHandler.java
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
+
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+@Component
+public class ApplicationSAMLSSOProtocolHandler implements ApplicationProtocolHandler {
+    
+    public static final String PROTOCOL = "urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser";
+
+    //private static final Logger LOG = LoggerFactory.getLogger(ApplicationWSFedProtocolHandler.class);
+
+    @Override
+    public boolean canHandleRequest(HttpServletRequest request) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+
+    @Override
+    public void mapSignInRequest(RequestContext context) {
+        // TODO Auto-generated method stub
+    }
+
+    @Override
+    public void mapSignInResponse(RequestContext context) {
+        // TODO Auto-generated method stub
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java
new file mode 100644
index 0000000..2024e3d
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ApplicationWSFedProtocolHandler.java
@@ -0,0 +1,57 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import javax.servlet.http.HttpServletRequest;
+
+import org.apache.cxf.fediz.service.idp.spi.ApplicationProtocolHandler;
+
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+@Component
+public class ApplicationWSFedProtocolHandler implements ApplicationProtocolHandler {
+    
+    public static final String PROTOCOL = "http://docs.oasis-open.org/wsfed/federation/200706";
+
+    //private static final Logger LOG = LoggerFactory.getLogger(ApplicationWSFedProtocolHandler.class);
+
+    @Override
+    public boolean canHandleRequest(HttpServletRequest request) {
+        // TODO Auto-generated method stub
+        return false;
+    }
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+
+    @Override
+    public void mapSignInRequest(RequestContext context) {
+        // TODO Auto-generated method stub
+    }
+
+    @Override
+    public void mapSignInResponse(RequestContext context) {
+        // TODO Auto-generated method stub
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java
new file mode 100644
index 0000000..d4da6c2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/ProtocolController.java
@@ -0,0 +1,32 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.spi.ProtocolHandler;
+
+public interface ProtocolController<T extends ProtocolHandler> {
+
+    T getProtocolHandler(String protocol);
+
+    List<String> getProtocols();
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
new file mode 100644
index 0000000..36db3ae
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpFacebookProtocolHandler.java
@@ -0,0 +1,226 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.Response;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.helpers.DOMUtils;
+import org.apache.cxf.interceptor.LoggingInInterceptor;
+import org.apache.cxf.interceptor.LoggingOutInterceptor;
+import org.apache.cxf.jaxrs.client.ClientConfiguration;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.jaxrs.json.basic.JsonMapObject;
+import org.apache.cxf.jaxrs.provider.json.JsonMapObjectProvider;
+import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken;
+import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider;
+import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.xml.security.stax.impl.util.IDGenerator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Extension of AbstractTrustedIdpOAuth2ProtocolHandler for Facebook Connect.
+ * Default values:
+ *  - scope: email
+ *  - token.endpoint: https://graph.facebook.com/v2.6/oauth/access_token
+ */
+@Component
+public class TrustedIdpFacebookProtocolHandler extends AbstractTrustedIdpOAuth2ProtocolHandler {
+    
+    /**
+     * The facebook API endpoint for querying claims (such as email address). If not specified
+     * it defaults to "https://graph.facebook.com/v2.6".
+     */
+    public static final String API_ENDPOINT = "api.endpoint";
+    
+    /**
+     * The Claim to use for the subject username to insert into the SAML Token. It defaults to 
+     * "email".
+     */
+    public static final String SUBJECT_CLAIM = "subject.claim";
+    
+    public static final String PROTOCOL = "facebook-connect";
+
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpFacebookProtocolHandler.class);
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+
+    @Override
+    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+
+        String code = (String) WebUtils.getAttributeFromFlowScope(context,
+                                                                  OAuthConstants.CODE_RESPONSE_TYPE);
+        if (code != null && !code.isEmpty()) {
+            
+            String tokenEndpoint = getProperty(trustedIdp, TOKEN_ENDPOINT);
+            if (tokenEndpoint == null || tokenEndpoint.isEmpty()) {
+                tokenEndpoint = "https://graph.facebook.com/v2.6/oauth/access_token";
+            }
+            
+            String apiEndpoint = getProperty(trustedIdp, API_ENDPOINT);
+            if (apiEndpoint == null || apiEndpoint.isEmpty()) {
+                apiEndpoint = "https://graph.facebook.com/v2.6";
+            }
+            
+            String clientId = getProperty(trustedIdp, CLIENT_ID);
+            String clientSecret = getProperty(trustedIdp, CLIENT_SECRET);
+            if (clientSecret == null || clientSecret.isEmpty()) {
+                LOG.warn("A CLIENT_SECRET must be configured to use the TrustedIdpFacebookProtocolHandler");
+                throw new IllegalStateException("No CLIENT_SECRET specified");
+            }
+            
+            // Here we need to get the AccessToken using the authorization code
+            ClientAccessToken accessToken = getAccessTokenUsingCode(tokenEndpoint, code, clientId,
+                                                                    clientSecret, idp.getIdpUrl().toString());
+            if (accessToken == null || accessToken.getTokenKey() == null) {
+                LOG.warn("No Access Token received from the Facebook IdP");
+                return null;
+            }
+            
+            // Now we need to invoke on the API endpoint using the access token to get the 
+            // user's claims
+            String subjectName = getSubjectName(apiEndpoint, accessToken.getTokenKey(), trustedIdp);
+            try {
+                String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
+                if (whr == null) {
+                    LOG.warn("Home realm is null");
+                    throw new IllegalStateException("Home realm is null");
+                }
+        
+                // Convert into a SAML Token
+                Date expires = new Date();
+                expires.setTime(expires.getTime() + (accessToken.getExpiresIn() * 1000L));
+                SecurityToken idpToken = new SecurityToken(IDGenerator.generateID(null), null, expires);
+                SamlAssertionWrapper assertion = 
+                    createSamlAssertion(idp, trustedIdp, subjectName, null, expires);
+                Document doc = DOMUtils.createDocument();
+                Element token = assertion.toDOM(doc);
+        
+                // Create new Security token with new id. 
+                // Parameters for freshness computation are copied from original IDP_TOKEN
+                idpToken.setToken(token);
+        
+                LOG.info("[IDP_TOKEN={}] for user '{}' issued by home realm [{}]",
+                         assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(), 
+                         whr);
+                LOG.debug("Expired date={}", expires);
+                
+                return idpToken;
+            } catch (IllegalStateException ex) {
+                throw ex;
+            } catch (Exception ex) {
+                LOG.warn("Unexpected exception occured", ex);
+                throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
+            }
+        }
+        return null;
+    }
+    
+    private ClientAccessToken getAccessTokenUsingCode(String tokenEndpoint, String code, String clientId,
+                                                      String clientSecret, String redirectURI) {
+        // Here we need to get the AccessToken using the authorization code
+        List<Object> providers = new ArrayList<Object>();
+        providers.add(new OAuthJSONProvider());
+        
+        WebClient client = 
+            WebClient.create(tokenEndpoint, providers, "cxf-tls.xml");
+        
+        ClientConfiguration config = WebClient.getConfig(client);
+
+        if (LOG.isDebugEnabled()) {
+            config.getOutInterceptors().add(new LoggingOutInterceptor());
+            config.getInInterceptors().add(new LoggingInInterceptor());
+        }
+        
+        client.type("application/x-www-form-urlencoded");
+        client.accept("application/json");
+
+        Form form = new Form();
+        form.param("grant_type", "authorization_code");
+        form.param("code", code);
+        form.param("client_id", clientId);
+        form.param("redirect_uri", redirectURI);
+        form.param("client_secret", clientSecret);
+        Response response = client.post(form);
+
+        return response.readEntity(ClientAccessToken.class);
+    }
+    
+    private String getSubjectName(String apiEndpoint, String accessToken, TrustedIdp trustedIdp) {
+        WebClient client = WebClient.create(apiEndpoint, 
+                                  Collections.singletonList(new JsonMapObjectProvider()), 
+                                  "cxf-tls.xml");
+        client.path("/me");
+        ClientConfiguration config = WebClient.getConfig(client);
+
+        if (LOG.isDebugEnabled()) {
+            config.getOutInterceptors().add(new LoggingOutInterceptor());
+            config.getInInterceptors().add(new LoggingInInterceptor());
+        }
+
+        client.accept("application/json");
+        client.query("access_token", accessToken);
+        
+        String subjectName = getProperty(trustedIdp, SUBJECT_CLAIM);
+        if (subjectName == null || subjectName.isEmpty()) {
+            subjectName = "email";
+        }
+        client.query("fields", subjectName);
+        JsonMapObject mapObject = client.get(JsonMapObject.class);
+        
+        String parsedSubjectName = (String)mapObject.getProperty(subjectName);
+        if (subjectName.contains("email")) {
+            parsedSubjectName = parsedSubjectName.replace("\\u0040", "@");
+        }
+        return parsedSubjectName;
+    }
+    
+    protected String getScope(TrustedIdp trustedIdp) {
+        String scope = getProperty(trustedIdp, SCOPE);
+        if (scope != null) {
+            scope = scope.trim();
+        }
+        
+        if (scope == null || scope.isEmpty()) {
+            scope = "email";
+        }
+        return scope;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
new file mode 100644
index 0000000..b45c763
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpOIDCProtocolHandler.java
@@ -0,0 +1,335 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import java.io.IOException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.Response;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.core.util.DOMUtils;
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.interceptor.LoggingInInterceptor;
+import org.apache.cxf.interceptor.LoggingOutInterceptor;
+import org.apache.cxf.jaxrs.client.ClientConfiguration;
+import org.apache.cxf.jaxrs.client.WebClient;
+import org.apache.cxf.rs.security.jose.common.JoseConstants;
+import org.apache.cxf.rs.security.jose.jaxrs.JsonWebKeysProvider;
+import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm;
+import org.apache.cxf.rs.security.jose.jwk.JsonWebKey;
+import org.apache.cxf.rs.security.jose.jwk.JsonWebKeys;
+import org.apache.cxf.rs.security.jose.jws.JwsJwtCompactConsumer;
+import org.apache.cxf.rs.security.jose.jwt.JwtConstants;
+import org.apache.cxf.rs.security.jose.jwt.JwtToken;
+import org.apache.cxf.rs.security.jose.jwt.JwtUtils;
+import org.apache.cxf.rs.security.oauth2.common.ClientAccessToken;
+import org.apache.cxf.rs.security.oauth2.provider.OAuthJSONProvider;
+import org.apache.cxf.rs.security.oauth2.utils.OAuthConstants;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.common.saml.SamlAssertionWrapper;
+import org.apache.xml.security.exceptions.Base64DecodingException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Extension of AbstractTrustedIdpOAuth2ProtocolHandler for OpenId Connect.
+ * Default values:
+ *  - scope: openid
+ */
+@Component
+public class TrustedIdpOIDCProtocolHandler extends AbstractTrustedIdpOAuth2ProtocolHandler {
+    
+    /**
+     * The signature algorithm to use in verifying the IdToken. The default is "RS256".
+     */
+    public static final String SIGNATURE_ALGORITHM = "signature.algorithm";
+    
+    /**
+     * The Claim in which to extract the Subject username to insert into the generated SAML token. 
+     * It defaults to "preferred_username", otherwise it falls back to the "sub" claim.
+     */
+    public static final String SUBJECT_CLAIM = "subject.claim";
+    
+    /**
+     * Additional (space-separated) parameters to be sent in the "scope" to the authorization endpoint.
+     * Fediz will automatically use "openid" for this value. 
+     */
+    public static final String SCOPE = "scope";
+    
+    /**
+     * The URI from which to retrieve the JSON Web Keys to validate the signed IdToken.
+     */
+    public static final String JWKS_URI = "jwks.uri";
+    
+    public static final String PROTOCOL = "openid-connect-1.0";
+
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpOIDCProtocolHandler.class);
+
+    @Override
+    public String getProtocol() {
+        return PROTOCOL;
+    }
+
+    @Override
+    public SecurityToken mapSignInResponse(RequestContext context, Idp idp, TrustedIdp trustedIdp) {
+
+        String code = (String) WebUtils.getAttributeFromFlowScope(context,
+                                                                  OAuthConstants.CODE_RESPONSE_TYPE);
+        if (code != null && !code.isEmpty()) {
+            
+            String tokenEndpoint = getProperty(trustedIdp, TOKEN_ENDPOINT);
+            if (tokenEndpoint == null || tokenEndpoint.isEmpty()) {
+                LOG.warn("A TOKEN_ENDPOINT must be configured to use the OIDCProtocolHandler");
+                throw new IllegalStateException("No TOKEN_ENDPOINT specified");
+            }
+            
+            String clientId = getProperty(trustedIdp, CLIENT_ID);
+            String clientSecret = getProperty(trustedIdp, CLIENT_SECRET);
+            if (clientSecret == null || clientSecret.isEmpty()) {
+                LOG.warn("A CLIENT_SECRET must be configured to use the OIDCProtocolHandler");
+                throw new IllegalStateException("No CLIENT_SECRET specified");
+            }
+            
+            // Here we need to get the IdToken using the authorization code
+            List<Object> providers = new ArrayList<Object>();
+            providers.add(new OAuthJSONProvider());
+            
+            WebClient client = 
+                WebClient.create(tokenEndpoint, providers, clientId, clientSecret, "cxf-tls.xml");
+            
+            ClientConfiguration config = WebClient.getConfig(client);
+
+            if (LOG.isDebugEnabled()) {
+                config.getOutInterceptors().add(new LoggingOutInterceptor());
+                config.getInInterceptors().add(new LoggingInInterceptor());
+            }
+            
+            client.type("application/x-www-form-urlencoded").accept("application/json");
+
+            Form form = new Form();
+            form.param("grant_type", "authorization_code");
+            form.param("code", code);
+            form.param("client_id", clientId);
+            form.param("redirect_uri", idp.getIdpUrl().toString());
+            Response response = client.post(form);
+
+            ClientAccessToken accessToken = response.readEntity(ClientAccessToken.class);
+            String idToken = accessToken.getParameters().get("id_token");
+            if (idToken == null) {
+                LOG.warn("No IdToken received from the OIDC IdP");
+                return null;
+            }
+            
+            client.close();
+            
+            try {
+                String whr = (String) WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
+                if (whr == null) {
+                    LOG.warn("Home realm is null");
+                    throw new IllegalStateException("Home realm is null");
+                }
+        
+                // Parse the received Token
+                JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(idToken);
+                JwtToken jwt = jwtConsumer.getJwtToken();
+                
+                if (jwt != null && jwt.getClaims() != null && LOG.isDebugEnabled()) {
+                    LOG.debug("Received Claims:");
+                    for (Map.Entry<String, Object> claim : jwt.getClaims().asMap().entrySet()) {
+                        LOG.debug(claim.getKey() + ": " + claim.getValue());
+                    }
+                }
+                
+                if (jwt != null && jwt.getJwsHeaders() != null && LOG.isDebugEnabled()) {
+                    LOG.debug("Received JWS Headers:");
+                    for (Map.Entry<String, Object> header : jwt.getJwsHeaders().asMap().entrySet()) {
+                        LOG.debug(header.getKey() + ": " + header.getValue());
+                    }
+                }
+                
+                if (!validateSignature(trustedIdp, jwtConsumer)) {
+                    LOG.warn("Signature does not validate");
+                    return null;
+                }
+                
+                // Make sure the received token is valid according to the spec
+                validateToken(jwt, clientId);
+                
+                Date created = new Date((long)jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT) * 1000L);
+                Date notBefore = null;
+                if (jwt.getClaim(JwtConstants.CLAIM_NOT_BEFORE) != null) {
+                    notBefore = new Date((long)jwt.getClaim(JwtConstants.CLAIM_NOT_BEFORE) * 1000L);
+                } 
+                
+                Date expires = new Date((long)jwt.getClaim(JwtConstants.CLAIM_EXPIRY) * 1000L);
+                
+                // Subject
+                String subjectName = getProperty(trustedIdp, SUBJECT_CLAIM);
+                LOG.debug("Trying to extract subject name using the claim name {}", subjectName);
+                if (subjectName == null || jwt.getClaim(subjectName) == null) {
+                    LOG.debug("No claim available in the token for {}", subjectName);
+                    subjectName = "preferred_username";
+                    LOG.debug("Falling back to use subject claim name {}", subjectName);
+                    if (subjectName == null || jwt.getClaim(subjectName) == null) {
+                        subjectName = JwtConstants.CLAIM_SUBJECT;
+                        LOG.debug("No claim available in the token for preferred_username. "
+                                  + "Falling back to use {}", subjectName);
+                    }
+                }
+                
+                // Convert into a SAML Token
+                SamlAssertionWrapper assertion = 
+                    createSamlAssertion(idp, trustedIdp, (String)jwt.getClaim(subjectName), notBefore, expires);
+                Document doc = DOMUtils.createDocument();
+                Element token = assertion.toDOM(doc);
+        
+                // Create new Security token with new id. 
+                // Parameters for freshness computation are copied from original IDP_TOKEN
+                SecurityToken idpToken = new SecurityToken(assertion.getId(), created, expires);
+                idpToken.setToken(token);
+        
+                LOG.info("[IDP_TOKEN={}] for user '{}' created from [RP_TOKEN={}] issued by home realm [{}/{}]",
+                         assertion.getId(), assertion.getSaml2().getSubject().getNameID().getValue(), 
+                         jwt.getClaim(JwtConstants.CLAIM_JWT_ID), whr, jwt.getClaim(JwtConstants.CLAIM_ISSUER));
+                LOG.debug("Created date={}", created);
+                LOG.debug("Expired date={}", expires);
+                
+                return idpToken;
+            } catch (IllegalStateException ex) {
+                throw ex;
+            } catch (Exception ex) {
+                LOG.warn("Unexpected exception occured", ex);
+                throw new IllegalStateException("Unexpected exception occured: " + ex.getMessage());
+            }
+        }
+        return null;
+    }
+    
+    protected void validateToken(JwtToken jwt, String clientId) {
+        // We must have the following claims
+        if (jwt.getClaim(JwtConstants.CLAIM_ISSUER) == null
+            || jwt.getClaim(JwtConstants.CLAIM_SUBJECT) == null
+            || jwt.getClaim(JwtConstants.CLAIM_AUDIENCE) == null
+            || jwt.getClaim(JwtConstants.CLAIM_EXPIRY) == null
+            || jwt.getClaim(JwtConstants.CLAIM_ISSUED_AT) == null) {
+            LOG.warn("The IdToken is missing a required claim");
+            throw new IllegalStateException("The IdToken is missing a required claim");
+        }
+        
+        // The audience must match the client_id of this client
+        boolean match = false;
+        for (String audience : jwt.getClaims().getAudiences()) {
+            if (clientId.equals(audience)) {
+                match = true;
+                break;
+            }
+        }
+        if (!match) {
+            LOG.warn("The audience of the token does not match this client");
+            throw new IllegalStateException("The audience of the token does not match this client");
+        }
+        
+        JwtUtils.validateTokenClaims(jwt.getClaims(), 300, 0, false);
+    }
+    
+    private boolean validateSignature(TrustedIdp trustedIdp, JwsJwtCompactConsumer jwtConsumer) 
+        throws CertificateException, WSSecurityException, Base64DecodingException, 
+            ProcessingException, IOException {
+        
+        // Validate the Signature
+        String sigAlgo = getProperty(trustedIdp, SIGNATURE_ALGORITHM);
+        if (sigAlgo == null || sigAlgo.isEmpty()) {
+            sigAlgo = "RS256";
+        }
+        
+        JwtToken jwt = jwtConsumer.getJwtToken();
+        String jwksUri = getProperty(trustedIdp, JWKS_URI);
+        JsonWebKey verifyingKey = null;
+        
+        if (jwksUri != null && jwt.getJwsHeaders() != null 
+            && jwt.getJwsHeaders().containsHeader(JoseConstants.HEADER_KEY_ID)) {
+            String kid = (String)jwt.getJwsHeaders().getHeader(JoseConstants.HEADER_KEY_ID);
+            LOG.debug("Attemping to retrieve key id {} from uri {}", kid, jwksUri);
+            List<Object> jsonKeyProviders = new ArrayList<Object>();
+            jsonKeyProviders.add(new JsonWebKeysProvider());
+            
+            WebClient client = 
+                WebClient.create(jwksUri, jsonKeyProviders, "cxf-tls.xml");
+            client.accept("application/json");
+            
+            ClientConfiguration config = WebClient.getConfig(client);
+            if (LOG.isDebugEnabled()) {
+                config.getOutInterceptors().add(new LoggingOutInterceptor());
+                config.getInInterceptors().add(new LoggingInInterceptor());
+            }
+            
+            Response response = client.get();
+            JsonWebKeys jsonWebKeys = response.readEntity(JsonWebKeys.class);
+            if (jsonWebKeys != null) {
+                verifyingKey = jsonWebKeys.getKey(kid);
+            }
+        }
+        
+        if (verifyingKey != null) {
+            return jwtConsumer.verifySignatureWith(verifyingKey, SignatureAlgorithm.getAlgorithm(sigAlgo));
+        }
+        
+        X509Certificate validatingCert = CertsUtils.parseX509Certificate(trustedIdp.getCertificate());
+        if (validatingCert != null) {
+            return jwtConsumer.verifySignatureWith(validatingCert, SignatureAlgorithm.getAlgorithm(sigAlgo));
+        }
+        
+        LOG.warn("No key supplied to verify the signature of the IdToken");
+        return false;
+    }
+    
+    protected String getScope(TrustedIdp trustedIdp) {
+        String scope = getProperty(trustedIdp, SCOPE);
+        if (scope != null) {
+            scope = scope.trim();
+            if (!scope.contains("openid")) {
+                scope = "openid " + scope;
+            }
+        }
+        
+        if (scope == null || scope.isEmpty()) {
+            scope = "openid";
+        }
+        return scope;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
new file mode 100644
index 0000000..31bc572
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/protocols/TrustedIdpProtocolControllerImpl.java
@@ -0,0 +1,60 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.protocols;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+@Component
+public class TrustedIdpProtocolControllerImpl implements ProtocolController<TrustedIdpProtocolHandler> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpProtocolControllerImpl.class);
+    
+    @Autowired
+    private List<TrustedIdpProtocolHandler> protocolHandlers;
+    
+    @Override
+    public TrustedIdpProtocolHandler getProtocolHandler(String protocol) {
+        for (TrustedIdpProtocolHandler protocolHandler : protocolHandlers) {
+            if (protocolHandler.getProtocol().equals(protocol)) {
+                return protocolHandler;
+            }
+        }
+        LOG.warn("No protocol handler found for {}", protocol);
+        return null;
+    }
+    
+    @Override
+    public List<String> getProtocols() {
+        List<String> protocols = new ArrayList<>();
+        for (TrustedIdpProtocolHandler protocolHandler : protocolHandlers) {
+            protocols.add(protocolHandler.getProtocol());
+        }
+        return Collections.unmodifiableList(protocols);
+    }
+
+}


[07/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/IdpTokenExpiredAction.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/IdpTokenExpiredAction.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/IdpTokenExpiredAction.java
deleted file mode 100644
index cbe4ee8..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/IdpTokenExpiredAction.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Check to see whether the IdP Token is expired or not
- */
-@Component
-public class IdpTokenExpiredAction {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(IdpTokenExpiredAction.class);
-    private boolean tokenExpirationValidation = true;
-
-    public boolean isTokenExpired(String homeRealm, RequestContext context)
-        throws Exception {
-        
-        SecurityToken idpToken = 
-            (SecurityToken) WebUtils.getAttributeFromExternalContext(context, homeRealm);
-        if (idpToken == null) {
-            return true;
-        }
-        
-        if (tokenExpirationValidation && idpToken.isExpired()) {
-            LOG.info("[IDP_TOKEN=" + idpToken.getId() + "] is expired.");
-            return true;
-        }
-
-        return false;
-    }
-
-    public boolean isTokenExpirationValidation() {
-        return tokenExpirationValidation;
-    }
-
-    /**
-     * Set whether the token validation (e.g. lifetime) shall be performed on every request (true) or only 
-     * once at initial authentication (false). The default is "true" (note that the plugins default for this
-     * configuration option is "true").
-     * @param tokenExpirationValidation Whether to perform token expiration validation per request
-     */
-    public void setTokenExpirationValidation(boolean tokenExpirationValidation) {
-        this.tokenExpirationValidation = tokenExpirationValidation;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/LogoutAction.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/LogoutAction.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/LogoutAction.java
deleted file mode 100644
index ae90757..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/LogoutAction.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import javax.servlet.http.HttpSession;
-
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * This class is responsible to clear security context and invalidate the IDP session.
- */
-@Component
-public class LogoutAction {
-
-    private static final Logger LOG = LoggerFactory.getLogger(LogoutAction.class);
-
-    public void submit(RequestContext requestContext) {
-        SecurityContextHolder.clearContext();
-        LOG.info("Security context has been cleared.");
-        HttpSession session = WebUtils.getHttpSession(requestContext);
-        session.invalidate();
-        LOG.info("Session " + session.getId() + " has been invalidated.");
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/PassiveRequestorValidator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/PassiveRequestorValidator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/PassiveRequestorValidator.java
deleted file mode 100644
index 3f5be36..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/PassiveRequestorValidator.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import java.util.regex.Matcher;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * This class is responsible to validate the 'wreply' parameter for WS-Federation, or else the
- * AssertionConsumer URL address for SAML SSO, by comparing it to a regular expression.
- */
-@Component
-public class PassiveRequestorValidator {
-
-    private static final Logger LOG = LoggerFactory.getLogger(PassiveRequestorValidator.class);
-
-    public boolean isValid(RequestContext context, String endpointAddress, String realm)
-        throws Exception {
-        if (endpointAddress == null) {
-            return true;
-        }
-        
-        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, "idpConfig");
-        Application serviceConfig = idpConfig.findApplication(realm);
-        if (serviceConfig == null) {
-            LOG.warn("No service config found for " + realm);
-            return false;
-        }
-        
-        if (serviceConfig.getPassiveRequestorEndpoint() == null 
-            && serviceConfig.getCompiledPassiveRequestorEndpointConstraint() == null) {
-            LOG.error("Either the 'passiveRequestorEndpoint' or the 'passiveRequestorEndpointConstraint' "
-                + "configuration values must be specified for the application");
-        } else if (serviceConfig.getPassiveRequestorEndpoint() != null 
-            && serviceConfig.getPassiveRequestorEndpoint().equals(endpointAddress)) {
-            LOG.debug("The supplied endpoint address {} matches the configured passive requestor endpoint value", 
-                      endpointAddress);
-            return true;
-        } else if (serviceConfig.getCompiledPassiveRequestorEndpointConstraint() != null) {
-            Matcher matcher = 
-                serviceConfig.getCompiledPassiveRequestorEndpointConstraint().matcher(endpointAddress);
-            if (matcher.matches()) {
-                return true;
-            } else {
-                LOG.error("The endpointAddress value of {} does not match any of the passive requestor values",
-                          endpointAddress);
-            }
-        }
-        
-        return false;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/ProcessHRDSExpressionAction.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/ProcessHRDSExpressionAction.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/ProcessHRDSExpressionAction.java
deleted file mode 100644
index 351f88c..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/ProcessHRDSExpressionAction.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import javax.servlet.http.Cookie;
-
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.expression.Expression;
-import org.springframework.expression.ExpressionParser;
-import org.springframework.expression.spel.standard.SpelExpressionParser;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * This class is responsible to process Home Realm Discovery Service Expression.
- */
-@Component
-public class ProcessHRDSExpressionAction {
-
-    private static final String IDP_CONFIG = "idpConfig";
-
-    private static final Logger LOG = LoggerFactory.getLogger(ProcessHRDSExpressionAction.class);
-
-    @Autowired
-    private HomeRealmReminder homeRealmReminder;
-
-    public String submit(RequestContext context, String homeRealm) {
-        // Check if home realm is known already
-        Cookie homeRealmCookie = homeRealmReminder.readCookie(context);
-        if (homeRealmCookie != null) {
-            LOG.debug("Home Realm Cookie set: {}", homeRealmCookie);
-            return homeRealmCookie.getValue();
-        }
-
-        // Check if custom HRDS is defined
-        Idp idpConfig = (Idp)WebUtils.getAttributeFromFlowScope(context, IDP_CONFIG);
-        String hrds = idpConfig.getHrds();
-
-        if (hrds != null) {
-            LOG.debug("HomeRealmDiscoveryService EL: {}", hrds);
-            ExpressionParser parser = new SpelExpressionParser();
-            Expression exp = parser.parseExpression(hrds);
-            String result = exp.getValue(context, String.class);
-            LOG.info("Realm resolved by HomeRealmDiscoveryService: {}", result);
-            return result;
-        }
-
-        // Return home realm parameter unchanged
-        LOG.debug("No custom homeRealm handling, using home realm parameter as provided in request: {}", homeRealm);
-        return homeRealm;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/STSClientAction.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/STSClientAction.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/STSClientAction.java
deleted file mode 100644
index 0d6c37d..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/STSClientAction.java
+++ /dev/null
@@ -1,439 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import java.io.IOException;
-import java.io.StringReader;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.security.cert.X509Certificate;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.xml.namespace.QName;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.XMLStreamException;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.apache.cxf.Bus;
-import org.apache.cxf.BusFactory;
-import org.apache.cxf.binding.soap.SoapFault;
-import org.apache.cxf.fediz.core.FederationConstants;
-import org.apache.cxf.fediz.core.exception.ProcessingException;
-import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
-import org.apache.cxf.fediz.core.util.DOMUtils;
-import org.apache.cxf.fediz.service.idp.IdpSTSClient;
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.staxutils.W3CDOMStreamWriter;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.cxf.ws.security.trust.STSClient;
-import org.apache.cxf.ws.security.trust.STSUtils;
-import org.apache.wss4j.dom.WSConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * This class is responsible to ask for Security Tokens to STS.
- */
-
-public class STSClientAction {
-
-    private static final String HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY = 
-            "http://schemas.xmlsoap.org/ws/2005/05/identity";
-
-    private static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER = 
-            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
-    
-    private static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_PUBLICKEY = 
-            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey";
-
-    private static final String HTTP_WWW_W3_ORG_2005_08_ADDRESSING = "http://www.w3.org/2005/08/addressing";
-
-    private static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512 = 
-            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/";
-    
-    private static final String HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST =
-        "http://schemas.xmlsoap.org/ws/2005/02/trust";
-
-    private static final String SECURITY_TOKEN_SERVICE = "SecurityTokenService";
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(STSClientAction.class);
-    
-    protected String namespace = HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512;
-
-    protected String wsdlLocation;
-
-    protected String wsdlEndpoint;
-    
-    protected String wsdlService = SECURITY_TOKEN_SERVICE;
-  
-    protected String tokenType = WSConstants.WSS_SAML2_TOKEN_TYPE;
-    
-    protected Map<String, Object> properties;
-    
-    protected boolean use200502Namespace;
-    
-    protected int ttl = 1800;
-    
-    protected Bus bus;
-    
-    private boolean isPortSet;
-    
-    private String keyType = HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER;
-
-
-    public String getWsdlLocation() {
-        return wsdlLocation;
-    }
-
-    public void setWsdlLocation(String wsdlLocation) {
-        this.wsdlLocation = wsdlLocation;
-        try {
-            URL url = new URL(wsdlLocation);
-            isPortSet = url.getPort() > 0;
-            if (!isPortSet) {
-                LOG.info("Port is 0 for 'wsdlLocation'. Port evaluated when processing first request.");
-            }
-        } catch (MalformedURLException e) {
-            LOG.error("Invalid Url '" + wsdlLocation + "': "  + e.getMessage());
-        }
-    }
-
-    public String getWsdlEndpoint() {
-        return wsdlEndpoint;
-    }
-
-    public void setWsdlEndpoint(String wsdlEndpoint) {
-        this.wsdlEndpoint = wsdlEndpoint;
-    }
-    
-    public String getWsdlService() {
-        return wsdlService;
-    }
-
-    public void setWsdlService(String wsdlService) {
-        this.wsdlService = wsdlService;
-    }
-    
-    public String getNamespace() {
-        return namespace;
-    }
-
-    public void setNamespace(String namespace) {
-        this.namespace = namespace;
-    }
-    
-    public void setBus(Bus bus) {
-        this.bus = bus;
-    }
-
-    public Bus getBus() {
-        // do not store a referance to the default bus
-        return (bus != null) ? bus : BusFactory.getDefaultBus();
-    }
-
-    public String getTokenType() {
-        return tokenType;
-    }
-
-    public void setTokenType(String tokenType) {
-        this.tokenType = tokenType;
-    }
-
-    public int getTtl() {
-        return ttl;
-    }
-
-    public void setTtl(int ttl) {
-        this.ttl = ttl;
-    }
-    
-    /**
-     * @param context the webflow request context
-     * @param realm The client/application realm
-     * @return a RP security token
-     * @throws Exception
-     */
-    public Element submit(RequestContext context, String realm, String homeRealm)
-        throws Exception {
-        
-        SecurityToken idpToken = getSecurityToken(context, homeRealm);
-
-        Bus cxfBus = getBus();
-        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, "idpConfig");
-
-        IdpSTSClient sts = new IdpSTSClient(cxfBus);
-        sts.setAddressingNamespace(HTTP_WWW_W3_ORG_2005_08_ADDRESSING);
-        
-        Application serviceConfig = idpConfig.findApplication(realm);
-        if (serviceConfig == null) {
-            LOG.warn("No service config found for " + realm);
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-        
-        // Parse wreq parameter - we only support parsing TokenType and KeyType for now
-        String wreq = (String)WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_REQUEST);
-        String stsTokenType = null;
-        String stsKeyType = keyType;
-        if (wreq != null) {
-            try {
-                Document wreqDoc = DOMUtils.readXml(new StringReader(wreq));
-                Element wreqElement = wreqDoc.getDocumentElement();
-                if (wreqElement != null && "RequestSecurityToken".equals(wreqElement.getLocalName())
-                    && (STSUtils.WST_NS_05_12.equals(wreqElement.getNamespaceURI())
-                        || HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST.equals(wreqElement.getNamespaceURI()))) {
-                    Element tokenTypeElement = 
-                        DOMUtils.getFirstChildWithName(wreqElement, wreqElement.getNamespaceURI(), "TokenType");
-                    if (tokenTypeElement != null) {
-                        stsTokenType = tokenTypeElement.getTextContent();
-                    }
-                    Element keyTypeElement = 
-                        DOMUtils.getFirstChildWithName(wreqElement, wreqElement.getNamespaceURI(), "KeyType");
-                    if (keyTypeElement != null) {
-                        stsKeyType = keyTypeElement.getTextContent();
-                    }
-                }
-            } catch (Exception e) {
-                LOG.warn("Error parsing 'wreq' parameter: " + e.getMessage());
-                throw new ProcessingException(TYPE.BAD_REQUEST);
-            }
-        }
-        
-        if (stsTokenType != null) {
-            sts.setTokenType(stsTokenType);
-        } else if (serviceConfig.getTokenType() != null && serviceConfig.getTokenType().length() > 0) {
-            sts.setTokenType(serviceConfig.getTokenType());
-        } else {
-            sts.setTokenType(getTokenType());
-        }
-        
-        if (serviceConfig.getPolicyNamespace() != null && serviceConfig.getPolicyNamespace().length() > 0) {
-            sts.setWspNamespace(serviceConfig.getPolicyNamespace());
-        }
-        
-        LOG.debug("TokenType {} set for realm {}", sts.getTokenType(), realm);
-        
-        sts.setKeyType(stsKeyType);
-        if (HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_PUBLICKEY.equals(stsKeyType)) {
-            HttpServletRequest servletRequest = WebUtils.getHttpServletRequest(context);
-            if (servletRequest != null) {
-                X509Certificate certs[] = 
-                    (X509Certificate[])servletRequest.getAttribute("javax.servlet.request.X509Certificate");
-                if (certs != null && certs.length > 0) {
-                    sts.setUseCertificateForConfirmationKeyInfo(true);
-                    sts.setUseKeyCertificate(certs[0]);
-                } else {
-                    LOG.info("Can't send a PublicKey KeyType as no client certs are available");
-                    sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
-                }
-            }
-        }
-
-        processWsdlLocation(context);
-        sts.setWsdlLocation(wsdlLocation);
-        sts.setServiceQName(new QName(namespace, wsdlService));
-        sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
-        if (use200502Namespace) {
-            sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
-        }
-
-        if (serviceConfig.getRequestedClaims() != null && serviceConfig.getRequestedClaims().size() > 0) {
-            addClaims(sts, serviceConfig.getRequestedClaims());
-            LOG.debug("Requested claims set for {}", realm);
-        }
-        
-        sts.setEnableLifetime(true);
-        setLifetime(sts, serviceConfig, realm);
-        
-        sts.setEnableAppliesTo(serviceConfig.isEnableAppliesTo());
-        
-        sts.setOnBehalfOf(idpToken.getToken());
-       
-        if (properties != null) {
-            sts.setProperties(properties);
-        }
-        
-        Element rpToken = null;
-        try {
-            rpToken = sts.requestSecurityTokenResponse(realm);
-        } catch (SoapFault ex) {
-            LOG.error("Error in retrieving a token", ex.getMessage());
-            if (ex.getFaultCode() != null 
-                && "RequestFailed".equals(ex.getFaultCode().getLocalPart())) {
-                throw new ProcessingException(TYPE.BAD_REQUEST);
-            }
-            throw ex;
-        }
-
-        if (LOG.isInfoEnabled()) {
-            String id = getIdFromToken(rpToken);
-            
-            LOG.info("[RP_TOKEN={}] successfully created for realm [{}] on behalf of [IDP_TOKEN={}]",
-                     id, realm, idpToken.getId());
-        }
-        return rpToken;
-    }
-    
-    private String getIdFromToken(Element token) throws IOException, XMLStreamException {
-        if (token != null) {
-            NodeList nd = token.getElementsByTagNameNS(WSConstants.SAML2_NS, "Assertion");
-            
-            String identifier = "ID";
-            if (nd.getLength() == 0) {
-                nd = token.getElementsByTagNameNS(WSConstants.SAML_NS, "Assertion");
-                identifier = "AssertionID";
-            }
-            
-            if (nd.getLength() > 0) {
-                Element e = (Element) nd.item(0);
-                if (e.hasAttributeNS(null, identifier)) {
-                    return e.getAttributeNS(null, identifier);
-                }
-            }
-        }
-        
-        return "";
-    }
-
-    private SecurityToken getSecurityToken(RequestContext context, String homeRealm) throws ProcessingException {
-
-        SecurityToken idpToken = (SecurityToken) WebUtils.getAttributeFromFlowScope(context, "idpToken");
-        if (idpToken != null) {
-            LOG.debug("[IDP_TOKEN={} successfully retrieved from cache for home realm [{}]",
-                          idpToken.getId(), homeRealm);
-        } else {
-            LOG.error("IDP_TOKEN not found");
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-        return idpToken;
-    }
-    
-
-    private void processWsdlLocation(RequestContext context) {
-        if (!isPortSet) {
-            try {
-                URL url = new URL(this.wsdlLocation);
-                URL updatedUrl = new URL(url.getProtocol(), url.getHost(),
-                                         WebUtils.getHttpServletRequest(context).getLocalPort(), url.getFile());
-                
-                setSTSWsdlUrl(updatedUrl.toString());
-                LOG.info("STS WSDL URL updated to {}", updatedUrl.toString());
-            } catch (MalformedURLException e) {
-                LOG.error("Invalid Url '{}': {}", this.wsdlLocation, e.getMessage());
-            }
-        }
-    }
-
-    private void addClaims(STSClient sts, List<RequestClaim> requestClaimList)
-        throws ParserConfigurationException, XMLStreamException {
-        
-        Element claims = createClaimsElement(requestClaimList);
-        if (claims != null) {
-            sts.setClaims(claims);
-        }
-    }
-
-    private Element createClaimsElement(List<RequestClaim> realmClaims)
-        throws ParserConfigurationException, XMLStreamException {
-        if (realmClaims == null || realmClaims.size() == 0) {
-            return null;
-        }
-
-        W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
-        writer.writeStartElement("wst", "Claims", STSUtils.WST_NS_05_12);
-        writer.writeNamespace("wst", STSUtils.WST_NS_05_12);
-        writer.writeNamespace("ic",
-                HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY);
-        writer.writeAttribute("Dialect",
-                HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY);
-
-        if (realmClaims.size() > 0) {
-            for (RequestClaim item : realmClaims) {
-                LOG.debug("  {}", item.getClaimType().toString());
-                writer.writeStartElement("ic", "ClaimType",
-                        HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY);
-                writer.writeAttribute("Uri", item.getClaimType().toString());
-                writer.writeAttribute("Optional", Boolean.toString(item.isOptional())); 
-                writer.writeEndElement();
-            }
-        }
-
-        writer.writeEndElement();
-
-        return writer.getDocument().getDocumentElement();
-    }
-    
-    private synchronized void setSTSWsdlUrl(String wsdlUrl) {
-        this.wsdlLocation = wsdlUrl;
-        this.isPortSet = true;
-    }
-
-    public String getKeyType() {
-        return keyType;
-    }
-
-    public void setKeyType(String keyType) {
-        this.keyType = keyType;
-    }
-
-    public boolean isUse200502Namespace() {
-        return use200502Namespace;
-    }
-
-    public void setUse200502Namespace(boolean use200502Namespace) {
-        this.use200502Namespace = use200502Namespace;
-    }
-
-    private void setLifetime(STSClient sts, Application serviceConfig, String wtrealm) {
-        if (serviceConfig.getLifeTime() > 0) {
-            try {
-                int lifetime = serviceConfig.getLifeTime();
-                sts.setTtl(lifetime);
-                sts.setEnableLifetime(lifetime > 0);
-                LOG.debug("Lifetime set to {} seconds for realm {}", serviceConfig.getLifeTime(), wtrealm);
-            } catch (NumberFormatException ex) {
-                LOG.warn("Invalid lifetime configured for service provider " + wtrealm);
-                sts.setTtl(this.ttl);
-                sts.setEnableLifetime(this.ttl > 0);
-            }
-        } else {
-            sts.setTtl(this.ttl);
-            sts.setEnableLifetime(this.ttl > 0);
-            if (LOG.isDebugEnabled()) {
-                LOG.debug("Lifetime set to {} seconds for realm {}", this.ttl, wtrealm);
-            }
-        }
-    }
-
-    public Map<String, Object> getProperties() {
-        return properties;
-    }
-
-    public void setProperties(Map<String, Object> properties) {
-        this.properties = properties;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/SigninParametersCacheAction.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/SigninParametersCacheAction.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/SigninParametersCacheAction.java
deleted file mode 100644
index bbecc5a..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/SigninParametersCacheAction.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import java.net.URL;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import org.apache.cxf.fediz.core.FederationConstants;
-import org.apache.cxf.fediz.core.exception.ProcessingException;
-import org.apache.cxf.fediz.service.idp.IdpConstants;
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.samlsso.SAMLAuthnRequest;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-@Component
-public class SigninParametersCacheAction {
-
-    public static final String ACTIVE_APPLICATIONS = "realmConfigMap";
-
-    private static final Logger LOG = LoggerFactory.getLogger(SigninParametersCacheAction.class);
-
-    public void store(RequestContext context, String protocol) {
-        Map<String, Object> signinParams = new HashMap<>();
-        String uuidKey = UUID.randomUUID().toString();
-
-        Object value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
-        if (value != null) {
-            signinParams.put(IdpConstants.HOME_REALM, value);
-        }
-        value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.CONTEXT);
-        if (value != null) {
-            signinParams.put(IdpConstants.CONTEXT, value);
-        }
-        value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.REALM);
-        if (value != null) {
-            signinParams.put(IdpConstants.REALM, value);
-        }
-        value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.RETURN_ADDRESS);
-        if (value != null) {
-            signinParams.put(IdpConstants.RETURN_ADDRESS, value);
-        }
-        value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.RETURN_ADDRESS);
-        if (value != null) {
-            signinParams.put(IdpConstants.RETURN_ADDRESS, value);
-        }
-
-        if ("samlsso".equals(protocol)) {
-            value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
-            if (value != null) {
-                signinParams.put(IdpConstants.SAML_AUTHN_REQUEST, value);
-            }
-        }
-
-        WebUtils.putAttributeInExternalContext(context, uuidKey, signinParams);
-
-        LOG.debug("SignIn parameters cached: {}", signinParams.toString());
-        WebUtils.putAttributeInFlowScope(context, IdpConstants.TRUSTED_IDP_CONTEXT, uuidKey);
-        LOG.info("SignIn parameters cached and context set to [" + uuidKey + "].");
-    }
-
-    public void restore(RequestContext context, String contextKey, String protocol) {
-
-        if (contextKey != null) {
-            @SuppressWarnings("unchecked")
-            Map<String, Object> signinParams =
-                (Map<String, Object>)WebUtils.getAttributeFromExternalContext(context, contextKey);
-
-            if (signinParams != null) {
-                LOG.debug("SignIn parameters restored: {}", signinParams.toString());
-
-                String value = (String)signinParams.get(IdpConstants.HOME_REALM);
-                if (value != null) {
-                    WebUtils.putAttributeInFlowScope(context, IdpConstants.HOME_REALM, value);
-                }
-                value = (String)signinParams.get(IdpConstants.REALM);
-                if (value != null) {
-                    WebUtils.putAttributeInFlowScope(context, IdpConstants.REALM, value);
-                }
-                value = (String)signinParams.get(IdpConstants.RETURN_ADDRESS);
-                if (value != null) {
-                    WebUtils.putAttributeInFlowScope(context, IdpConstants.RETURN_ADDRESS, value);
-                }
-                value = (String)signinParams.get(IdpConstants.CONTEXT);
-                if (value != null) {
-                    WebUtils.putAttributeInFlowScope(context, IdpConstants.CONTEXT, value);
-                }
-
-                if ("wsfed".equals(protocol)) {
-
-                    WebUtils.removeAttributeFromFlowScope(context, FederationConstants.PARAM_CONTEXT);
-                    LOG.info("SignIn parameters restored and " + FederationConstants.PARAM_CONTEXT + "["
-                        + contextKey + "] cleared.");
-
-                } else if ("samlsso".equals(protocol)) {
-                    SAMLAuthnRequest authnRequest =
-                        (SAMLAuthnRequest)signinParams.get(IdpConstants.SAML_AUTHN_REQUEST);
-                    if (authnRequest != null) {
-                        WebUtils.putAttributeInFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST, authnRequest);
-                    }
-                }
-
-            }  else {
-                LOG.debug("Error in restoring security context");
-            }
-
-            WebUtils.removeAttributeFromFlowScope(context, contextKey);
-        } else {
-            LOG.debug("Error in restoring security context");
-        }
-    }
-
-    public void storeRPConfigInSession(RequestContext context) throws ProcessingException {
-
-        String wtrealm = (String)WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_TREALM);
-        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, IdpConstants.IDP_CONFIG);
-        if (wtrealm == null || idpConfig == null) {
-            return;
-        }
-
-        Application serviceConfig = idpConfig.findApplication(wtrealm);
-        if (serviceConfig != null) {
-            if (serviceConfig.getPassiveRequestorEndpoint() == null) {
-                String url = guessPassiveRequestorURL(context, wtrealm);
-                serviceConfig.setPassiveRequestorEndpoint(url);
-            }
-
-            @SuppressWarnings("unchecked")
-            Map<String, Application> realmConfigMap =
-                    (Map<String, Application>)WebUtils
-                            .getAttributeFromExternalContext(context, ACTIVE_APPLICATIONS);
-
-            if (realmConfigMap == null) {
-                realmConfigMap = new HashMap<>();
-                WebUtils.putAttributeInExternalContext(context, ACTIVE_APPLICATIONS, realmConfigMap);
-            }
-
-            if (realmConfigMap.get(wtrealm) == null) {
-                realmConfigMap.put(wtrealm, serviceConfig);
-            }
-        }
-    }
-
-    protected String guessPassiveRequestorURL(RequestContext context, String wtrealm) throws ProcessingException {
-        String url = (String)WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_REPLY);
-        try {
-            //basic check if the url is correctly formed
-            new URL(url);
-        } catch (Exception e) {
-            url = null;
-        }
-        if (url == null) {
-            url = wtrealm;
-            try {
-                //basic check if the url is correctly formed
-                new URL(url);
-            } catch (Exception e) {
-                throw new ProcessingException(e.getMessage(), e, ProcessingException.TYPE.INVALID_REQUEST);
-            }
-        }
-        return url;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/TokenSerializer.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/TokenSerializer.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/TokenSerializer.java
deleted file mode 100644
index 4665cb5..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/TokenSerializer.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import java.io.StringWriter;
-
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-import org.w3c.dom.Element;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Serialize the RP Token
- */
-@Component
-public class TokenSerializer {
-
-    private static final Logger LOG = LoggerFactory.getLogger(TokenSerializer.class);
-
-    public String serialize(RequestContext context, Element rpToken) {
-        if (rpToken != null) {
-            StringWriter sw = new StringWriter();
-            try {
-                Transformer t = TransformerFactory.newInstance().newTransformer();
-                t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
-                t.transform(new DOMSource(rpToken), new StreamResult(sw));
-            } catch (TransformerException te) {
-                LOG.warn("nodeToString Transformer Exception");
-            }
-            String serializedToken = sw.toString();
-    
-            return org.apache.commons.lang3.StringEscapeUtils.escapeXml11(serializedToken);
-        }
-        
-        return null;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/TrustedIdpProtocolAction.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/TrustedIdpProtocolAction.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/TrustedIdpProtocolAction.java
deleted file mode 100644
index 9ea2de2..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/TrustedIdpProtocolAction.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans;
-
-import java.net.URL;
-
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.protocols.ProtocolController;
-import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Qualifier;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * This class is responsible to map the sign in request/response when calling a trusted third party IdP
- */
-@Component
-public class TrustedIdpProtocolAction {
-
-    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpProtocolAction.class);
-    
-    private static final String IDP_CONFIG = "idpConfig";
-    
-    @Autowired
-    // Qualifier workaround. See http://www.jayway.com/2013/11/03/spring-and-autowiring-of-generic-types/
-    @Qualifier("trustedIdpProtocolControllerImpl")
-    private ProtocolController<TrustedIdpProtocolHandler> trustedIdpProtocolHandlers;
-    
-    public String mapSignInRequest(RequestContext requestContext, String trustedIdpRealm) {
-        LOG.info("Prepare redirect to Trusted IDP '{}'", trustedIdpRealm);
-        
-        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(requestContext, IDP_CONFIG);
-        
-        TrustedIdp trustedIdp = idpConfig.findTrustedIdp(trustedIdpRealm);
-        if (trustedIdp == null) {
-            LOG.error("TrustedIdp '{}' not configured", trustedIdpRealm);
-            throw new IllegalStateException("TrustedIdp '" + trustedIdpRealm + "'");
-        }
-        
-        String protocol = trustedIdp.getProtocol();
-        LOG.debug("TrustedIdp '{}' supports protocol {}", trustedIdpRealm, protocol);
-        
-        TrustedIdpProtocolHandler protocolHandler = trustedIdpProtocolHandlers.getProtocolHandler(protocol);
-        if (protocolHandler == null) {
-            LOG.error("No ProtocolHandler found for {}", protocol);
-            throw new IllegalStateException("No ProtocolHandler found for '" + protocol + "'");
-        }
-        URL redirectUrl = protocolHandler.mapSignInRequest(requestContext, idpConfig, trustedIdp);
-        LOG.info("Redirect url {}", redirectUrl.toString());
-        return redirectUrl.toString();
-    }
-    
-    public SecurityToken mapSignInResponse(RequestContext requestContext, String trustedIdpRealm) {
-        LOG.info("Prepare validate SignInResponse of Trusted IDP '{}'", trustedIdpRealm);
-        
-        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(requestContext, IDP_CONFIG);
-        
-        TrustedIdp trustedIdp = idpConfig.findTrustedIdp(trustedIdpRealm);
-        if (trustedIdp == null) {
-            LOG.error("TrustedIdp '{}' not configured", trustedIdpRealm);
-            throw new IllegalStateException("TrustedIdp '" + trustedIdpRealm + "'");
-        }
-        
-        String protocol = trustedIdp.getProtocol();
-        LOG.debug("TrustedIdp '{}' supports protocol {}", trustedIdpRealm, protocol);
-        
-        TrustedIdpProtocolHandler protocolHandler = trustedIdpProtocolHandlers.getProtocolHandler(protocol);
-        if (protocolHandler == null) {
-            LOG.error("No ProtocolHandler found for {}", protocol);
-            throw new IllegalStateException("No ProtocolHandler found for '" + protocol + "'");
-        }
-        SecurityToken token = protocolHandler.mapSignInResponse(requestContext, idpConfig, trustedIdp);
-        if (token != null) {
-            LOG.info("SignInResponse successfully validated and SecurityToken created");
-        }
-        return token;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
deleted file mode 100644
index 53feb73..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
+++ /dev/null
@@ -1,388 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans.samlsso;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URLEncoder;
-import java.nio.charset.StandardCharsets;
-import java.security.cert.X509Certificate;
-import java.util.Collections;
-
-import org.w3c.dom.Document;
-
-import org.apache.cxf.common.util.Base64Utility;
-import org.apache.cxf.fediz.core.exception.ProcessingException;
-import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
-import org.apache.cxf.fediz.core.util.CertsUtils;
-import org.apache.cxf.fediz.service.idp.IdpConstants;
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.samlsso.SAMLAuthnRequest;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
-import org.apache.cxf.rs.security.saml.sso.SSOConstants;
-import org.apache.cxf.staxutils.StaxUtils;
-import org.apache.wss4j.common.crypto.CertificateStore;
-import org.apache.wss4j.common.crypto.Crypto;
-import org.apache.wss4j.common.ext.WSSecurityException;
-import org.apache.wss4j.common.saml.OpenSAMLUtil;
-import org.apache.wss4j.common.saml.SAMLKeyInfo;
-import org.apache.wss4j.common.saml.SAMLUtil;
-import org.apache.wss4j.common.util.DOM2Writer;
-import org.apache.wss4j.dom.WSDocInfo;
-import org.apache.wss4j.dom.engine.WSSConfig;
-import org.apache.wss4j.dom.handler.RequestData;
-import org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor;
-import org.apache.wss4j.dom.validate.Credential;
-import org.apache.wss4j.dom.validate.SignatureTrustValidator;
-import org.apache.wss4j.dom.validate.Validator;
-import org.apache.xml.security.utils.Base64;
-import org.opensaml.saml.saml2.core.AuthnRequest;
-import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator;
-import org.opensaml.security.credential.BasicCredential;
-import org.opensaml.security.x509.BasicX509Credential;
-import org.opensaml.xmlsec.signature.KeyInfo;
-import org.opensaml.xmlsec.signature.Signature;
-import org.opensaml.xmlsec.signature.support.SignatureException;
-import org.opensaml.xmlsec.signature.support.SignatureValidator;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Parse the received SAMLRequest into an OpenSAML AuthnRequest
- */
-@Component
-public class AuthnRequestParser {
-
-    private static final Logger LOG = LoggerFactory.getLogger(AuthnRequestParser.class);
-    private boolean supportDeflateEncoding;
-    private boolean requireSignature = true;
-
-    public void parseSAMLRequest(RequestContext context, Idp idp, String samlRequest,
-                                 String signature, String relayState) throws ProcessingException {
-        LOG.debug("Received SAML Request: {}", samlRequest);
-        
-        if (samlRequest == null) {
-            WebUtils.removeAttribute(context, IdpConstants.SAML_AUTHN_REQUEST);
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        } else {
-            AuthnRequest parsedRequest = null;
-            try {
-                parsedRequest = extractRequest(context, samlRequest);
-            } catch (Exception ex) {
-                LOG.warn("Error parsing request: {}", ex.getMessage());
-                throw new ProcessingException(TYPE.BAD_REQUEST);
-            }
-            
-            // Store various attributes from the AuthnRequest
-            SAMLAuthnRequest authnRequest = new SAMLAuthnRequest(parsedRequest);
-            WebUtils.putAttributeInFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST, authnRequest);
-            
-            validateSignature(context, parsedRequest, idp, signature, relayState, 
-                              samlRequest, authnRequest.getIssuer());
-            validateRequest(parsedRequest);
-            
-            LOG.debug("SAML Request with id '{}' successfully parsed", parsedRequest.getID());
-        }
-    }
-    
-    public String retrieveRealm(RequestContext context) {
-        SAMLAuthnRequest authnRequest = 
-            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
-        
-        if (authnRequest != null) {
-            String issuer = authnRequest.getIssuer();
-            LOG.debug("Parsed SAML AuthnRequest Issuer: {}", issuer);
-            return issuer;
-        }
-        
-        LOG.debug("No AuthnRequest available to be parsed");
-        return null;
-    }
-    
-    public String retrieveConsumerURL(RequestContext context) {
-        SAMLAuthnRequest authnRequest = 
-            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
-
-        if (authnRequest != null && authnRequest.getConsumerServiceURL() != null) {
-            String consumerURL = authnRequest.getConsumerServiceURL();
-            LOG.debug("Parsed SAML AuthnRequest Consumer URL: {}", consumerURL);
-            return consumerURL;
-        }
-        
-        LOG.debug("No AuthnRequest available to be parsed");
-        return null;
-    }
-    
-    public String retrieveRequestId(RequestContext context) {
-        SAMLAuthnRequest authnRequest = 
-            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
-
-        if (authnRequest != null && authnRequest.getRequestId() != null) {
-            String id = authnRequest.getRequestId();
-            LOG.debug("Parsed SAML AuthnRequest Id: {}", id);
-            return id;
-        }
-        
-        LOG.debug("No AuthnRequest available to be parsed");
-        return null;
-    }
-    
-    public String retrieveRequestIssuer(RequestContext context) {
-        SAMLAuthnRequest authnRequest = 
-            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
-
-        if (authnRequest != null && authnRequest.getIssuer() != null) {
-            String issuer = authnRequest.getIssuer();
-            LOG.debug("Parsed SAML AuthnRequest Issuer: {}", issuer);
-            return issuer;
-        }
-        
-        LOG.debug("No AuthnRequest available to be parsed");
-        return null;
-    }
-    
-    public boolean isForceAuthentication(RequestContext context) {
-        SAMLAuthnRequest authnRequest = 
-            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
-        if (authnRequest != null) {
-            return authnRequest.isForceAuthn();
-        }
-        
-        LOG.debug("No AuthnRequest available to be parsed");
-        return false;
-    }
-    
-    protected AuthnRequest extractRequest(RequestContext context, String samlRequest) throws Exception {
-        byte[] deflatedToken = Base64Utility.decode(samlRequest);
-        String httpMethod = WebUtils.getHttpServletRequest(context).getMethod();
-        
-        InputStream tokenStream = supportDeflateEncoding || "GET".equals(httpMethod)
-             ? new DeflateEncoderDecoder().inflateToken(deflatedToken)
-                 : new ByteArrayInputStream(deflatedToken);
-
-        Document responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, "UTF-8"));
-        AuthnRequest request = 
-            (AuthnRequest)OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
-        if (LOG.isDebugEnabled()) {
-            LOG.debug(DOM2Writer.nodeToString(responseDoc));
-        }
-        return request;
-    }
-    
-    public boolean isSupportDeflateEncoding() {
-        return supportDeflateEncoding;
-    }
-
-    public void setSupportDeflateEncoding(boolean supportDeflateEncoding) {
-        this.supportDeflateEncoding = supportDeflateEncoding;
-    }
-    
-    private void validateRequest(AuthnRequest parsedRequest) throws ProcessingException {
-        if (parsedRequest.getIssuer() == null) {
-            LOG.debug("No Issuer is present in the AuthnRequest");
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-        
-        String format = parsedRequest.getIssuer().getFormat();
-        if (format != null
-            && !"urn:oasis:names:tc:SAML:2.0:nameid-format:entity".equals(format)) {
-            LOG.debug("An invalid Format attribute was received: {}", format);
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-        
-        // No SubjectConfirmation Elements are allowed
-        if (parsedRequest.getSubject() != null 
-            && parsedRequest.getSubject().getSubjectConfirmations() != null
-            && !parsedRequest.getSubject().getSubjectConfirmations().isEmpty()) {
-            LOG.debug("An invalid SubjectConfirmation Element was received");
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-    }
-    
-    private void validateSignature(RequestContext context, AuthnRequest authnRequest, Idp idp, 
-                                   String signature, String relayState, String samlRequest, 
-                                   String realm) throws ProcessingException {
-        try {
-            if (authnRequest.isSigned()) {
-                // Check destination
-                checkDestination(context, authnRequest);
-                
-                // Check signature
-                X509Certificate validatingCert = getValidatingCertificate(idp, realm);
-                Crypto issuerCrypto = 
-                    new CertificateStore(Collections.singletonList(validatingCert).toArray(new X509Certificate[0]));
-                validateAuthnRequestSignature(authnRequest.getSignature(), issuerCrypto);
-            } else if (signature != null) {
-                // Check destination
-                checkDestination(context, authnRequest);
-                
-                // Check signature
-                X509Certificate validatingCert = getValidatingCertificate(idp, realm);
-                
-                java.security.Signature sig = java.security.Signature.getInstance("SHA1withRSA");
-                sig.initVerify(validatingCert);
-                
-                // Recreate request to sign
-                String requestToSign = SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(samlRequest, "UTF-8")
-                     + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG 
-                     + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, StandardCharsets.UTF_8.name());
-                
-                sig.update(requestToSign.getBytes(StandardCharsets.UTF_8));
-                
-                if (!sig.verify(Base64.decode(signature))) {
-                    LOG.debug("Signature validation failed");
-                    throw new ProcessingException(TYPE.BAD_REQUEST);
-                }
-            } else if (requireSignature) {
-                LOG.debug("No signature is present, therefore the request is rejected");
-                throw new ProcessingException(TYPE.BAD_REQUEST);
-            } else {
-                LOG.debug("No signature is present, but this is allowed by configuration");
-            }
-        } catch (Exception ex) {
-            LOG.debug("Error validating SAML Signature", ex);
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-    }
-    
-    private X509Certificate getValidatingCertificate(Idp idp, String realm) 
-        throws Exception {
-        Application serviceConfig = idp.findApplication(realm);
-        if (serviceConfig == null || serviceConfig.getValidatingCertificate() == null) {
-            LOG.debug("No validating certificate found for realm {}", realm);
-            throw new ProcessingException(TYPE.ISSUER_NOT_TRUSTED);
-        }
-        
-        return CertsUtils.parseX509Certificate(serviceConfig.getValidatingCertificate());
-    }
-    
-    private void checkDestination(RequestContext context, AuthnRequest authnRequest) throws ProcessingException {
-        // Check destination
-        String destination = authnRequest.getDestination();
-        LOG.debug("Validating destination: {}", destination);
-        
-        String localAddr = WebUtils.getHttpServletRequest(context).getRequestURL().toString();
-        if (destination == null || !localAddr.startsWith(destination)) {
-            LOG.debug("The destination {} does not match the local address {}", destination, localAddr);
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-    }
-    
-    /**
-     * Validate the AuthnRequest signature
-     */
-    private void validateAuthnRequestSignature(
-        Signature signature,
-        Crypto sigCrypto
-    ) throws WSSecurityException {
-        RequestData requestData = new RequestData();
-        requestData.setSigVerCrypto(sigCrypto);
-        WSSConfig wssConfig = WSSConfig.getNewInstance();
-        requestData.setWssConfig(wssConfig);
-        // requestData.setCallbackHandler(callbackHandler);
-
-        SAMLKeyInfo samlKeyInfo = null;
-
-        KeyInfo keyInfo = signature.getKeyInfo();
-        if (keyInfo != null) {
-            try {
-                Document doc = signature.getDOM().getOwnerDocument();
-                samlKeyInfo =
-                    SAMLUtil.getCredentialFromKeyInfo(
-                        keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(doc)), sigCrypto
-                    );
-            } catch (WSSecurityException ex) {
-                LOG.debug("Error in getting KeyInfo from SAML AuthnRequest: {}", ex.getMessage(), ex);
-                throw ex;
-            }
-        }
-        
-        if (samlKeyInfo == null) {
-            LOG.debug("No KeyInfo supplied in the AuthnRequest signature");
-            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
-        }
-
-        // Validate Signature against profiles
-        validateSignatureAgainstProfiles(signature, samlKeyInfo);
-
-        // Now verify trust on the signature
-        Credential trustCredential = new Credential();
-        trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
-        trustCredential.setCertificates(samlKeyInfo.getCerts());
-
-        try {
-            Validator signatureValidator = new SignatureTrustValidator();
-            signatureValidator.validate(trustCredential, requestData);
-        } catch (WSSecurityException e) {
-            LOG.debug("Error in validating signature on SAML AuthnRequest: {}", e.getMessage(), e);
-            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
-        }
-    }
-
-    /**
-     * Validate a signature against the profiles
-     */
-    private void validateSignatureAgainstProfiles(
-        Signature signature,
-        SAMLKeyInfo samlKeyInfo
-    ) throws WSSecurityException {
-        // Validate Signature against profiles
-        SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
-        try {
-            validator.validate(signature);
-        } catch (SignatureException ex) {
-            LOG.debug("Error in validating the SAML Signature: {}", ex.getMessage(), ex);
-            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
-        }
-
-        BasicCredential credential = null;
-        if (samlKeyInfo.getCerts() != null) {
-            credential = new BasicX509Credential(samlKeyInfo.getCerts()[0]);
-        } else if (samlKeyInfo.getPublicKey() != null) {
-            credential = new BasicCredential(samlKeyInfo.getPublicKey());
-        } else {
-            LOG.debug("Can't get X509Certificate or PublicKey to verify signature");
-            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
-        }
-        try {
-            SignatureValidator.validate(signature, credential);
-        } catch (SignatureException ex) {
-            LOG.debug("Error in validating the SAML Signature: {}", ex.getMessage(), ex);
-            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
-        }
-    }
-
-    public boolean isRequireSignature() {
-        return requireSignature;
-    }
-
-    /**
-     * Whether to require a signature or not on the AuthnRequest
-     * @param requireSignature
-     */
-    public void setRequireSignature(boolean requireSignature) {
-        this.requireSignature = requireSignature;
-    }
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/LocalRedirectCreator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/LocalRedirectCreator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/LocalRedirectCreator.java
deleted file mode 100644
index 9dfd626..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/LocalRedirectCreator.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans.samlsso;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Parse the parameters to create the URL for local redirection
- */
-@Component
-public class LocalRedirectCreator {
-
-    public String createRedirectURL(RequestContext context, Idp idp) throws UnsupportedEncodingException {
-        StringBuilder redirectURL = new StringBuilder();
-        redirectURL.append(idp.getIdpUrl().toString()).append("?");
-        
-        String relayState = (String)WebUtils.getAttributeFromFlowScope(context, "RelayState");
-        redirectURL.append("RelayState=").append(relayState).append("&");
-        String samlRequest = (String)WebUtils.getAttributeFromFlowScope(context, "SAMLRequest");
-        redirectURL.append("SAMLRequest=").append(URLEncoder.encode(samlRequest, "UTF-8"));
-        
-        String signature = (String)WebUtils.getAttributeFromFlowScope(context, "Signature");
-        if (signature != null) {
-            redirectURL.append("&");
-            redirectURL.append("Signature=").append(URLEncoder.encode(signature, "UTF-8"));
-        }
-        
-        return redirectURL.toString();
-    }
-    
-    
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
deleted file mode 100644
index 742797d..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseCreator.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans.samlsso;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import org.apache.cxf.common.util.Base64Utility;
-import org.apache.cxf.fediz.core.exception.ProcessingException;
-import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
-import org.apache.cxf.fediz.core.util.CertsUtils;
-import org.apache.cxf.fediz.service.idp.IdpConstants;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.samlsso.SAML2CallbackHandler;
-import org.apache.cxf.fediz.service.idp.samlsso.SAML2PResponseComponentBuilder;
-import org.apache.cxf.fediz.service.idp.samlsso.SAMLAuthnRequest;
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.helpers.DOMUtils;
-import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
-import org.apache.wss4j.common.crypto.Crypto;
-import org.apache.wss4j.common.saml.OpenSAMLUtil;
-import org.apache.wss4j.common.saml.SAMLCallback;
-import org.apache.wss4j.common.saml.SAMLUtil;
-import org.apache.wss4j.common.saml.SamlAssertionWrapper;
-import org.apache.wss4j.common.saml.bean.AudienceRestrictionBean;
-import org.apache.wss4j.common.saml.bean.ConditionsBean;
-import org.apache.wss4j.common.saml.bean.SubjectConfirmationDataBean;
-import org.apache.wss4j.common.util.DOM2Writer;
-import org.apache.wss4j.dom.WSConstants;
-import org.joda.time.DateTime;
-import org.opensaml.saml.saml2.core.Assertion;
-import org.opensaml.saml.saml2.core.NameID;
-import org.opensaml.saml.saml2.core.Response;
-import org.opensaml.saml.saml2.core.Status;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Insert the SAML Token received from the STS into a SAML Response
- */
-@Component
-public class SamlResponseCreator {
-
-    private static final Logger LOG = LoggerFactory.getLogger(SamlResponseCreator.class);
-    private boolean supportDeflateEncoding;
-
-    public String createSAMLResponse(RequestContext context, Idp idp, Element rpToken,
-                                     String consumerURL, String requestId, String requestIssuer) 
-                                         throws ProcessingException {
-        List<Element> samlTokens = 
-            DOMUtils.findAllElementsByTagNameNS(rpToken, WSConstants.SAML2_NS, "Assertion");
-        if (samlTokens.isEmpty() || samlTokens.size() != 1) {
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-        
-        try {
-            SamlAssertionWrapper wrapper = new SamlAssertionWrapper(samlTokens.get(0));
-            if (wrapper.getSaml2() == null) {
-                throw new ProcessingException(TYPE.BAD_REQUEST);
-            }
-            
-            String remoteAddr = WebUtils.getHttpServletRequest(context).getRemoteAddr();
-            Assertion saml2Assertion = 
-                createSAML2Assertion(context, idp, wrapper, requestId, requestIssuer, 
-                                     remoteAddr, consumerURL);
-            
-            Element response = createResponse(idp, requestId, saml2Assertion);
-            return encodeResponse(response);
-        } catch (Exception ex) {
-            LOG.warn("Error marshalling SAML Token: {}", ex.getMessage());
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-    }
-    
-    private Assertion createSAML2Assertion(RequestContext context, Idp idp, SamlAssertionWrapper receivedToken,
-                                           String requestID, String requestIssuer, 
-                                           String remoteAddr, String racs) throws Exception {
-        // Create an AuthenticationAssertion
-        SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
-        callbackHandler.setIssuer(idp.getRealm());
-        callbackHandler.setSubject(receivedToken.getSaml2().getSubject());
-        
-        // Test Subject against received Subject (if applicable)
-        SAMLAuthnRequest authnRequest = 
-            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
-        if (authnRequest.getSubjectNameId() != null && receivedToken.getSaml2().getSubject().getNameID() != null) {
-            NameID issuedNameId = receivedToken.getSaml2().getSubject().getNameID();
-            if (!authnRequest.getSubjectNameId().equals(issuedNameId.getValue())) {
-                LOG.debug("Received NameID value of {} does not match issued value {}",
-                          authnRequest.getSubjectNameId(), issuedNameId.getValue());
-                throw new ProcessingException(ProcessingException.TYPE.INVALID_REQUEST);
-            }
-        }
-        
-        // Subject Confirmation Data
-        SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
-        subjectConfirmationData.setAddress(remoteAddr);
-        subjectConfirmationData.setInResponseTo(requestID);
-        subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
-        subjectConfirmationData.setRecipient(racs);
-        callbackHandler.setSubjectConfirmationData(subjectConfirmationData);
-        
-        // Audience Restriction
-        ConditionsBean conditions = new ConditionsBean();
-        conditions.setTokenPeriodMinutes(5);
-        
-        AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
-        audienceRestriction.setAudienceURIs(Collections.singletonList(requestIssuer));
-        conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
-        callbackHandler.setConditions(conditions);
-        
-        // Attributes
-        callbackHandler.setAttributeStatements(receivedToken.getSaml2().getAttributeStatements());
-        
-        SAMLCallback samlCallback = new SAMLCallback();
-        SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
-        SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);
-        
-        Crypto issuerCrypto = CertsUtils.getCryptoFromCertificate(idp.getCertificate());
-        assertion.signAssertion(issuerCrypto.getDefaultX509Identifier(), idp.getCertificatePassword(), 
-                                issuerCrypto, false);
-        
-        return assertion.getSaml2();
-    }
-    
-    protected Element createResponse(Idp idp, String requestID, Assertion assertion) throws Exception {
-        Document doc = DOMUtils.newDocument();
-        
-        Status status = 
-            SAML2PResponseComponentBuilder.createStatus(
-                "urn:oasis:names:tc:SAML:2.0:status:Success", null
-            );
-        Response response = 
-            SAML2PResponseComponentBuilder.createSAMLResponse(requestID, idp.getRealm(), status);
-        
-        response.getAssertions().add(assertion);
-        
-        Element policyElement = OpenSAMLUtil.toDom(response, doc);
-        doc.appendChild(policyElement);
-        
-        return policyElement;
-    }
-
-    protected String encodeResponse(Element response) throws IOException {
-        String responseMessage = DOM2Writer.nodeToString(response);
-        LOG.debug("Created Response: {}", responseMessage);
-
-        if (supportDeflateEncoding) {
-            DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
-            byte[] deflatedBytes = encoder.deflateToken(responseMessage.getBytes("UTF-8"));
-
-            return Base64Utility.encode(deflatedBytes);
-        }
-        
-        return Base64Utility.encode(responseMessage.getBytes());
-    }
-    
-    public boolean isSupportDeflateEncoding() {
-        return supportDeflateEncoding;
-    }
-
-    public void setSupportDeflateEncoding(boolean supportDeflateEncoding) {
-        this.supportDeflateEncoding = supportDeflateEncoding;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseErrorCreator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseErrorCreator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseErrorCreator.java
deleted file mode 100644
index ce257e0..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/SamlResponseErrorCreator.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans.samlsso;
-
-import java.io.IOException;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import org.apache.cxf.common.util.Base64Utility;
-import org.apache.cxf.fediz.core.exception.ProcessingException;
-import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.samlsso.SAML2PResponseComponentBuilder;
-import org.apache.cxf.helpers.DOMUtils;
-import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
-import org.apache.wss4j.common.saml.OpenSAMLUtil;
-import org.apache.wss4j.common.util.DOM2Writer;
-import org.opensaml.saml.saml2.core.Response;
-import org.opensaml.saml.saml2.core.Status;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * Create a SAML Error Response
- */
-@Component
-public class SamlResponseErrorCreator {
-
-    private static final Logger LOG = LoggerFactory.getLogger(SamlResponseErrorCreator.class);
-    private boolean supportDeflateEncoding;
-
-    public String createSAMLResponse(RequestContext context, boolean requestor,
-                                     Idp idp, String requestID) throws ProcessingException { 
-        Document doc = DOMUtils.newDocument();
-        
-        String statusValue = "urn:oasis:names:tc:SAML:2.0:status:Responder";
-        if (requestor) {
-            statusValue = "urn:oasis:names:tc:SAML:2.0:status:Requester";
-        }
-        Status status = 
-            SAML2PResponseComponentBuilder.createStatus(statusValue, null);
-        Response response = 
-            SAML2PResponseComponentBuilder.createSAMLResponse(requestID, idp.getRealm(), status);
-        
-        try {
-            Element policyElement = OpenSAMLUtil.toDom(response, doc);
-            doc.appendChild(policyElement);
-            
-            Element responseElement = policyElement;
-            return encodeResponse(responseElement);
-        } catch (Exception e) {
-            LOG.warn("Error marshalling SAML Token: {}", e.getMessage());
-            throw new ProcessingException(TYPE.BAD_REQUEST);
-        }
-    }
-
-    protected String encodeResponse(Element response) throws IOException {
-        String responseMessage = DOM2Writer.nodeToString(response);
-        LOG.debug("Created Response: {}", responseMessage);
-
-        if (supportDeflateEncoding) {
-            DeflateEncoderDecoder encoder = new DeflateEncoderDecoder();
-            byte[] deflatedBytes = encoder.deflateToken(responseMessage.getBytes("UTF-8"));
-
-            return Base64Utility.encode(deflatedBytes);
-        }
-        
-        return Base64Utility.encode(responseMessage.getBytes());
-    }
-    
-    public boolean isSupportDeflateEncoding() {
-        return supportDeflateEncoding;
-    }
-
-    public void setSupportDeflateEncoding(boolean supportDeflateEncoding) {
-        this.supportDeflateEncoding = supportDeflateEncoding;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/wsfed/WfreshParser.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/wsfed/WfreshParser.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/wsfed/WfreshParser.java
deleted file mode 100644
index 148d24b..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/beans/wsfed/WfreshParser.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.beans.wsfed;
-
-import java.util.Date;
-
-import org.apache.cxf.fediz.service.idp.util.WebUtils;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.springframework.stereotype.Component;
-import org.springframework.webflow.execution.RequestContext;
-
-/**
- * This class is responsible to parse the 'wfresh' parameter 
- */
-@Component
-public class WfreshParser {
-
-    private static final Logger LOG = LoggerFactory.getLogger(WfreshParser.class);
-
-    public boolean authenticationRequired(String wfresh, String whr, RequestContext context)
-        throws Exception {
-        
-        SecurityToken idpToken = 
-            (SecurityToken) WebUtils.getAttributeFromExternalContext(context, whr);
-        if (idpToken == null) {
-            return true;
-        }
-        
-        if (wfresh == null || wfresh.trim().isEmpty()) {
-            return false;
-        }
-
-        long ttl;
-        try {
-            ttl = Long.parseLong(wfresh.trim());
-        } catch (Exception e) {
-            LOG.info("wfresh value '" + wfresh + "' is invalid.");
-            return false;
-        }
-        if (ttl == 0) {
-            return true;
-        }
-        
-        long ttlMs = ttl * 60L * 1000L;
-        if (ttlMs > 0) {
-            Date createdDate = idpToken.getCreated();
-            if (createdDate != null) {
-                Date expiryDate = new Date();
-                expiryDate.setTime(createdDate.getTime() + ttlMs);
-                if (expiryDate.before(new Date())) {
-                    LOG.info("[IDP_TOKEN="
-                            + idpToken.getId()
-                            + "] is valid but relying party requested new authentication caused by wfresh="
-                            + wfresh + " outdated.");
-                    return true;
-                }
-            } else {
-                LOG.info("token creation date not set. Unable to check wfresh is outdated.");
-            }
-        } else {
-            LOG.info("ttl value '" + ttl + "' is negative or is too large.");
-        }
-        return false;
-    }
-    
-}


[06/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Application.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Application.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Application.java
deleted file mode 100644
index 814e342..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Application.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.domain;
-
-import java.io.Serializable;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Pattern;
-
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElementRef;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlType;
-
-@XmlRootElement(name = "application", namespace = "http://org.apache.cxf.fediz/")
-@XmlType(propOrder = {"realm", "role", "serviceDisplayName", "serviceDescription", "protocol",
-                      "tokenType", "lifeTime", "encryptionCertificate", "requestedClaims",
-                      "policyNamespace", "passiveRequestorEndpoint", "passiveRequestorEndpointConstraint", "id",
-                      "validatingCertificate", "enableAppliesTo"})
-public class Application implements Serializable {
-        
-    private static final long serialVersionUID = 5644327504861846964L;
-
-    
-    
-    protected int id;
-    
-            
-    //Could be imported from Metadata document or manually filled
-    
-    //@Column(name = "REALM", nullable = true, length = FIELD_LENGTH)
-    protected String realm;  //wtrealm, whr
-
-    //Could be read from Metadata, RoleDescriptor protocolSupportEnumeration=
-    // "http://docs.oasis-open.org/wsfed/federation/200706"
-    // Metadata could provide more than one but one must be chosen
-    protected String protocol;
- 
-    // Public key only
-    // Could be read from Metadata, md:KeyDescriptor, use="encryption"
-    protected String encryptionCertificate;
-    
-    // Certificate for Signature verification
-    protected String validatingCertificate;
-    
-    // Could be read from Metadata, fed:ClaimTypesRequested
-    protected List<RequestClaim> requestedClaims = new ArrayList<>();
-    
-    //Could be read from Metadata, ServiceDisplayName
-    //usage for list of application where user is logged in
-    protected String serviceDisplayName;
-    
-    //Could be read from Metadata, ServiceDescription
-    //usage for list of application where user is logged in
-    protected String serviceDescription;
-    
-    //Could be read from Metadata, RoleDescriptor
-    //fed:ApplicationServiceType, fed:SecurityTokenServiceType
-    protected String role;
-        
-    // Not in Metadata, configured in IDP or passed in wreq parameter
-    protected String tokenType;
-    
-    // Not in Metadata, configured in IDP or passed in wreq parameter
-    protected int lifeTime;
-    
-    // WS-Policy Namespace for AppliesTo element
-    protected String policyNamespace;
-    
-    // Request audience restriction in token for this application (default is true)
-    private boolean enableAppliesTo = true;
-    
-    private URI href;
-    
-    //Could be read from Metadata, PassiveRequestorEndpoint
-    //fed:ApplicationServiceType, fed:SecurityTokenServiceType
-    private String passiveRequestorEndpoint;
-    
-    // A regular expression constraint on the passiveRequestorEndpoint
-    private String passiveRequestorEndpointConstraint;
-    private Pattern compiledPassiveRequestorEndpointConstraint;
-    
-    
-    @XmlAttribute
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    @XmlAttribute
-    public URI getHref() {
-        return href;
-    }
-
-    public void setHref(URI href) {
-        this.href = href;
-    }
-
-    public String getRealm() {
-        return realm;
-    }
-
-    public void setRealm(String realm) {
-        this.realm = realm;
-    }
-
-    public String getProtocol() {
-        return protocol;
-    }
-
-    public void setProtocol(String protocol) {
-        this.protocol = protocol;
-    }
-
-    public String getEncryptionCertificate() {
-        return encryptionCertificate;
-    }
-
-    public void setEncryptionCertificate(String encryptionCertificate) {
-        this.encryptionCertificate = encryptionCertificate;
-    }
-
-    @XmlElementWrapper(name = "claims")
-    @XmlElementRef(name = "requestedClaims")
-    public List<RequestClaim> getRequestedClaims() {
-        return requestedClaims;
-    }
-
-    public void setRequestedClaims(List<RequestClaim> requestedClaims) {
-        this.requestedClaims = requestedClaims;
-    }
-
-    public String getServiceDisplayName() {
-        return serviceDisplayName;
-    }
-
-    public void setServiceDisplayName(String serviceDisplayName) {
-        this.serviceDisplayName = serviceDisplayName;
-    }
-
-    public String getServiceDescription() {
-        return serviceDescription;
-    }
-
-    public void setServiceDescription(String serviceDescription) {
-        this.serviceDescription = serviceDescription;
-    }
-
-    public String getRole() {
-        return role;
-    }
-
-    public void setRole(String role) {
-        this.role = role;
-    }
-
-    public String getTokenType() {
-        return tokenType;
-    }
-
-    public void setTokenType(String tokenType) {
-        this.tokenType = tokenType;
-    }
-
-    public int getLifeTime() {
-        return lifeTime;
-    }
-
-    public void setLifeTime(int lifeTime) {
-        this.lifeTime = lifeTime;
-    }
-
-    public String getPolicyNamespace() {
-        return policyNamespace;
-    }
-
-    public void setPolicyNamespace(String policyNamespace) {
-        this.policyNamespace = policyNamespace;
-    }
-
-    public String getPassiveRequestorEndpoint() {
-        return passiveRequestorEndpoint;
-    }
-
-    public void setPassiveRequestorEndpoint(String passiveRequestorEndpoint) {
-        this.passiveRequestorEndpoint = passiveRequestorEndpoint;
-    }
-
-    public String getPassiveRequestorEndpointConstraint() {
-        return passiveRequestorEndpointConstraint;
-    }
-
-    public void setPassiveRequestorEndpointConstraint(String passiveRequestorEndpointConstraint) {
-        this.passiveRequestorEndpointConstraint = passiveRequestorEndpointConstraint;
-        if (passiveRequestorEndpointConstraint != null) {
-            compiledPassiveRequestorEndpointConstraint = Pattern.compile(passiveRequestorEndpointConstraint);
-        } else {
-            compiledPassiveRequestorEndpointConstraint = null;
-        }
-    }
-    
-    public Pattern getCompiledPassiveRequestorEndpointConstraint() {
-        return compiledPassiveRequestorEndpointConstraint;
-    }
-    
-    public String getValidatingCertificate() {
-        return validatingCertificate;
-    }
-
-    public void setValidatingCertificate(String validatingCertificate) {
-        this.validatingCertificate = validatingCertificate;
-    }
-
-    public boolean isEnableAppliesTo() {
-        return enableAppliesTo;
-    }
-
-    public void setEnableAppliesTo(boolean useAudienceRestriction) {
-        this.enableAppliesTo = useAudienceRestriction;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Claim.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Claim.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Claim.java
deleted file mode 100644
index 96afed9..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Claim.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.domain;
-
-import java.io.Serializable;
-import java.net.URI;
-
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement(name = "claim", namespace = "http://org.apache.cxf.fediz/")
-public class Claim implements Serializable {
-    
-    private static final long serialVersionUID = 2635896159019665467L;
-    
-    protected URI claimType;
-    protected String displayName;
-    protected String description;
-    protected int id;
-    private URI href;
-    
-    @XmlAttribute
-    public URI getHref() {
-        return href;
-    }
-
-    public void setHref(URI href) {
-        this.href = href;
-    }
-    
-    @XmlAttribute
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    public void setClaimType(URI claimType) {
-        this.claimType = claimType;
-    }
-    
-    public URI getClaimType() {
-        return claimType;
-    }
-
-    public String getDisplayName() {
-        return displayName;
-    }
-
-    public void setDisplayName(String displayName) {
-        this.displayName = displayName;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Entitlement.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Entitlement.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Entitlement.java
deleted file mode 100644
index c926386..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Entitlement.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.domain;
-
-import java.io.Serializable;
-
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlType;
-
-@XmlRootElement(name = "entitlement", namespace = "http://org.apache.cxf.fediz/")
-@XmlType(propOrder = {"name", "description", "internal", "id" })
-public class Entitlement implements Serializable {
-    
-    private static final long serialVersionUID = 2635896159019665467L;
-    
-    protected String name;
-    protected String description;
-    protected int id;
-    protected boolean internal;
-    
-    @XmlAttribute
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-
-    public boolean isInternal() {
-        return internal;
-    }
-
-    public void setInternal(boolean internal) {
-        this.internal = internal;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/FederationType.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/FederationType.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/FederationType.java
deleted file mode 100644
index 2dcc296..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/FederationType.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.domain;
-
-import javax.xml.bind.annotation.XmlEnum;
-
-@XmlEnum
-public enum FederationType {
-
-    FEDERATE_IDENTITY("FederateIdentity"),
-    FEDERATE_CLAIMS("FederateClaims");
-
-    private String name;
-
-    FederationType(final String name) {
-        this.name = name;
-    }
-
-    @Override
-    public String toString() {
-        return name;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Idp.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Idp.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Idp.java
deleted file mode 100644
index d382184..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Idp.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.domain;
-
-import java.io.Serializable;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElementRef;
-import javax.xml.bind.annotation.XmlElementWrapper;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlType;
-
-@XmlRootElement(name = "idp", namespace = "http://org.apache.cxf.fediz/")
-@XmlType(propOrder = {"realm", "uri", "serviceDisplayName", "serviceDescription", "idpUrl", "stsUrl",
-                     "certificate", "certificatePassword", "provideIdpList", "useCurrentIdp", "hrds",
-                     "rpSingleSignOutConfirmation", "supportedProtocols", "tokenTypesOffered", "claimTypesOffered",
-                     "authenticationURIs", "applications", "trustedIdps", "id", "rpSingleSignOutCleanupConfirmation" })
-public class Idp implements Serializable {
-
-    private static final long serialVersionUID = -5570301342547139039L;
-
-    
-    protected int id;
-    
-    // Unique
-    // fed:TargetScope
-    protected String realm; // wtrealm, whr
-
-    // Unique
-    // https://<host>:<port>/fediz-idp/<IDP uri>/
-    protected String uri;
-
-    // Home Realm Discovery Service
-    // Spring EL
-    protected String hrds;
-
-    // @Column(name = "INACTIVE", nullable = true, length = FIELD_LENGTH)
-    // if HRDS can't determine the home realm, should
-    // the list of trusted IDPs be shown to make a choice
-    protected boolean provideIdpList;
-
-    // If HRDS can't discover a home realm and displaying IDP list is not
-    // enabled
-    // it falls back to current IDP if an authentication domain is configured
-    protected boolean useCurrentIdp;
-
-    // Store certificate in DB or filesystem, provide options?
-    // md:KeyDescriptor, use="signing"
-    protected String certificate;
-
-    // Password to read the private key to sign metadata document
-    protected String certificatePassword;
-
-    // fed:SecurityTokenSerivceEndpoint
-    protected URL stsUrl;
-
-    // fed:PassiveRequestorEndpoint
-    // published hostname, port must be configured
-    protected URL idpUrl;
-
-    // RoleDescriptor protocolSupportEnumeration=
-    // "http://docs.oasis-open.org/wsfed/federation/200706"
-    // "http://docs.oasis-open.org/ws-sx/ws-trust/200512"
-    // Could be more in the future
-    protected List<String> supportedProtocols = new ArrayList<>();
-
-    // list of RPs and RP-IDPs from whom we accept SignInResponse
-    // which includes RP IDPs
-    // key: wtrealm
-    protected List<Application> applications = new ArrayList<>();
-
-    // list of trusted IDP from whom we accept SignInResponse
-    // key: whr
-    protected List<TrustedIdp> trustedIdpList = new ArrayList<>();
-
-    // which URI to redirect for authentication
-    // fediz-idp/<IDP uri>/login/auth/<auth URI>
-    // wauth to auth URI mapping
-    protected Map<String, String> authenticationURIs = new HashMap<>();
-
-    // required to create Federation Metadata document
-    // fed:TokenTypesOffered
-    protected List<String> tokenTypesOffered = new ArrayList<>();
-
-    // fed:ClaimTypesOffered
-    protected List<Claim> claimTypesOffered = new ArrayList<>();
-
-    // ServiceDisplayName
-    protected String serviceDisplayName;
-
-    // ServiceDescription
-    protected String serviceDescription;
-    
-    // The user/browser must explicitly confirm to logout from all applications
-    private boolean rpSingleSignOutConfirmation;
-    
-    // Is explicit confirmation required when the "cleanup" URL is called
-    private boolean rpSingleSignOutCleanupConfirmation;
-    
-    @XmlAttribute
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    public String getRealm() {
-        return realm;
-    }
-
-    public void setRealm(String realm) {
-        this.realm = realm;
-    }
-
-    public String getUri() {
-        return uri;
-    }
-
-    public void setUri(String uri) {
-        this.uri = uri;
-    }
-
-    public String getHrds() {
-        return hrds;
-    }
-
-    public void setHrds(String hrds) {
-        this.hrds = hrds;
-    }
-
-    public boolean isProvideIdpList() {
-        return provideIdpList;
-    }
-
-    public void setProvideIdpList(boolean provideIdpList) {
-        this.provideIdpList = provideIdpList;
-    }
-
-    public boolean isUseCurrentIdp() {
-        return useCurrentIdp;
-    }
-
-    public void setUseCurrentIdp(boolean useCurrentIdp) {
-        this.useCurrentIdp = useCurrentIdp;
-    }
-
-    public String getCertificate() {
-        return certificate;
-    }
-
-    public void setCertificate(String certificate) {
-        this.certificate = certificate;
-    }
-
-    public String getCertificatePassword() {
-        return certificatePassword;
-    }
-
-    public void setCertificatePassword(String password) {
-        this.certificatePassword = password;
-    }
-
-    public URL getStsUrl() {
-        return stsUrl;
-    }
-
-    public void setStsUrl(URL stsUrl) {
-        this.stsUrl = stsUrl;
-    }
-
-    public URL getIdpUrl() {
-        return idpUrl;
-    }
-
-    public void setIdpUrl(URL idpUrl) {
-        this.idpUrl = idpUrl;
-    }
-
-    @XmlElementWrapper(name = "supportedProtocols")
-    public List<String> getSupportedProtocols() {
-        return supportedProtocols;
-    }
-
-    public void setSupportedProtocols(List<String> supportedProtocols) {
-        this.supportedProtocols = supportedProtocols;
-    }
-
-    public Application findApplication(String realmApplication) {
-        for (Application item : applications) {
-            if (item.getRealm().equals(realmApplication)) {
-                return item;
-            }
-        }
-        return null;
-    }
-    
-    @XmlElementWrapper(name = "applications")
-    @XmlElementRef(name = "application")
-    public List<Application> getApplications() {
-        return applications;
-    }
-
-    public void setApplications(List<Application> applications) {
-        this.applications = applications;
-    }
-
-    public TrustedIdp findTrustedIdp(String realmTrustedIdp) {
-        for (TrustedIdp item : trustedIdpList) {
-            if (item.getRealm().equals(realmTrustedIdp)) {
-                return item;
-            }
-        }
-        return null;
-    }
-    
-    @XmlElementWrapper(name = "trustedIdps")
-    @XmlElementRef(name = "trustedIdp")
-    public List<TrustedIdp> getTrustedIdps() {
-        return trustedIdpList;
-    }
-
-    public Map<String, String> getAuthenticationURIs() {
-        return authenticationURIs;
-    }
-
-    public void setAuthenticationURIs(Map<String, String> authenticationURIs) {
-        this.authenticationURIs = authenticationURIs;
-    }
-
-    @XmlElementWrapper(name = "tokenTypesOffered")
-    public List<String> getTokenTypesOffered() {
-        return tokenTypesOffered;
-    }
-
-    public void setTokenTypesOffered(List<String> tokenTypesOffered) {
-        this.tokenTypesOffered = tokenTypesOffered;
-    }
-
-    @XmlElementWrapper(name = "claimTypesOffered")
-    @XmlElementRef(name = "claimType")
-    public List<Claim> getClaimTypesOffered() {
-        return claimTypesOffered;
-    }
-
-    public void setClaimTypesOffered(List<Claim> claimTypesOffered) {
-        this.claimTypesOffered = claimTypesOffered;
-    }
-
-    public String getServiceDisplayName() {
-        return serviceDisplayName;
-    }
-
-    public void setServiceDisplayName(String serviceDisplayName) {
-        this.serviceDisplayName = serviceDisplayName;
-    }
-
-    public String getServiceDescription() {
-        return serviceDescription;
-    }
-
-    public void setServiceDescription(String serviceDescription) {
-        this.serviceDescription = serviceDescription;
-    }
-
-    public boolean isRpSingleSignOutConfirmation() {
-        return rpSingleSignOutConfirmation;
-    }
-
-    public void setRpSingleSignOutConfirmation(boolean rpSingleSignOutConfirmation) {
-        this.rpSingleSignOutConfirmation = rpSingleSignOutConfirmation;
-    }
-
-    public boolean isRpSingleSignOutCleanupConfirmation() {
-        return rpSingleSignOutCleanupConfirmation;
-    }
-
-    public void setRpSingleSignOutCleanupConfirmation(boolean rpSingleSignOutCleanupConfirmation) {
-        this.rpSingleSignOutCleanupConfirmation = rpSingleSignOutCleanupConfirmation;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/RequestClaim.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/RequestClaim.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/RequestClaim.java
deleted file mode 100644
index 008e75a..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/RequestClaim.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.domain;
-
-import javax.xml.bind.annotation.XmlRootElement;
-
-@XmlRootElement(name = "requestClaim", namespace = "http://org.apache.cxf.fediz/")
-public class RequestClaim extends Claim {
-    
-    private static final long serialVersionUID = 8097560995225077866L;
-    
-    protected boolean optional;
-    
-    public RequestClaim() {
-        super();
-    }
-    
-    public RequestClaim(Claim c) {
-        super();
-        this.setClaimType(c.getClaimType());
-        this.setDescription(c.getDescription());
-        this.setDisplayName(c.getDisplayName());
-        this.setId(c.getId());
-    }
-      
-    public void setOptional(boolean optional) {
-        this.optional = optional;
-    }
-    
-    public boolean isOptional() {
-        return optional;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Role.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Role.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Role.java
deleted file mode 100644
index f403546..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/Role.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.domain;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlType;
-
-@XmlRootElement(name = "role", namespace = "http://org.apache.cxf.fediz/")
-@XmlType(propOrder = {"name", "description", "entitlements", "id" })
-public class Role implements Serializable {
-    
-    private static final long serialVersionUID = 2635896159019665467L;
-    
-    protected String name;
-    protected String description;
-    protected int id;
-    
-    protected List<Entitlement> entitlements = new ArrayList<>();
-    
-    @XmlAttribute
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-
-    public List<Entitlement> getEntitlements() {
-        return entitlements;
-    }
-
-    public void setEntitlements(List<Entitlement> entitlements) {
-        this.entitlements = entitlements;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustType.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustType.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustType.java
deleted file mode 100644
index 50efb25..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustType.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.domain;
-
-import javax.xml.bind.annotation.XmlEnum;
-
-@XmlEnum
-public enum TrustType {
-
-    PEER_TRUST("PeerTrust"),
-    INDIRECT_TRUST("IndirectTrust");
-
-    private String name;
-
-    TrustType(final String name) {
-        this.name = name;
-    }
-
-    @Override
-    public String toString() {
-        return name;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustedIdp.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustedIdp.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustedIdp.java
deleted file mode 100644
index b3262b5..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/domain/TrustedIdp.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.domain;
-
-import java.io.Serializable;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlRootElement;
-import javax.xml.bind.annotation.XmlType;
-
-@XmlRootElement(name = "trustedIdp", namespace = "http://org.apache.cxf.fediz/")
-@XmlType(propOrder = {"realm", "issuer", "url", "name", "description", "protocol", "trustType",
-                      "certificate", "federationType", "cacheTokens", "logo", "id", "parameters" })
-//@XmlAttribute on Id must be set on getter, not on attribute, otherwise error
-public class TrustedIdp implements Serializable {
-
-    private static final long serialVersionUID = -6520081722646469178L;
-
-    
-    protected int id;
-
-    //@Column(name = "REALM", nullable = true, length = FIELD_LENGTH)
-    protected String realm;  //wtrealm, whr
-    
-    //@Column(name = "Issuer", nullable = true, length = FIELD_LENGTH)
-    protected String issuer;  //SAMLResponse issuer name
-
-    // Should tokens be cached from trusted IDPs
-    // to avoid redirection to the trusted IDP again for next SignIn request
-    protected boolean cacheTokens;
-    
-    //Could be read from Metadata, PassiveRequestorEndpoint
-    protected String url;
-    
-    //Could be read from Metadata, md:KeyDescriptor, use="signing"
-    //Store certificate in DB or filesystem, provide options?
-    protected String certificate;
-    
-    //Direct trust (signing cert imported), Indirect trust (CA certs imported, subject configured)
-    protected TrustType trustType;
-    
-    //Could be read from Metadata, RoleDescriptor protocolSupportEnumeration=
-    // "http://docs.oasis-open.org/wsfed/federation/200706"
-    // Metadata could provide more than one but one must be chosen
-    protected String protocol;
-    
-    //FederateIdentity, FederateClaims
-    protected FederationType federationType;
-    
-    //optional (to provide a list of IDPs)
-    protected String name;
-    
-    //optional (to provide a list of IDPs)
-    protected String description;
-    
-    //optional (to provide a list of IDPs)
-    protected String logo;
-    
-    // Additional (possibly protocol specific parameters)
-    protected Map<String, String> parameters = new HashMap<>();
-
-    
-    @XmlAttribute
-    public int getId() {
-        return id;
-    }
-
-    public void setId(int id) {
-        this.id = id;
-    }
-    
-    public String getIssuer() {
-        return issuer;
-    }
-    
-    public void setIssuer(String issuer) {
-        this.issuer = issuer;
-    }
-    
-    public String getRealm() {
-        return realm;
-    }
-
-    public void setRealm(String realm) {
-        this.realm = realm;
-    }
-
-    public boolean isCacheTokens() {
-        return cacheTokens;
-    }
-
-    public void setCacheTokens(boolean cacheTokens) {
-        this.cacheTokens = cacheTokens;
-    }
-
-    public String getUrl() {
-        return url;
-    }
-
-    public void setUrl(String url) {
-        this.url = url;
-    }
-
-    public String getCertificate() {
-        return certificate;
-    }
-
-    public void setCertificate(String certificate) {
-        this.certificate = certificate;
-    }
-
-    public String getProtocol() {
-        return protocol;
-    }
-
-    public void setProtocol(String protocol) {
-        this.protocol = protocol;
-    }
-
-    public FederationType getFederationType() {
-        return federationType;
-    }
-
-    public void setFederationType(FederationType federationType) {
-        this.federationType = federationType;
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public void setName(String name) {
-        this.name = name;
-    }
-
-    public String getDescription() {
-        return description;
-    }
-
-    public void setDescription(String description) {
-        this.description = description;
-    }
-
-    public String getLogo() {
-        return logo;
-    }
-
-    public void setLogo(String logo) {
-        this.logo = logo;
-    }
-
-    public TrustType getTrustType() {
-        return trustType;
-    }
-
-    public void setTrustType(TrustType trustType) {
-        this.trustType = trustType;
-    }
-
-    public Map<String, String> getParameters() {
-        return parameters;
-    }
-
-    public void setParameters(Map<String, String> parameters) {
-        this.parameters = parameters;
-    }
-               
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosAuthenticationProcessingFilter.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosAuthenticationProcessingFilter.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosAuthenticationProcessingFilter.java
deleted file mode 100644
index 8e39e85..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosAuthenticationProcessingFilter.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-/*
- * Copyright 2002-2008 the original author or authors.
- * 
- * 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 org.apache.cxf.fediz.service.idp.kerberos;
-
-import java.io.IOException;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.springframework.security.authentication.AnonymousAuthenticationToken;
-import org.springframework.security.authentication.AuthenticationDetailsSource;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.security.crypto.codec.Base64;
-import org.springframework.security.web.authentication.AuthenticationFailureHandler;
-import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
-import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
-import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
-import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
-import org.springframework.util.Assert;
-import org.springframework.web.filter.GenericFilterBean;
-/**
- * Parses the SPNEGO authentication Header, which was generated by the browser
- * and creates a {@link KerberosServiceRequestToken} out if it. It will then
- * call the {@link AuthenticationManager}.
- *
- * @author Mike Wiesner
- * @since 1.0
- * @version $Id$
- * @see KerberosServiceAuthenticationProvider
- * @see KerberosEntryPoint
- */
-public class KerberosAuthenticationProcessingFilter extends GenericFilterBean {
-    private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = 
-        new WebAuthenticationDetailsSource();
-    private AuthenticationManager authenticationManager;
-    private AuthenticationSuccessHandler successHandler;
-    private AuthenticationFailureHandler failureHandler;
-    private SessionAuthenticationStrategy sessionStrategy = new NullAuthenticatedSessionStrategy();
-    private boolean skipIfAlreadyAuthenticated = true;
-    /*
-     * (non-Javadoc)
-     *
-     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
-     * javax.servlet.ServletResponse, javax.servlet.FilterChain)
-     */
-    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 
-        throws IOException, ServletException {
-        HttpServletRequest request = (HttpServletRequest) req;
-        HttpServletResponse response = (HttpServletResponse) res;
-        if (skipIfAlreadyAuthenticated) {
-            Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
-            if (existingAuth != null && existingAuth.isAuthenticated()
-                && !(existingAuth instanceof AnonymousAuthenticationToken)) {
-                chain.doFilter(request, response);
-                return;
-            }
-        }
-        String header = request.getHeader("Authorization");
-        if ((header != null) && header.startsWith("Negotiate ")) {
-            if (logger.isDebugEnabled()) {
-                logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
-            }
-            byte[] base64Token = header.substring(10).getBytes("UTF-8");
-            byte[] kerberosTicket = Base64.decode(base64Token);
-            KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
-            authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));
-            Authentication authentication;
-            try {
-                authentication = authenticationManager.authenticate(authenticationRequest);
-            } catch (AuthenticationException e) {
-                //That shouldn't happen, as it is most likely a wrong
-                //configuration on the server side
-                logger.warn("Negotiate Header was invalid: " + header, e);
-                SecurityContextHolder.clearContext();
-                if (failureHandler != null) {
-                    failureHandler.onAuthenticationFailure(request, response, e);
-                } else {
-                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-                    response.flushBuffer();
-                }
-                return;
-            }
-            sessionStrategy.onAuthentication(authentication, request, response);
-            SecurityContextHolder.getContext().setAuthentication(authentication);
-            if (successHandler != null) {
-                successHandler.onAuthenticationSuccess(request, response, authentication);
-            }
-        }
-        chain.doFilter(request, response);
-    }
-    /**
-     * The authentication manager for validating the ticket.
-     *
-     * @param authenticationManager
-     */
-    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
-        this.authenticationManager = authenticationManager;
-    }
-    /**
-     * This handler is called after a successful authentication. One can add
-     * additional authentication behavior by setting this.<br />
-     * Default is null, which means nothing additional happens
-     *
-     * @param successHandler
-     */
-    public void setSuccessHandler(AuthenticationSuccessHandler successHandler) {
-        this.successHandler = successHandler;
-    }
-    /**
-     * This handler is called after a failure authentication. In most cases you
-     * only get Kerberos/SPNEGO failures with a wrong server or network
-     * configurations and not during runtime. If the client encounters an error,
-     * he will just stop the communication with server and therefore this
-     * handler will not be called in this case.<br />
-     * Default is null, which means that the Filter returns the HTTP 500 code
-     *
-     * @param failureHandler
-     */
-    public void setFailureHandler(AuthenticationFailureHandler failureHandler) {
-        this.failureHandler = failureHandler;
-    }
-    /**
-     * Should Kerberos authentication be skipped if a user is already authenticated
-     * for this request (e.g. in the HTTP session).
-     *
-     * @param skipIfAlreadyAuthenticated default is true
-     */
-    public void setSkipIfAlreadyAuthenticated(boolean skipIfAlreadyAuthenticated) {
-        this.skipIfAlreadyAuthenticated = skipIfAlreadyAuthenticated;
-    }
-    /**
-     * The session handling strategy which will be invoked immediately after an authentication request is
-     * successfully processed by the <tt>AuthenticationManager</tt>. Used, for example, to handle changing of the
-     * session identifier to prevent session fixation attacks.
-     *
-     * @param sessionAuthStrategy the implementation to use. If not set a null implementation is
-     * used.
-     */
-    public void setSessionAuthenticationStrategy(SessionAuthenticationStrategy sessionAuthStrategy) {
-        this.sessionStrategy = sessionAuthStrategy;
-    }
-    public void setAuthenticationDetailsSource(
-        AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
-        Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
-        this.authenticationDetailsSource = authenticationDetailsSource;
-    }
-    /*
-     * (non-Javadoc)
-     *
-     * @see
-     * org.springframework.web.filter.GenericFilterBean#afterPropertiesSet()
-     */
-    @Override
-    public void afterPropertiesSet() throws ServletException {
-        super.afterPropertiesSet();
-        Assert.notNull(this.authenticationManager, "authenticationManager must be specified");
-    }
-}
-
-
-

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosEntryPoint.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosEntryPoint.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosEntryPoint.java
deleted file mode 100644
index 457a60e..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosEntryPoint.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-/*
- * Copyright 2009 the original author or authors.
- * 
- * 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 org.apache.cxf.fediz.service.idp.kerberos;
-
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.web.AuthenticationEntryPoint;
-
-/**
-* Sends back a request for a Negotiate Authentication to the browser.
-*
-* @author Mike Wiesner
-* @since 1.0
-* @version $Id$
-* @see KerberosAuthenticationProcessingFilter
-*/
-public class KerberosEntryPoint implements AuthenticationEntryPoint {
-    
-    private static final Log LOG = LogFactory.getLog(KerberosEntryPoint.class);
-    
-    public void commence(HttpServletRequest request, HttpServletResponse response,
-                         AuthenticationException ex) throws IOException, ServletException {
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Sending back Negotiate Header for request: " + request.getRequestURL());
-        }
-        response.addHeader("WWW-Authenticate", "Negotiate");
-        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
-        response.flushBuffer();
-    }
-    
-}
-

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosServiceRequestToken.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosServiceRequestToken.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosServiceRequestToken.java
deleted file mode 100644
index 2aba9cf..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosServiceRequestToken.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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.
- */
-/*
- * Copyright 2009 the original author or authors.
- * 
- * 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 org.apache.cxf.fediz.service.idp.kerberos;
-
-import java.util.Arrays;
-import java.util.Collection;
-import org.springframework.security.authentication.AbstractAuthenticationToken;
-import org.springframework.security.core.GrantedAuthority;
-
-/**
- * Holds the Kerberos/SPNEGO token for requesting a kerberized service
- * and is also the output of <code>KerberosServiceAuthenticationProvider</code>.<br>
- * Will mostly be created in <code>SpnegoAuthenticationProcessingFilter</code>
- * and authenticated in <code>KerberosServiceAuthenticationProvider</code>.
- *
- * This token cannot be re-authenticated, as you will get a Kerberos Reply error.
- *
- * @author Mike Wiesner
- * @since 1.0
- * @version $Id$
- * @see KerberosServiceAuthenticationProvider
- * @see KerberosAuthenticationProcessingFilter
- */
-public class KerberosServiceRequestToken extends AbstractAuthenticationToken {
-    private static final long serialVersionUID = 395488921064775014L;
-    private final byte[] token;
-    private final Object principal;
-    
-    /** Creates an authenticated token, normally used as an output of an authentication provider.
-     * @param principal the user principal (mostly of instance <code>UserDetails</code>
-     * @param authorities the authorities which are granted to the user
-     * @param token the Kerberos/SPNEGO token
-     * @see UserDetails
-     */
-    public KerberosServiceRequestToken(Object principal, 
-                                       Collection<? extends GrantedAuthority> authorities, 
-                                       byte[] token) {
-        super(authorities);
-        if (token != null) {
-            this.token = Arrays.copyOf(token, token.length);
-        } else {
-            this.token = null;
-        }
-        this.principal = principal;
-        super.setAuthenticated(true);
-    }
-    
-    /**
-     * Creates an unauthenticated instance which should then be authenticated by
-     * <code>KerberosServiceAuthenticationProvider/code>
-     *
-     * @param token Kerberos/SPNEGO token
-     * @see KerberosServiceAuthenticationProvider
-     */
-    public KerberosServiceRequestToken(byte[] token) {
-        super(null);
-        if (token != null) {
-            this.token = Arrays.copyOf(token, token.length);
-        } else {
-            this.token = null;
-        }
-        this.principal = null;
-    }
-    
-    /**
-     * Calculates hashcode based on the Kerberos token
-     */
-    @Override
-    public int hashCode() {
-        final int prime = 31;
-        int result = super.hashCode();
-        result = prime * result + Arrays.hashCode(token);
-        return result;
-    }
-    
-    /**
-     * equals() is based only on the Kerberos token
-     */
-    @Override
-    public boolean equals(Object obj) {
-        if (this == obj) {
-            return true;
-        }
-        if (!super.equals(obj)) {
-            return false;
-        }
-        if (getClass() != obj.getClass()) {
-            return false;
-        }
-        KerberosServiceRequestToken other = (KerberosServiceRequestToken) obj;
-        if (!Arrays.equals(token, other.token)) {       //NOPMD
-            return false;
-        }
-        return true;
-    }
-    
-    /* (non-Javadoc)
-     * @see org.springframework.security.core.Authentication#getCredentials()
-     */
-    public Object getCredentials() {
-        return null;
-    }
-    
-    /* (non-Javadoc)
-     * @see org.springframework.security.core.Authentication#getPrincipal()
-     */
-    public Object getPrincipal() {
-        return this.principal;
-    }
-    
-    /** Returns the Kerberos token
-     */
-    public byte[] getToken() {
-        if (token != null) {
-            return Arrays.copyOf(token, token.length);
-        }
-        return null;
-    }
-}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosTokenValidator.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosTokenValidator.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosTokenValidator.java
deleted file mode 100644
index c9b0cd7..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/KerberosTokenValidator.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.kerberos;
-
-import java.security.Principal;
-import java.security.PrivilegedActionException;
-import java.util.Set;
-
-import javax.security.auth.Subject;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.login.LoginContext;
-import javax.security.auth.login.LoginException;
-
-import org.apache.wss4j.common.kerberos.KerberosServiceContext;
-import org.apache.wss4j.common.kerberos.KerberosServiceExceptionAction;
-
-/**
- * Validate a Kerberos Token
- */
-public class KerberosTokenValidator {
-
-    private static final org.slf4j.Logger LOG =
-        org.slf4j.LoggerFactory.getLogger(KerberosTokenValidator.class);
-
-    private String serviceName;
-    private CallbackHandler callbackHandler;
-    private String contextName;
-    private boolean usernameServiceNameForm;
-    private boolean spnego;
-
-    /**
-     * Get the JAAS Login context name to use.
-     * @return the JAAS Login context name to use
-     */
-    public String getContextName() {
-        return contextName;
-    }
-
-    /**
-     * Set the JAAS Login context name to use.
-     * @param contextName the JAAS Login context name to use
-     */
-    public void setContextName(String contextName) {
-        this.contextName = contextName;
-    }
-
-    /**
-     * Get the CallbackHandler to use with the LoginContext
-     * @return the CallbackHandler to use with the LoginContext
-     */
-    public CallbackHandler getCallbackHandler() {
-        return callbackHandler;
-    }
-
-    /**
-     * Set the CallbackHandler to use with the LoginContext. It can be null.
-     * @param callbackHandler the CallbackHandler to use with the LoginContext
-     */
-    public void setCallbackHandler(CallbackHandler callbackHandler) {
-        this.callbackHandler = callbackHandler;
-    }
-
-    /**
-     * The name of the service to use when contacting the KDC. This value can be null, in which
-     * case it defaults to the current principal name.
-     * @param serviceName the name of the service to use when contacting the KDC
-     */
-    public void setServiceName(String serviceName) {
-        this.serviceName = serviceName;
-    }
-
-    /**
-     * Get the name of the service to use when contacting the KDC. This value can be null, in which
-     * case it defaults to the current principal name.
-     * @return the name of the service to use when contacting the KDC
-     */
-    public String getServiceName() {
-        return serviceName;
-    }
-
-    public KerberosServiceContext validate(KerberosServiceRequestToken token) 
-        throws LoginException, PrivilegedActionException {
-        if (LOG.isDebugEnabled()) {
-            try {
-                String jaasAuth = System.getProperty("java.security.auth.login.config");
-                String krbConf = System.getProperty("java.security.krb5.conf");
-                LOG.debug("KerberosTokenValidator - Using JAAS auth login file: " + jaasAuth);
-                LOG.debug("KerberosTokenValidator - Using KRB conf file: " + krbConf);
-            } catch (SecurityException ex) {
-                LOG.debug(ex.getMessage(), ex);
-            }
-        }
-
-        // Get a TGT from the KDC using JAAS
-        LoginContext loginContext = null;
-        if (callbackHandler != null) {
-            loginContext = new LoginContext(getContextName(), callbackHandler);
-        } else {
-            loginContext = new LoginContext(getContextName());
-        }
-        loginContext.login();
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Successfully authenticated to the TGT");
-        }
-
-        // Get the service name to use - fall back on the principal
-        Subject subject = loginContext.getSubject();
-        String service = serviceName;
-        if (service == null) {
-            Set<Principal> principals = subject.getPrincipals();
-            if (principals.isEmpty()) {
-                LOG.debug("No Client principals found after login");
-                return null;
-            }
-            service = principals.iterator().next().getName();
-        }
-
-        // Validate the ticket
-        KerberosServiceExceptionAction action = 
-            new KerberosServiceExceptionAction(token.getToken(), service, 
-                                               isUsernameServiceNameForm(), spnego);
-        KerberosServiceContext krbServiceCtx = Subject.doAs(subject, action);
-
-        if (LOG.isDebugEnabled()) {
-            LOG.debug("Successfully validated a ticket");
-        }
-
-        return krbServiceCtx;
-    }
-
-    /**
-     * SPN can be configured to be in either <b>"hostbased"</b> or <b>"username"</b> form.<br/>
-     *     - <b>"hostbased"</b> - specifies that the service principal name should be interpreted
-     *      as a "host-based" name as specified in GSS API Rfc, section "4.1: Host-Based Service 
-     *      Name Form" - The service name, as it is specified in LDAP/AD, as it is listed in the
-     *      KDC.<br/>
-     *     - <b>"username"</b> - specifies that the service principal name should be interpreted
-     *      as a "username" name as specified in GSS API Rfc, section "4.2: User Name Form" 
-     *      This is usually the client username in LDAP/AD used for authentication to the KDC.
-     * 
-     * <br/><br/>Default is <b>"hostbased"</b>.
-     * 
-     * @return the isUsernameServiceNameForm
-     */
-    public boolean isUsernameServiceNameForm() {
-        return usernameServiceNameForm;
-    }
-
-    /**
-     * If true - sets the SPN form to "username"
-     * <br/>If false<b>(default)</b> - the SPN form is "hostbased"
-     * 
-     * @see KerberosSecurity#retrieveServiceTicket(String, CallbackHandler, String, boolean)
-     * 
-     * @param isUsernameServiceNameForm the isUsernameServiceNameForm to set
-     */
-    public void setUsernameServiceNameForm(boolean isUsernameServiceNameForm) {
-        this.usernameServiceNameForm = isUsernameServiceNameForm;
-    }
-
-    public boolean isSpnego() {
-        return spnego;
-    }
-
-    public void setSpnego(boolean spnego) {
-        this.spnego = spnego;
-    }
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/PassThroughKerberosClient.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/PassThroughKerberosClient.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/PassThroughKerberosClient.java
deleted file mode 100644
index d75b812..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/kerberos/PassThroughKerberosClient.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.kerberos;
-
-import java.util.Arrays;
-
-import org.apache.cxf.fediz.core.util.DOMUtils;
-import org.apache.cxf.ws.security.kerberos.KerberosClient;
-import org.apache.cxf.ws.security.tokenstore.SecurityToken;
-import org.apache.wss4j.common.util.KeyUtils;
-import org.apache.wss4j.dom.WSConstants;
-import org.apache.wss4j.dom.engine.WSSConfig;
-import org.apache.wss4j.dom.message.token.KerberosSecurity;
-import org.apache.xml.security.utils.Base64;
-
-/**
- * Override the default CXF KerberosClient just to create a BinarySecurityToken from a 
- * give Kerberos token. This is used to pass a received Kerberos token through to the 
- * STS, without retrieving a new token.
- */
-public class PassThroughKerberosClient extends KerberosClient {
-    
-    private byte[] token;
-
-    public PassThroughKerberosClient() {
-        super();
-    }
-
-    @Override
-    public SecurityToken requestSecurityToken() throws Exception {
-        KerberosSecurity bst = new KerberosSecurity(DOMUtils.createDocument());
-        bst.setValueType(WSConstants.WSS_GSS_KRB_V5_AP_REQ);
-        bst.setToken(token);
-        bst.addWSUNamespace();
-        bst.setID(WSSConfig.getNewInstance().getIdAllocator().createSecureId("BST-", bst));
-        
-        SecurityToken securityToken = new SecurityToken(bst.getID());
-        securityToken.setToken(bst.getElement());
-        securityToken.setWsuId(bst.getID());
-        securityToken.setData(bst.getToken());
-        String sha1 = Base64.encode(KeyUtils.generateDigest(bst.getToken()));
-        securityToken.setSHA1(sha1);
-        securityToken.setTokenType(bst.getValueType());
-
-        return securityToken;
-    }
-
-    public byte[] getToken() {
-        if (token != null) {
-            return Arrays.copyOf(token, token.length);
-        }
-        return null;
-    }
-
-    public void setToken(byte[] token) {
-        if (token != null) {
-            this.token = Arrays.copyOf(token, token.length);
-        } else {
-            this.token = null;
-        }
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
deleted file mode 100644
index 7c5baec..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/IdpMetadataWriter.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.metadata;
-
-import java.security.cert.X509Certificate;
-
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamWriter;
-
-import org.w3c.dom.Document;
-import org.apache.cxf.fediz.core.util.CertsUtils;
-import org.apache.cxf.fediz.core.util.SignatureUtils;
-import org.apache.cxf.fediz.service.idp.domain.Claim;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.staxutils.W3CDOMStreamWriter;
-import org.apache.wss4j.common.crypto.Crypto;
-import org.apache.wss4j.common.util.DOM2Writer;
-import org.apache.xml.security.stax.impl.util.IDGenerator;
-import org.apache.xml.security.utils.Base64;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import static org.apache.cxf.fediz.core.FedizConstants.SAML2_METADATA_NS;
-import static org.apache.cxf.fediz.core.FedizConstants.SCHEMA_INSTANCE_NS;
-import static org.apache.cxf.fediz.core.FedizConstants.WS_ADDRESSING_NS;
-import static org.apache.cxf.fediz.core.FedizConstants.WS_FEDERATION_NS;
-
-public class IdpMetadataWriter {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(IdpMetadataWriter.class);
-    
-    //CHECKSTYLE:OFF
-    public Document getMetaData(Idp config) throws RuntimeException {
-        try {
-            //Return as text/xml
-            Crypto crypto = CertsUtils.getCryptoFromFile(config.getCertificate());
-
-            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
-
-            writer.writeStartDocument("UTF-8", "1.0");
-
-            String referenceID = IDGenerator.generateID("_");
-            writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS);
-            writer.writeAttribute("ID", referenceID);
-
-            writer.writeAttribute("entityID", config.getIdpUrl().toString());
-
-            writer.writeNamespace("md", SAML2_METADATA_NS);
-            writer.writeNamespace("fed", WS_FEDERATION_NS);
-            writer.writeNamespace("wsa", WS_ADDRESSING_NS);
-            writer.writeNamespace("auth", WS_FEDERATION_NS);
-            writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
-
-            writeFederationMetadata(writer, config, crypto);
-
-            writer.writeEndElement(); // EntityDescriptor
-
-            writer.writeEndDocument();
-
-            writer.close();
-
-            if (LOG.isDebugEnabled()) {
-                String out = DOM2Writer.nodeToString(writer.getDocument());
-                LOG.debug("***************** unsigned ****************");
-                LOG.debug(out);
-                LOG.debug("***************** unsigned ****************");
-            }
-
-            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), 
-                                                          writer.getDocument(), referenceID);
-            if (result != null) {
-                return result;
-            } else {
-                throw new RuntimeException("Failed to sign the metadata document: result=null");
-            }
-        } catch (Exception e) {
-            LOG.error("Error creating service metadata information ", e);
-            throw new RuntimeException("Error creating service metadata information: " + e.getMessage());
-        }
-
-    }
-    
-    private void writeFederationMetadata(
-        XMLStreamWriter writer, Idp config, Crypto crypto
-    ) throws XMLStreamException {
-
-        writer.writeStartElement("md", "RoleDescriptor", WS_FEDERATION_NS);
-        writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:SecurityTokenServiceType");
-        writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
-        if (config.getServiceDescription() != null && config.getServiceDescription().length() > 0 ) {
-            writer.writeAttribute("ServiceDescription", config.getServiceDescription());
-        }
-        if (config.getServiceDisplayName() != null && config.getServiceDisplayName().length() > 0 ) {
-            writer.writeAttribute("ServiceDisplayName", config.getServiceDisplayName());
-        }
-
-        //http://docs.oasis-open.org/security/saml/v2.0/saml-schema-metadata-2.0.xsd
-        //missing organization, contactperson
-
-        //KeyDescriptor
-        writer.writeStartElement("", "KeyDescriptor", SAML2_METADATA_NS);
-        writer.writeAttribute("use", "signing");
-        writer.writeStartElement("", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
-        writer.writeStartElement("", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
-        writer.writeStartElement("", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");
-
-        try {
-            String keyAlias = crypto.getDefaultX509Identifier();
-            X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
-            writer.writeCharacters(Base64.encode(cert.getEncoded()));
-        } catch (Exception ex) {
-            LOG.error("Failed to add certificate information to metadata. Metadata incomplete", ex);
-        }
-
-        writer.writeEndElement(); // X509Certificate
-        writer.writeEndElement(); // X509Data
-        writer.writeEndElement(); // KeyInfo
-        writer.writeEndElement(); // KeyDescriptor
-
-
-        // SecurityTokenServiceEndpoint
-        writer.writeStartElement("fed", "SecurityTokenServiceEndpoint", WS_FEDERATION_NS);
-        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
-
-        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
-        writer.writeCharacters(config.getStsUrl().toString());
-
-        writer.writeEndElement(); // Address
-        writer.writeEndElement(); // EndpointReference
-        writer.writeEndElement(); // SecurityTokenServiceEndpoint
-
-
-        // PassiveRequestorEndpoint
-        writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
-        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
-
-        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
-        writer.writeCharacters(config.getIdpUrl().toString());
-
-        writer.writeEndElement(); // Address
-        writer.writeEndElement(); // EndpointReference
-        writer.writeEndElement(); // PassiveRequestorEndpoint
-
-
-        // create ClaimsType section
-        if (config.getClaimTypesOffered() != null && config.getClaimTypesOffered().size() > 0) {
-            writer.writeStartElement("fed", "ClaimTypesOffered", WS_FEDERATION_NS);
-            for (Claim claim : config.getClaimTypesOffered()) {
-
-                writer.writeStartElement("auth", "ClaimType", WS_FEDERATION_NS);
-                writer.writeAttribute("Uri", claim.getClaimType().toString());
-                writer.writeAttribute("Optional", "true");
-                writer.writeEndElement(); // ClaimType
-
-            }
-            writer.writeEndElement(); // ClaimTypesOffered
-        }
-
-        writer.writeEndElement(); // RoleDescriptor
-    }
-
- 
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
deleted file mode 100644
index 3118d8f..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/metadata/ServiceMetadataWriter.java
+++ /dev/null
@@ -1,214 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.metadata;
-
-import java.security.cert.X509Certificate;
-import java.util.Map;
-
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamWriter;
-
-import org.w3c.dom.Document;
-import org.apache.cxf.fediz.core.exception.ProcessingException;
-import org.apache.cxf.fediz.core.util.CertsUtils;
-import org.apache.cxf.fediz.core.util.SignatureUtils;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-import org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler;
-import org.apache.cxf.staxutils.W3CDOMStreamWriter;
-import org.apache.wss4j.common.crypto.Crypto;
-import org.apache.wss4j.common.util.DOM2Writer;
-import org.apache.xml.security.stax.impl.util.IDGenerator;
-import org.apache.xml.security.utils.Base64;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import static org.apache.cxf.fediz.core.FedizConstants.SAML2_METADATA_NS;
-import static org.apache.cxf.fediz.core.FedizConstants.SCHEMA_INSTANCE_NS;
-import static org.apache.cxf.fediz.core.FedizConstants.WS_ADDRESSING_NS;
-import static org.apache.cxf.fediz.core.FedizConstants.WS_FEDERATION_NS;
-
-public class ServiceMetadataWriter {
-    
-    private static final Logger LOG = LoggerFactory.getLogger(ServiceMetadataWriter.class);
-
-    //CHECKSTYLE:OFF
-    public Document getMetaData(Idp config, TrustedIdp serviceConfig) throws ProcessingException {
-
-        try {
-            Crypto crypto = CertsUtils.getCryptoFromFile(config.getCertificate());
-            
-            W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
-
-            writer.writeStartDocument("UTF-8", "1.0");
-
-            String referenceID = IDGenerator.generateID("_");
-            writer.writeStartElement("md", "EntityDescriptor", SAML2_METADATA_NS);
-            writer.writeAttribute("ID", referenceID);
-            
-            String serviceURL = config.getIdpUrl().toString();
-            writer.writeAttribute("entityID", config.getRealm());
-            
-            writer.writeNamespace("md", SAML2_METADATA_NS);
-            writer.writeNamespace("fed", WS_FEDERATION_NS);
-            writer.writeNamespace("wsa", WS_ADDRESSING_NS);
-            writer.writeNamespace("auth", WS_FEDERATION_NS);
-            writer.writeNamespace("xsi", SCHEMA_INSTANCE_NS);
-
-            if ("http://docs.oasis-open.org/wsfed/federation/200706".equals(serviceConfig.getProtocol())) {
-                writeFederationMetadata(writer, serviceConfig, serviceURL);
-            } else if ("urn:oasis:names:tc:SAML:2.0:profiles:SSO:browser".equals(serviceConfig.getProtocol())) {
-                writeSAMLMetadata(writer, serviceConfig, serviceURL, crypto);
-            }
-            
-            writer.writeEndElement(); // EntityDescriptor
-
-            writer.writeEndDocument();
-            
-            writer.close();
-
-            if (LOG.isDebugEnabled()) {
-                String out = DOM2Writer.nodeToString(writer.getDocument());
-                LOG.debug("***************** unsigned ****************");
-                LOG.debug(out);
-                LOG.debug("***************** unsigned ****************");
-            }
-
-            Document result = SignatureUtils.signMetaInfo(crypto, null, config.getCertificatePassword(), 
-                                                          writer.getDocument(), referenceID);
-            if (result != null) {
-                return result;
-            } else {
-                throw new RuntimeException("Failed to sign the metadata document: result=null");
-            }
-        } catch (ProcessingException e) {
-            throw e;
-        } catch (Exception e) {
-            LOG.error("Error creating service metadata information ", e);
-            throw new ProcessingException("Error creating service metadata information: " + e.getMessage());
-        }
-
-    }
-
-    private void writeFederationMetadata(
-        XMLStreamWriter writer, 
-        TrustedIdp config,
-        String serviceURL
-    ) throws XMLStreamException {
-
-        writer.writeStartElement("md", "RoleDescriptor", WS_FEDERATION_NS);
-        writer.writeAttribute(SCHEMA_INSTANCE_NS, "type", "fed:ApplicationServiceType");
-        writer.writeAttribute("protocolSupportEnumeration", WS_FEDERATION_NS);
-
-        writer.writeStartElement("fed", "ApplicationServiceEndpoint", WS_FEDERATION_NS);
-        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
-
-        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
-        writer.writeCharacters(serviceURL);
-        
-        writer.writeEndElement(); // Address
-        writer.writeEndElement(); // EndpointReference
-        writer.writeEndElement(); // ApplicationServiceEndpoint
-
-        // create target scope element
-        writer.writeStartElement("fed", "TargetScope", WS_FEDERATION_NS);
-        writer.writeEndElement(); // TargetScope
-
-        // create sign in endpoint section
-
-        writer.writeStartElement("fed", "PassiveRequestorEndpoint", WS_FEDERATION_NS);
-        writer.writeStartElement("wsa", "EndpointReference", WS_ADDRESSING_NS);
-        writer.writeStartElement("wsa", "Address", WS_ADDRESSING_NS);
-
-        writer.writeCharacters(serviceURL);
-
-        // writer.writeCharacters("http://host:port/url Issuer from config");
-        writer.writeEndElement(); // Address
-        writer.writeEndElement(); // EndpointReference
-
-        writer.writeEndElement(); // PassiveRequestorEndpoint
-        writer.writeEndElement(); // RoleDescriptor
-    }
-    
-    private void writeSAMLMetadata(
-        XMLStreamWriter writer, 
-        TrustedIdp config,
-        String serviceURL,
-        Crypto crypto
-    ) throws Exception {
-        
-        writer.writeStartElement("md", "SPSSODescriptor", SAML2_METADATA_NS);
-        boolean signRequest = 
-            isPropertyConfigured(config, TrustedIdpSAMLProtocolHandler.SIGN_REQUEST, true);
-        writer.writeAttribute("AuthnRequestsSigned", Boolean.toString(signRequest));
-        writer.writeAttribute("WantAssertionsSigned", "true");
-        writer.writeAttribute("protocolSupportEnumeration", "urn:oasis:names:tc:SAML:2.0:protocol");
-        
-        writer.writeStartElement("md", "AssertionConsumerService", SAML2_METADATA_NS);
-        writer.writeAttribute("Location", serviceURL);
-        writer.writeAttribute("index", "0");
-        writer.writeAttribute("isDefault", "true");
-        writer.writeAttribute("Binding", "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST");
-        writer.writeEndElement(); // AssertionConsumerService
-        
-        if (signRequest) {
-            writer.writeStartElement("md", "KeyDescriptor", SAML2_METADATA_NS);
-            writer.writeAttribute("use", "signing");
-            
-            writer.writeStartElement("ds", "KeyInfo", "http://www.w3.org/2000/09/xmldsig#");
-            writer.writeNamespace("ds", "http://www.w3.org/2000/09/xmldsig#");
-            writer.writeStartElement("ds", "X509Data", "http://www.w3.org/2000/09/xmldsig#");
-            writer.writeStartElement("ds", "X509Certificate", "http://www.w3.org/2000/09/xmldsig#");
-
-            // Write the Base-64 encoded certificate
-            
-            String keyAlias = crypto.getDefaultX509Identifier();
-            X509Certificate cert = CertsUtils.getX509CertificateFromCrypto(crypto, keyAlias);
-            
-            if (cert == null) {
-                throw new ProcessingException(
-                    "No signing certs were found to insert into the metadata using name: " 
-                        + keyAlias);
-            }
-            byte data[] = cert.getEncoded();
-            String encodedCertificate = Base64.encode(data);
-            writer.writeCharacters(encodedCertificate);
-            
-            writer.writeEndElement(); // X509Certificate
-            writer.writeEndElement(); // X509Data
-            writer.writeEndElement(); // KeyInfo
-            writer.writeEndElement(); // KeyDescriptor
-        }
-        
-        writer.writeEndElement(); // SPSSODescriptor
-    }
-    
-    // Is a property configured. Defaults to "true" if not
-    private boolean isPropertyConfigured(TrustedIdp trustedIdp, String property, boolean defaultValue) {
-        Map<String, String> parameters = trustedIdp.getParameters();
-        
-        if (parameters != null && parameters.containsKey(property)) {
-            return Boolean.parseBoolean(parameters.get(property));
-        }
-        
-        return defaultValue;
-    }
-
-}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java
----------------------------------------------------------------------
diff --git a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java b/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java
deleted file mode 100644
index 9b9c5cd..0000000
--- a/services/idp/src/main/java/org/apache/cxf/fediz/service/idp/model/IDPConfig.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you 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 org.apache.cxf.fediz.service.idp.model;
-
-import java.util.ArrayList;
-import java.util.Map;
-
-import org.apache.cxf.fediz.service.idp.domain.Application;
-import org.apache.cxf.fediz.service.idp.domain.Idp;
-import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
-
-public class IDPConfig extends Idp {
-
-    private static final long serialVersionUID = -5570301342547139039L;
-
-    public void setServices(Map<String, Application> applications) {
-        this.applications = new ArrayList<>(applications.values());
-    }
-    
-    public void setTrustedIdps(Map<String, TrustedIDPConfig> trustedIdps) {
-        this.trustedIdpList = new ArrayList<TrustedIdp>(trustedIdps.values());
-    }
-    
-    @Deprecated
-    public void setTrustedIDPs(Map<String, TrustedIDPConfig> trustedIdps) {
-        setTrustedIdps(trustedIdps);
-    }
-}


[17/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSUPAuthenticationProvider.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSUPAuthenticationProvider.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSUPAuthenticationProvider.java
new file mode 100644
index 0000000..6e9130c
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSUPAuthenticationProvider.java
@@ -0,0 +1,131 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+import java.util.List;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.xml.namespace.QName;
+
+import org.apache.cxf.Bus;
+import org.apache.cxf.ws.security.SecurityConstants;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.wss4j.dom.WSConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.ServletRequestAttributes;
+
+/**
+ * An authentication provider to authenticate a Username/Password to the STS
+ */
+public class STSUPAuthenticationProvider extends STSAuthenticationProvider {
+
+    private static final Logger LOG = LoggerFactory.getLogger(STSUPAuthenticationProvider.class);
+    
+    @Override
+    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
+        // We only handle UsernamePasswordAuthenticationTokens
+        if (!(authentication instanceof UsernamePasswordAuthenticationToken)) {
+            return null;
+        }
+        
+        Bus cxfBus = getBus();
+        IdpSTSClient sts = new IdpSTSClient(cxfBus);
+        sts.setAddressingNamespace("http://www.w3.org/2005/08/addressing");
+        if (tokenType != null && tokenType.length() > 0) {
+            sts.setTokenType(tokenType);
+        } else {
+            sts.setTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
+        }
+        sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
+        sts.setWsdlLocation(wsdlLocation);
+        sts.setServiceQName(new QName(namespace, wsdlService));
+        sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
+        
+        sts.getProperties().putAll(properties);
+        if (use200502Namespace) {
+            sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
+        }
+        
+        if (lifetime != null) {
+            sts.setEnableLifetime(true);
+            sts.setTtl(lifetime.intValue());
+        }
+        
+        return handleUsernamePassword((UsernamePasswordAuthenticationToken)authentication, sts);
+    }
+    
+    private Authentication handleUsernamePassword(
+        UsernamePasswordAuthenticationToken usernamePasswordToken,
+        IdpSTSClient sts
+    ) {
+        sts.getProperties().put(SecurityConstants.USERNAME, usernamePasswordToken.getName());
+        sts.getProperties().put(SecurityConstants.PASSWORD, (String)usernamePasswordToken.getCredentials());
+        
+        try {
+            
+            if (getCustomSTSParameter() != null) {
+                HttpServletRequest request = 
+                    ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
+                String authRealmParameter = request.getParameter(getCustomSTSParameter());
+                LOG.debug("Found {} custom STS parameter {}", getCustomSTSParameter(), authRealmParameter);
+                if (authRealmParameter != null) {
+                    sts.setCustomContent(authRealmParameter);
+                }
+            }
+
+            // Line below may be uncommented for debugging    
+            // setTimeout(sts.getClient(), 3600000L);
+
+            SecurityToken token = sts.requestSecurityToken(this.appliesTo);
+            
+            List<GrantedAuthority> authorities = createAuthorities(token);
+            
+            UsernamePasswordAuthenticationToken upat = 
+                new UsernamePasswordAuthenticationToken(usernamePasswordToken.getName(), 
+                                                        usernamePasswordToken.getCredentials(), 
+                                                        authorities);
+
+            STSUserDetails details = new STSUserDetails(usernamePasswordToken.getName(),
+                                                        (String)usernamePasswordToken.getCredentials(),
+                                                        authorities,
+                                                        token);
+            upat.setDetails(details);
+
+            LOG.debug("[IDP_TOKEN={}] provided for user '{}'", token.getId(), usernamePasswordToken.getName());
+            return upat;
+                                                                                           
+        } catch (Exception ex) {
+            LOG.info("Failed to authenticate user '" + usernamePasswordToken.getName() + "'", ex);
+            return null;
+        }
+        
+    }
+    
+    @Override
+    public boolean supports(Class<?> authentication) {
+        return authentication.equals(UsernamePasswordAuthenticationToken.class);
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSUserDetails.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSUserDetails.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSUserDetails.java
new file mode 100644
index 0000000..080bcb4
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/STSUserDetails.java
@@ -0,0 +1,73 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp;
+
+import java.util.Collection;
+
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.springframework.security.core.GrantedAuthority;
+import org.springframework.security.core.userdetails.User;
+
+public class STSUserDetails extends User {
+    
+    private static final long serialVersionUID = 1975259365978165675L;
+    
+    private SecurityToken token;
+    
+    public STSUserDetails(String username, String password, boolean enabled, boolean accountNonExpired,
+                          boolean credentialsNonExpired, boolean accountNonLocked,
+                          Collection<? extends GrantedAuthority> authorities) {
+        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
+    }
+    
+    public STSUserDetails(String username, String password, 
+                          Collection<? extends GrantedAuthority> authorities, SecurityToken token) {
+        super(username, password, true, true, true, true, authorities);
+        this.token = token;
+    }
+
+    public SecurityToken getSecurityToken() {
+        return this.token;
+    }
+
+    @Override
+    public boolean equals(Object object) {
+        if (!(object instanceof STSUserDetails)) {
+            return false;
+        }
+        
+        if (token != null && !token.equals(((STSUserDetails)object).token)) {
+            return false;
+        } else  if (token == null && ((STSUserDetails)object).token != null) {
+            return false;
+        }
+        
+        return super.equals(object);
+    }
+    
+    @Override
+    public int hashCode() {
+        int hashCode = 17;
+        if (token != null) {
+            hashCode *= 31 * token.hashCode();
+        }
+        
+        return hashCode * super.hashCode();
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/CacheSecurityToken.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/CacheSecurityToken.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/CacheSecurityToken.java
new file mode 100644
index 0000000..e219741
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/CacheSecurityToken.java
@@ -0,0 +1,56 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import org.apache.cxf.fediz.service.idp.STSUserDetails;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.stereotype.Component;
+import org.springframework.util.Assert;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * This class is responsible to cache the IDP token.
+ */
+@Component
+public class CacheSecurityToken {
+
+    private static final String IDP_CONFIG = "idpConfig";
+    private static final Logger LOG = LoggerFactory.getLogger(CacheSecurityToken.class);
+
+    public void submit(RequestContext context) {
+
+        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
+        Assert.isInstanceOf(STSUserDetails.class, auth.getDetails());
+        final STSUserDetails stsUserDetails = (STSUserDetails) auth.getDetails();
+        SecurityToken securityToken = stsUserDetails.getSecurityToken();
+
+        Idp idpConfig = (Idp)WebUtils.getAttributeFromFlowScope(context, IDP_CONFIG);
+
+        WebUtils.putAttributeInExternalContext(context, idpConfig.getRealm(), securityToken);
+        LOG.info("Token [IDP_TOKEN=" + securityToken.getId()
+                + "] for realm ["
+                + idpConfig.getRealm() + "] successfully cached.");
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/CommonsURLValidator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/CommonsURLValidator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/CommonsURLValidator.java
new file mode 100644
index 0000000..25780d2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/CommonsURLValidator.java
@@ -0,0 +1,52 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import org.apache.commons.validator.routines.UrlValidator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Validate a URL using Commons Validator
+ */
+@Component
+public class CommonsURLValidator {
+
+    private static final Logger LOG = LoggerFactory.getLogger(CommonsURLValidator.class);
+
+    public boolean isValid(RequestContext context, String endpointAddress)
+        throws Exception {
+        if (endpointAddress == null) {
+            return true;
+        }
+        
+        // The endpointAddress address must be a valid URL + start with http(s)
+        // Validate it first using commons-validator
+        UrlValidator urlValidator = new UrlValidator(new String[] {"http", "https"}, UrlValidator.ALLOW_LOCAL_URLS);
+        if (!urlValidator.isValid(endpointAddress)) {
+            LOG.warn("The given endpointAddress parameter {} is not a valid URL", endpointAddress);
+            return false;
+        }
+        
+        return true;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/HomeRealmReminder.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/HomeRealmReminder.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/HomeRealmReminder.java
new file mode 100644
index 0000000..c755ebf
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/HomeRealmReminder.java
@@ -0,0 +1,43 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import javax.servlet.http.Cookie;
+
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+@Component
+public class HomeRealmReminder {
+
+    public static final String FEDIZ_HOME_REALM = "FEDIZ_HOME_REALM";
+
+    public Cookie readCookie(RequestContext requestContext) {
+        return WebUtils.readCookie(requestContext, FEDIZ_HOME_REALM);
+    }
+
+    public void addCookie(RequestContext requestContext, String cookieValue) {
+        WebUtils.addCookie(requestContext, FEDIZ_HOME_REALM, cookieValue);
+    }
+
+    public void removeCookie(RequestContext requestContext) {
+        WebUtils.removeCookie(requestContext, FEDIZ_HOME_REALM);
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/IdpTokenExpiredAction.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/IdpTokenExpiredAction.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/IdpTokenExpiredAction.java
new file mode 100644
index 0000000..cbe4ee8
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/IdpTokenExpiredAction.java
@@ -0,0 +1,69 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Check to see whether the IdP Token is expired or not
+ */
+@Component
+public class IdpTokenExpiredAction {
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(IdpTokenExpiredAction.class);
+    private boolean tokenExpirationValidation = true;
+
+    public boolean isTokenExpired(String homeRealm, RequestContext context)
+        throws Exception {
+        
+        SecurityToken idpToken = 
+            (SecurityToken) WebUtils.getAttributeFromExternalContext(context, homeRealm);
+        if (idpToken == null) {
+            return true;
+        }
+        
+        if (tokenExpirationValidation && idpToken.isExpired()) {
+            LOG.info("[IDP_TOKEN=" + idpToken.getId() + "] is expired.");
+            return true;
+        }
+
+        return false;
+    }
+
+    public boolean isTokenExpirationValidation() {
+        return tokenExpirationValidation;
+    }
+
+    /**
+     * Set whether the token validation (e.g. lifetime) shall be performed on every request (true) or only 
+     * once at initial authentication (false). The default is "true" (note that the plugins default for this
+     * configuration option is "true").
+     * @param tokenExpirationValidation Whether to perform token expiration validation per request
+     */
+    public void setTokenExpirationValidation(boolean tokenExpirationValidation) {
+        this.tokenExpirationValidation = tokenExpirationValidation;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/LogoutAction.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/LogoutAction.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/LogoutAction.java
new file mode 100644
index 0000000..ae90757
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/LogoutAction.java
@@ -0,0 +1,45 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import javax.servlet.http.HttpSession;
+
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.context.SecurityContextHolder;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * This class is responsible to clear security context and invalidate the IDP session.
+ */
+@Component
+public class LogoutAction {
+
+    private static final Logger LOG = LoggerFactory.getLogger(LogoutAction.class);
+
+    public void submit(RequestContext requestContext) {
+        SecurityContextHolder.clearContext();
+        LOG.info("Security context has been cleared.");
+        HttpSession session = WebUtils.getHttpSession(requestContext);
+        session.invalidate();
+        LOG.info("Session " + session.getId() + " has been invalidated.");
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/PassiveRequestorValidator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/PassiveRequestorValidator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/PassiveRequestorValidator.java
new file mode 100644
index 0000000..3f5be36
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/PassiveRequestorValidator.java
@@ -0,0 +1,76 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import java.util.regex.Matcher;
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * This class is responsible to validate the 'wreply' parameter for WS-Federation, or else the
+ * AssertionConsumer URL address for SAML SSO, by comparing it to a regular expression.
+ */
+@Component
+public class PassiveRequestorValidator {
+
+    private static final Logger LOG = LoggerFactory.getLogger(PassiveRequestorValidator.class);
+
+    public boolean isValid(RequestContext context, String endpointAddress, String realm)
+        throws Exception {
+        if (endpointAddress == null) {
+            return true;
+        }
+        
+        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, "idpConfig");
+        Application serviceConfig = idpConfig.findApplication(realm);
+        if (serviceConfig == null) {
+            LOG.warn("No service config found for " + realm);
+            return false;
+        }
+        
+        if (serviceConfig.getPassiveRequestorEndpoint() == null 
+            && serviceConfig.getCompiledPassiveRequestorEndpointConstraint() == null) {
+            LOG.error("Either the 'passiveRequestorEndpoint' or the 'passiveRequestorEndpointConstraint' "
+                + "configuration values must be specified for the application");
+        } else if (serviceConfig.getPassiveRequestorEndpoint() != null 
+            && serviceConfig.getPassiveRequestorEndpoint().equals(endpointAddress)) {
+            LOG.debug("The supplied endpoint address {} matches the configured passive requestor endpoint value", 
+                      endpointAddress);
+            return true;
+        } else if (serviceConfig.getCompiledPassiveRequestorEndpointConstraint() != null) {
+            Matcher matcher = 
+                serviceConfig.getCompiledPassiveRequestorEndpointConstraint().matcher(endpointAddress);
+            if (matcher.matches()) {
+                return true;
+            } else {
+                LOG.error("The endpointAddress value of {} does not match any of the passive requestor values",
+                          endpointAddress);
+            }
+        }
+        
+        return false;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/ProcessHRDSExpressionAction.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/ProcessHRDSExpressionAction.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/ProcessHRDSExpressionAction.java
new file mode 100644
index 0000000..351f88c
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/ProcessHRDSExpressionAction.java
@@ -0,0 +1,72 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import javax.servlet.http.Cookie;
+
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.expression.Expression;
+import org.springframework.expression.ExpressionParser;
+import org.springframework.expression.spel.standard.SpelExpressionParser;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * This class is responsible to process Home Realm Discovery Service Expression.
+ */
+@Component
+public class ProcessHRDSExpressionAction {
+
+    private static final String IDP_CONFIG = "idpConfig";
+
+    private static final Logger LOG = LoggerFactory.getLogger(ProcessHRDSExpressionAction.class);
+
+    @Autowired
+    private HomeRealmReminder homeRealmReminder;
+
+    public String submit(RequestContext context, String homeRealm) {
+        // Check if home realm is known already
+        Cookie homeRealmCookie = homeRealmReminder.readCookie(context);
+        if (homeRealmCookie != null) {
+            LOG.debug("Home Realm Cookie set: {}", homeRealmCookie);
+            return homeRealmCookie.getValue();
+        }
+
+        // Check if custom HRDS is defined
+        Idp idpConfig = (Idp)WebUtils.getAttributeFromFlowScope(context, IDP_CONFIG);
+        String hrds = idpConfig.getHrds();
+
+        if (hrds != null) {
+            LOG.debug("HomeRealmDiscoveryService EL: {}", hrds);
+            ExpressionParser parser = new SpelExpressionParser();
+            Expression exp = parser.parseExpression(hrds);
+            String result = exp.getValue(context, String.class);
+            LOG.info("Realm resolved by HomeRealmDiscoveryService: {}", result);
+            return result;
+        }
+
+        // Return home realm parameter unchanged
+        LOG.debug("No custom homeRealm handling, using home realm parameter as provided in request: {}", homeRealm);
+        return homeRealm;
+    }
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/STSClientAction.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/STSClientAction.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/STSClientAction.java
new file mode 100644
index 0000000..0d6c37d
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/STSClientAction.java
@@ -0,0 +1,439 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.cert.X509Certificate;
+import java.util.List;
+import java.util.Map;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.xml.namespace.QName;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLStreamException;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.apache.cxf.Bus;
+import org.apache.cxf.BusFactory;
+import org.apache.cxf.binding.soap.SoapFault;
+import org.apache.cxf.fediz.core.FederationConstants;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
+import org.apache.cxf.fediz.core.util.DOMUtils;
+import org.apache.cxf.fediz.service.idp.IdpSTSClient;
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.staxutils.W3CDOMStreamWriter;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.apache.cxf.ws.security.trust.STSClient;
+import org.apache.cxf.ws.security.trust.STSUtils;
+import org.apache.wss4j.dom.WSConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * This class is responsible to ask for Security Tokens to STS.
+ */
+
+public class STSClientAction {
+
+    private static final String HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY = 
+            "http://schemas.xmlsoap.org/ws/2005/05/identity";
+
+    private static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER = 
+            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer";
+    
+    private static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_PUBLICKEY = 
+            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey";
+
+    private static final String HTTP_WWW_W3_ORG_2005_08_ADDRESSING = "http://www.w3.org/2005/08/addressing";
+
+    private static final String HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512 = 
+            "http://docs.oasis-open.org/ws-sx/ws-trust/200512/";
+    
+    private static final String HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST =
+        "http://schemas.xmlsoap.org/ws/2005/02/trust";
+
+    private static final String SECURITY_TOKEN_SERVICE = "SecurityTokenService";
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(STSClientAction.class);
+    
+    protected String namespace = HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512;
+
+    protected String wsdlLocation;
+
+    protected String wsdlEndpoint;
+    
+    protected String wsdlService = SECURITY_TOKEN_SERVICE;
+  
+    protected String tokenType = WSConstants.WSS_SAML2_TOKEN_TYPE;
+    
+    protected Map<String, Object> properties;
+    
+    protected boolean use200502Namespace;
+    
+    protected int ttl = 1800;
+    
+    protected Bus bus;
+    
+    private boolean isPortSet;
+    
+    private String keyType = HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER;
+
+
+    public String getWsdlLocation() {
+        return wsdlLocation;
+    }
+
+    public void setWsdlLocation(String wsdlLocation) {
+        this.wsdlLocation = wsdlLocation;
+        try {
+            URL url = new URL(wsdlLocation);
+            isPortSet = url.getPort() > 0;
+            if (!isPortSet) {
+                LOG.info("Port is 0 for 'wsdlLocation'. Port evaluated when processing first request.");
+            }
+        } catch (MalformedURLException e) {
+            LOG.error("Invalid Url '" + wsdlLocation + "': "  + e.getMessage());
+        }
+    }
+
+    public String getWsdlEndpoint() {
+        return wsdlEndpoint;
+    }
+
+    public void setWsdlEndpoint(String wsdlEndpoint) {
+        this.wsdlEndpoint = wsdlEndpoint;
+    }
+    
+    public String getWsdlService() {
+        return wsdlService;
+    }
+
+    public void setWsdlService(String wsdlService) {
+        this.wsdlService = wsdlService;
+    }
+    
+    public String getNamespace() {
+        return namespace;
+    }
+
+    public void setNamespace(String namespace) {
+        this.namespace = namespace;
+    }
+    
+    public void setBus(Bus bus) {
+        this.bus = bus;
+    }
+
+    public Bus getBus() {
+        // do not store a referance to the default bus
+        return (bus != null) ? bus : BusFactory.getDefaultBus();
+    }
+
+    public String getTokenType() {
+        return tokenType;
+    }
+
+    public void setTokenType(String tokenType) {
+        this.tokenType = tokenType;
+    }
+
+    public int getTtl() {
+        return ttl;
+    }
+
+    public void setTtl(int ttl) {
+        this.ttl = ttl;
+    }
+    
+    /**
+     * @param context the webflow request context
+     * @param realm The client/application realm
+     * @return a RP security token
+     * @throws Exception
+     */
+    public Element submit(RequestContext context, String realm, String homeRealm)
+        throws Exception {
+        
+        SecurityToken idpToken = getSecurityToken(context, homeRealm);
+
+        Bus cxfBus = getBus();
+        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, "idpConfig");
+
+        IdpSTSClient sts = new IdpSTSClient(cxfBus);
+        sts.setAddressingNamespace(HTTP_WWW_W3_ORG_2005_08_ADDRESSING);
+        
+        Application serviceConfig = idpConfig.findApplication(realm);
+        if (serviceConfig == null) {
+            LOG.warn("No service config found for " + realm);
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+        
+        // Parse wreq parameter - we only support parsing TokenType and KeyType for now
+        String wreq = (String)WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_REQUEST);
+        String stsTokenType = null;
+        String stsKeyType = keyType;
+        if (wreq != null) {
+            try {
+                Document wreqDoc = DOMUtils.readXml(new StringReader(wreq));
+                Element wreqElement = wreqDoc.getDocumentElement();
+                if (wreqElement != null && "RequestSecurityToken".equals(wreqElement.getLocalName())
+                    && (STSUtils.WST_NS_05_12.equals(wreqElement.getNamespaceURI())
+                        || HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST.equals(wreqElement.getNamespaceURI()))) {
+                    Element tokenTypeElement = 
+                        DOMUtils.getFirstChildWithName(wreqElement, wreqElement.getNamespaceURI(), "TokenType");
+                    if (tokenTypeElement != null) {
+                        stsTokenType = tokenTypeElement.getTextContent();
+                    }
+                    Element keyTypeElement = 
+                        DOMUtils.getFirstChildWithName(wreqElement, wreqElement.getNamespaceURI(), "KeyType");
+                    if (keyTypeElement != null) {
+                        stsKeyType = keyTypeElement.getTextContent();
+                    }
+                }
+            } catch (Exception e) {
+                LOG.warn("Error parsing 'wreq' parameter: " + e.getMessage());
+                throw new ProcessingException(TYPE.BAD_REQUEST);
+            }
+        }
+        
+        if (stsTokenType != null) {
+            sts.setTokenType(stsTokenType);
+        } else if (serviceConfig.getTokenType() != null && serviceConfig.getTokenType().length() > 0) {
+            sts.setTokenType(serviceConfig.getTokenType());
+        } else {
+            sts.setTokenType(getTokenType());
+        }
+        
+        if (serviceConfig.getPolicyNamespace() != null && serviceConfig.getPolicyNamespace().length() > 0) {
+            sts.setWspNamespace(serviceConfig.getPolicyNamespace());
+        }
+        
+        LOG.debug("TokenType {} set for realm {}", sts.getTokenType(), realm);
+        
+        sts.setKeyType(stsKeyType);
+        if (HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_PUBLICKEY.equals(stsKeyType)) {
+            HttpServletRequest servletRequest = WebUtils.getHttpServletRequest(context);
+            if (servletRequest != null) {
+                X509Certificate certs[] = 
+                    (X509Certificate[])servletRequest.getAttribute("javax.servlet.request.X509Certificate");
+                if (certs != null && certs.length > 0) {
+                    sts.setUseCertificateForConfirmationKeyInfo(true);
+                    sts.setUseKeyCertificate(certs[0]);
+                } else {
+                    LOG.info("Can't send a PublicKey KeyType as no client certs are available");
+                    sts.setKeyType(HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
+                }
+            }
+        }
+
+        processWsdlLocation(context);
+        sts.setWsdlLocation(wsdlLocation);
+        sts.setServiceQName(new QName(namespace, wsdlService));
+        sts.setEndpointQName(new QName(namespace, wsdlEndpoint));
+        if (use200502Namespace) {
+            sts.setNamespace(HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_02_TRUST);
+        }
+
+        if (serviceConfig.getRequestedClaims() != null && serviceConfig.getRequestedClaims().size() > 0) {
+            addClaims(sts, serviceConfig.getRequestedClaims());
+            LOG.debug("Requested claims set for {}", realm);
+        }
+        
+        sts.setEnableLifetime(true);
+        setLifetime(sts, serviceConfig, realm);
+        
+        sts.setEnableAppliesTo(serviceConfig.isEnableAppliesTo());
+        
+        sts.setOnBehalfOf(idpToken.getToken());
+       
+        if (properties != null) {
+            sts.setProperties(properties);
+        }
+        
+        Element rpToken = null;
+        try {
+            rpToken = sts.requestSecurityTokenResponse(realm);
+        } catch (SoapFault ex) {
+            LOG.error("Error in retrieving a token", ex.getMessage());
+            if (ex.getFaultCode() != null 
+                && "RequestFailed".equals(ex.getFaultCode().getLocalPart())) {
+                throw new ProcessingException(TYPE.BAD_REQUEST);
+            }
+            throw ex;
+        }
+
+        if (LOG.isInfoEnabled()) {
+            String id = getIdFromToken(rpToken);
+            
+            LOG.info("[RP_TOKEN={}] successfully created for realm [{}] on behalf of [IDP_TOKEN={}]",
+                     id, realm, idpToken.getId());
+        }
+        return rpToken;
+    }
+    
+    private String getIdFromToken(Element token) throws IOException, XMLStreamException {
+        if (token != null) {
+            NodeList nd = token.getElementsByTagNameNS(WSConstants.SAML2_NS, "Assertion");
+            
+            String identifier = "ID";
+            if (nd.getLength() == 0) {
+                nd = token.getElementsByTagNameNS(WSConstants.SAML_NS, "Assertion");
+                identifier = "AssertionID";
+            }
+            
+            if (nd.getLength() > 0) {
+                Element e = (Element) nd.item(0);
+                if (e.hasAttributeNS(null, identifier)) {
+                    return e.getAttributeNS(null, identifier);
+                }
+            }
+        }
+        
+        return "";
+    }
+
+    private SecurityToken getSecurityToken(RequestContext context, String homeRealm) throws ProcessingException {
+
+        SecurityToken idpToken = (SecurityToken) WebUtils.getAttributeFromFlowScope(context, "idpToken");
+        if (idpToken != null) {
+            LOG.debug("[IDP_TOKEN={} successfully retrieved from cache for home realm [{}]",
+                          idpToken.getId(), homeRealm);
+        } else {
+            LOG.error("IDP_TOKEN not found");
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+        return idpToken;
+    }
+    
+
+    private void processWsdlLocation(RequestContext context) {
+        if (!isPortSet) {
+            try {
+                URL url = new URL(this.wsdlLocation);
+                URL updatedUrl = new URL(url.getProtocol(), url.getHost(),
+                                         WebUtils.getHttpServletRequest(context).getLocalPort(), url.getFile());
+                
+                setSTSWsdlUrl(updatedUrl.toString());
+                LOG.info("STS WSDL URL updated to {}", updatedUrl.toString());
+            } catch (MalformedURLException e) {
+                LOG.error("Invalid Url '{}': {}", this.wsdlLocation, e.getMessage());
+            }
+        }
+    }
+
+    private void addClaims(STSClient sts, List<RequestClaim> requestClaimList)
+        throws ParserConfigurationException, XMLStreamException {
+        
+        Element claims = createClaimsElement(requestClaimList);
+        if (claims != null) {
+            sts.setClaims(claims);
+        }
+    }
+
+    private Element createClaimsElement(List<RequestClaim> realmClaims)
+        throws ParserConfigurationException, XMLStreamException {
+        if (realmClaims == null || realmClaims.size() == 0) {
+            return null;
+        }
+
+        W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
+        writer.writeStartElement("wst", "Claims", STSUtils.WST_NS_05_12);
+        writer.writeNamespace("wst", STSUtils.WST_NS_05_12);
+        writer.writeNamespace("ic",
+                HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY);
+        writer.writeAttribute("Dialect",
+                HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY);
+
+        if (realmClaims.size() > 0) {
+            for (RequestClaim item : realmClaims) {
+                LOG.debug("  {}", item.getClaimType().toString());
+                writer.writeStartElement("ic", "ClaimType",
+                        HTTP_SCHEMAS_XMLSOAP_ORG_WS_2005_05_IDENTITY);
+                writer.writeAttribute("Uri", item.getClaimType().toString());
+                writer.writeAttribute("Optional", Boolean.toString(item.isOptional())); 
+                writer.writeEndElement();
+            }
+        }
+
+        writer.writeEndElement();
+
+        return writer.getDocument().getDocumentElement();
+    }
+    
+    private synchronized void setSTSWsdlUrl(String wsdlUrl) {
+        this.wsdlLocation = wsdlUrl;
+        this.isPortSet = true;
+    }
+
+    public String getKeyType() {
+        return keyType;
+    }
+
+    public void setKeyType(String keyType) {
+        this.keyType = keyType;
+    }
+
+    public boolean isUse200502Namespace() {
+        return use200502Namespace;
+    }
+
+    public void setUse200502Namespace(boolean use200502Namespace) {
+        this.use200502Namespace = use200502Namespace;
+    }
+
+    private void setLifetime(STSClient sts, Application serviceConfig, String wtrealm) {
+        if (serviceConfig.getLifeTime() > 0) {
+            try {
+                int lifetime = serviceConfig.getLifeTime();
+                sts.setTtl(lifetime);
+                sts.setEnableLifetime(lifetime > 0);
+                LOG.debug("Lifetime set to {} seconds for realm {}", serviceConfig.getLifeTime(), wtrealm);
+            } catch (NumberFormatException ex) {
+                LOG.warn("Invalid lifetime configured for service provider " + wtrealm);
+                sts.setTtl(this.ttl);
+                sts.setEnableLifetime(this.ttl > 0);
+            }
+        } else {
+            sts.setTtl(this.ttl);
+            sts.setEnableLifetime(this.ttl > 0);
+            if (LOG.isDebugEnabled()) {
+                LOG.debug("Lifetime set to {} seconds for realm {}", this.ttl, wtrealm);
+            }
+        }
+    }
+
+    public Map<String, Object> getProperties() {
+        return properties;
+    }
+
+    public void setProperties(Map<String, Object> properties) {
+        this.properties = properties;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/SigninParametersCacheAction.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/SigninParametersCacheAction.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/SigninParametersCacheAction.java
new file mode 100644
index 0000000..bbecc5a
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/SigninParametersCacheAction.java
@@ -0,0 +1,185 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import org.apache.cxf.fediz.core.FederationConstants;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.samlsso.SAMLAuthnRequest;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+@Component
+public class SigninParametersCacheAction {
+
+    public static final String ACTIVE_APPLICATIONS = "realmConfigMap";
+
+    private static final Logger LOG = LoggerFactory.getLogger(SigninParametersCacheAction.class);
+
+    public void store(RequestContext context, String protocol) {
+        Map<String, Object> signinParams = new HashMap<>();
+        String uuidKey = UUID.randomUUID().toString();
+
+        Object value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.HOME_REALM);
+        if (value != null) {
+            signinParams.put(IdpConstants.HOME_REALM, value);
+        }
+        value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.CONTEXT);
+        if (value != null) {
+            signinParams.put(IdpConstants.CONTEXT, value);
+        }
+        value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.REALM);
+        if (value != null) {
+            signinParams.put(IdpConstants.REALM, value);
+        }
+        value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.RETURN_ADDRESS);
+        if (value != null) {
+            signinParams.put(IdpConstants.RETURN_ADDRESS, value);
+        }
+        value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.RETURN_ADDRESS);
+        if (value != null) {
+            signinParams.put(IdpConstants.RETURN_ADDRESS, value);
+        }
+
+        if ("samlsso".equals(protocol)) {
+            value = WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
+            if (value != null) {
+                signinParams.put(IdpConstants.SAML_AUTHN_REQUEST, value);
+            }
+        }
+
+        WebUtils.putAttributeInExternalContext(context, uuidKey, signinParams);
+
+        LOG.debug("SignIn parameters cached: {}", signinParams.toString());
+        WebUtils.putAttributeInFlowScope(context, IdpConstants.TRUSTED_IDP_CONTEXT, uuidKey);
+        LOG.info("SignIn parameters cached and context set to [" + uuidKey + "].");
+    }
+
+    public void restore(RequestContext context, String contextKey, String protocol) {
+
+        if (contextKey != null) {
+            @SuppressWarnings("unchecked")
+            Map<String, Object> signinParams =
+                (Map<String, Object>)WebUtils.getAttributeFromExternalContext(context, contextKey);
+
+            if (signinParams != null) {
+                LOG.debug("SignIn parameters restored: {}", signinParams.toString());
+
+                String value = (String)signinParams.get(IdpConstants.HOME_REALM);
+                if (value != null) {
+                    WebUtils.putAttributeInFlowScope(context, IdpConstants.HOME_REALM, value);
+                }
+                value = (String)signinParams.get(IdpConstants.REALM);
+                if (value != null) {
+                    WebUtils.putAttributeInFlowScope(context, IdpConstants.REALM, value);
+                }
+                value = (String)signinParams.get(IdpConstants.RETURN_ADDRESS);
+                if (value != null) {
+                    WebUtils.putAttributeInFlowScope(context, IdpConstants.RETURN_ADDRESS, value);
+                }
+                value = (String)signinParams.get(IdpConstants.CONTEXT);
+                if (value != null) {
+                    WebUtils.putAttributeInFlowScope(context, IdpConstants.CONTEXT, value);
+                }
+
+                if ("wsfed".equals(protocol)) {
+
+                    WebUtils.removeAttributeFromFlowScope(context, FederationConstants.PARAM_CONTEXT);
+                    LOG.info("SignIn parameters restored and " + FederationConstants.PARAM_CONTEXT + "["
+                        + contextKey + "] cleared.");
+
+                } else if ("samlsso".equals(protocol)) {
+                    SAMLAuthnRequest authnRequest =
+                        (SAMLAuthnRequest)signinParams.get(IdpConstants.SAML_AUTHN_REQUEST);
+                    if (authnRequest != null) {
+                        WebUtils.putAttributeInFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST, authnRequest);
+                    }
+                }
+
+            }  else {
+                LOG.debug("Error in restoring security context");
+            }
+
+            WebUtils.removeAttributeFromFlowScope(context, contextKey);
+        } else {
+            LOG.debug("Error in restoring security context");
+        }
+    }
+
+    public void storeRPConfigInSession(RequestContext context) throws ProcessingException {
+
+        String wtrealm = (String)WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_TREALM);
+        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(context, IdpConstants.IDP_CONFIG);
+        if (wtrealm == null || idpConfig == null) {
+            return;
+        }
+
+        Application serviceConfig = idpConfig.findApplication(wtrealm);
+        if (serviceConfig != null) {
+            if (serviceConfig.getPassiveRequestorEndpoint() == null) {
+                String url = guessPassiveRequestorURL(context, wtrealm);
+                serviceConfig.setPassiveRequestorEndpoint(url);
+            }
+
+            @SuppressWarnings("unchecked")
+            Map<String, Application> realmConfigMap =
+                    (Map<String, Application>)WebUtils
+                            .getAttributeFromExternalContext(context, ACTIVE_APPLICATIONS);
+
+            if (realmConfigMap == null) {
+                realmConfigMap = new HashMap<>();
+                WebUtils.putAttributeInExternalContext(context, ACTIVE_APPLICATIONS, realmConfigMap);
+            }
+
+            if (realmConfigMap.get(wtrealm) == null) {
+                realmConfigMap.put(wtrealm, serviceConfig);
+            }
+        }
+    }
+
+    protected String guessPassiveRequestorURL(RequestContext context, String wtrealm) throws ProcessingException {
+        String url = (String)WebUtils.getAttributeFromFlowScope(context, FederationConstants.PARAM_REPLY);
+        try {
+            //basic check if the url is correctly formed
+            new URL(url);
+        } catch (Exception e) {
+            url = null;
+        }
+        if (url == null) {
+            url = wtrealm;
+            try {
+                //basic check if the url is correctly formed
+                new URL(url);
+            } catch (Exception e) {
+                throw new ProcessingException(e.getMessage(), e, ProcessingException.TYPE.INVALID_REQUEST);
+            }
+        }
+        return url;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/TokenSerializer.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/TokenSerializer.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/TokenSerializer.java
new file mode 100644
index 0000000..4665cb5
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/TokenSerializer.java
@@ -0,0 +1,62 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import java.io.StringWriter;
+
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+
+import org.w3c.dom.Element;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Serialize the RP Token
+ */
+@Component
+public class TokenSerializer {
+
+    private static final Logger LOG = LoggerFactory.getLogger(TokenSerializer.class);
+
+    public String serialize(RequestContext context, Element rpToken) {
+        if (rpToken != null) {
+            StringWriter sw = new StringWriter();
+            try {
+                Transformer t = TransformerFactory.newInstance().newTransformer();
+                t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
+                t.transform(new DOMSource(rpToken), new StreamResult(sw));
+            } catch (TransformerException te) {
+                LOG.warn("nodeToString Transformer Exception");
+            }
+            String serializedToken = sw.toString();
+    
+            return org.apache.commons.lang3.StringEscapeUtils.escapeXml11(serializedToken);
+        }
+        
+        return null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/TrustedIdpProtocolAction.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/TrustedIdpProtocolAction.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/TrustedIdpProtocolAction.java
new file mode 100644
index 0000000..9ea2de2
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/TrustedIdpProtocolAction.java
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans;
+
+import java.net.URL;
+
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.domain.TrustedIdp;
+import org.apache.cxf.fediz.service.idp.protocols.ProtocolController;
+import org.apache.cxf.fediz.service.idp.spi.TrustedIdpProtocolHandler;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.ws.security.tokenstore.SecurityToken;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * This class is responsible to map the sign in request/response when calling a trusted third party IdP
+ */
+@Component
+public class TrustedIdpProtocolAction {
+
+    private static final Logger LOG = LoggerFactory.getLogger(TrustedIdpProtocolAction.class);
+    
+    private static final String IDP_CONFIG = "idpConfig";
+    
+    @Autowired
+    // Qualifier workaround. See http://www.jayway.com/2013/11/03/spring-and-autowiring-of-generic-types/
+    @Qualifier("trustedIdpProtocolControllerImpl")
+    private ProtocolController<TrustedIdpProtocolHandler> trustedIdpProtocolHandlers;
+    
+    public String mapSignInRequest(RequestContext requestContext, String trustedIdpRealm) {
+        LOG.info("Prepare redirect to Trusted IDP '{}'", trustedIdpRealm);
+        
+        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(requestContext, IDP_CONFIG);
+        
+        TrustedIdp trustedIdp = idpConfig.findTrustedIdp(trustedIdpRealm);
+        if (trustedIdp == null) {
+            LOG.error("TrustedIdp '{}' not configured", trustedIdpRealm);
+            throw new IllegalStateException("TrustedIdp '" + trustedIdpRealm + "'");
+        }
+        
+        String protocol = trustedIdp.getProtocol();
+        LOG.debug("TrustedIdp '{}' supports protocol {}", trustedIdpRealm, protocol);
+        
+        TrustedIdpProtocolHandler protocolHandler = trustedIdpProtocolHandlers.getProtocolHandler(protocol);
+        if (protocolHandler == null) {
+            LOG.error("No ProtocolHandler found for {}", protocol);
+            throw new IllegalStateException("No ProtocolHandler found for '" + protocol + "'");
+        }
+        URL redirectUrl = protocolHandler.mapSignInRequest(requestContext, idpConfig, trustedIdp);
+        LOG.info("Redirect url {}", redirectUrl.toString());
+        return redirectUrl.toString();
+    }
+    
+    public SecurityToken mapSignInResponse(RequestContext requestContext, String trustedIdpRealm) {
+        LOG.info("Prepare validate SignInResponse of Trusted IDP '{}'", trustedIdpRealm);
+        
+        Idp idpConfig = (Idp) WebUtils.getAttributeFromFlowScope(requestContext, IDP_CONFIG);
+        
+        TrustedIdp trustedIdp = idpConfig.findTrustedIdp(trustedIdpRealm);
+        if (trustedIdp == null) {
+            LOG.error("TrustedIdp '{}' not configured", trustedIdpRealm);
+            throw new IllegalStateException("TrustedIdp '" + trustedIdpRealm + "'");
+        }
+        
+        String protocol = trustedIdp.getProtocol();
+        LOG.debug("TrustedIdp '{}' supports protocol {}", trustedIdpRealm, protocol);
+        
+        TrustedIdpProtocolHandler protocolHandler = trustedIdpProtocolHandlers.getProtocolHandler(protocol);
+        if (protocolHandler == null) {
+            LOG.error("No ProtocolHandler found for {}", protocol);
+            throw new IllegalStateException("No ProtocolHandler found for '" + protocol + "'");
+        }
+        SecurityToken token = protocolHandler.mapSignInResponse(requestContext, idpConfig, trustedIdp);
+        if (token != null) {
+            LOG.info("SignInResponse successfully validated and SecurityToken created");
+        }
+        return token;
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
new file mode 100644
index 0000000..53feb73
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/AuthnRequestParser.java
@@ -0,0 +1,388 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans.samlsso;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URLEncoder;
+import java.nio.charset.StandardCharsets;
+import java.security.cert.X509Certificate;
+import java.util.Collections;
+
+import org.w3c.dom.Document;
+
+import org.apache.cxf.common.util.Base64Utility;
+import org.apache.cxf.fediz.core.exception.ProcessingException;
+import org.apache.cxf.fediz.core.exception.ProcessingException.TYPE;
+import org.apache.cxf.fediz.core.util.CertsUtils;
+import org.apache.cxf.fediz.service.idp.IdpConstants;
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.samlsso.SAMLAuthnRequest;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.apache.cxf.rs.security.saml.DeflateEncoderDecoder;
+import org.apache.cxf.rs.security.saml.sso.SSOConstants;
+import org.apache.cxf.staxutils.StaxUtils;
+import org.apache.wss4j.common.crypto.CertificateStore;
+import org.apache.wss4j.common.crypto.Crypto;
+import org.apache.wss4j.common.ext.WSSecurityException;
+import org.apache.wss4j.common.saml.OpenSAMLUtil;
+import org.apache.wss4j.common.saml.SAMLKeyInfo;
+import org.apache.wss4j.common.saml.SAMLUtil;
+import org.apache.wss4j.common.util.DOM2Writer;
+import org.apache.wss4j.dom.WSDocInfo;
+import org.apache.wss4j.dom.engine.WSSConfig;
+import org.apache.wss4j.dom.handler.RequestData;
+import org.apache.wss4j.dom.saml.WSSSAMLKeyInfoProcessor;
+import org.apache.wss4j.dom.validate.Credential;
+import org.apache.wss4j.dom.validate.SignatureTrustValidator;
+import org.apache.wss4j.dom.validate.Validator;
+import org.apache.xml.security.utils.Base64;
+import org.opensaml.saml.saml2.core.AuthnRequest;
+import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator;
+import org.opensaml.security.credential.BasicCredential;
+import org.opensaml.security.x509.BasicX509Credential;
+import org.opensaml.xmlsec.signature.KeyInfo;
+import org.opensaml.xmlsec.signature.Signature;
+import org.opensaml.xmlsec.signature.support.SignatureException;
+import org.opensaml.xmlsec.signature.support.SignatureValidator;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Parse the received SAMLRequest into an OpenSAML AuthnRequest
+ */
+@Component
+public class AuthnRequestParser {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AuthnRequestParser.class);
+    private boolean supportDeflateEncoding;
+    private boolean requireSignature = true;
+
+    public void parseSAMLRequest(RequestContext context, Idp idp, String samlRequest,
+                                 String signature, String relayState) throws ProcessingException {
+        LOG.debug("Received SAML Request: {}", samlRequest);
+        
+        if (samlRequest == null) {
+            WebUtils.removeAttribute(context, IdpConstants.SAML_AUTHN_REQUEST);
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        } else {
+            AuthnRequest parsedRequest = null;
+            try {
+                parsedRequest = extractRequest(context, samlRequest);
+            } catch (Exception ex) {
+                LOG.warn("Error parsing request: {}", ex.getMessage());
+                throw new ProcessingException(TYPE.BAD_REQUEST);
+            }
+            
+            // Store various attributes from the AuthnRequest
+            SAMLAuthnRequest authnRequest = new SAMLAuthnRequest(parsedRequest);
+            WebUtils.putAttributeInFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST, authnRequest);
+            
+            validateSignature(context, parsedRequest, idp, signature, relayState, 
+                              samlRequest, authnRequest.getIssuer());
+            validateRequest(parsedRequest);
+            
+            LOG.debug("SAML Request with id '{}' successfully parsed", parsedRequest.getID());
+        }
+    }
+    
+    public String retrieveRealm(RequestContext context) {
+        SAMLAuthnRequest authnRequest = 
+            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
+        
+        if (authnRequest != null) {
+            String issuer = authnRequest.getIssuer();
+            LOG.debug("Parsed SAML AuthnRequest Issuer: {}", issuer);
+            return issuer;
+        }
+        
+        LOG.debug("No AuthnRequest available to be parsed");
+        return null;
+    }
+    
+    public String retrieveConsumerURL(RequestContext context) {
+        SAMLAuthnRequest authnRequest = 
+            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
+
+        if (authnRequest != null && authnRequest.getConsumerServiceURL() != null) {
+            String consumerURL = authnRequest.getConsumerServiceURL();
+            LOG.debug("Parsed SAML AuthnRequest Consumer URL: {}", consumerURL);
+            return consumerURL;
+        }
+        
+        LOG.debug("No AuthnRequest available to be parsed");
+        return null;
+    }
+    
+    public String retrieveRequestId(RequestContext context) {
+        SAMLAuthnRequest authnRequest = 
+            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
+
+        if (authnRequest != null && authnRequest.getRequestId() != null) {
+            String id = authnRequest.getRequestId();
+            LOG.debug("Parsed SAML AuthnRequest Id: {}", id);
+            return id;
+        }
+        
+        LOG.debug("No AuthnRequest available to be parsed");
+        return null;
+    }
+    
+    public String retrieveRequestIssuer(RequestContext context) {
+        SAMLAuthnRequest authnRequest = 
+            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
+
+        if (authnRequest != null && authnRequest.getIssuer() != null) {
+            String issuer = authnRequest.getIssuer();
+            LOG.debug("Parsed SAML AuthnRequest Issuer: {}", issuer);
+            return issuer;
+        }
+        
+        LOG.debug("No AuthnRequest available to be parsed");
+        return null;
+    }
+    
+    public boolean isForceAuthentication(RequestContext context) {
+        SAMLAuthnRequest authnRequest = 
+            (SAMLAuthnRequest)WebUtils.getAttributeFromFlowScope(context, IdpConstants.SAML_AUTHN_REQUEST);
+        if (authnRequest != null) {
+            return authnRequest.isForceAuthn();
+        }
+        
+        LOG.debug("No AuthnRequest available to be parsed");
+        return false;
+    }
+    
+    protected AuthnRequest extractRequest(RequestContext context, String samlRequest) throws Exception {
+        byte[] deflatedToken = Base64Utility.decode(samlRequest);
+        String httpMethod = WebUtils.getHttpServletRequest(context).getMethod();
+        
+        InputStream tokenStream = supportDeflateEncoding || "GET".equals(httpMethod)
+             ? new DeflateEncoderDecoder().inflateToken(deflatedToken)
+                 : new ByteArrayInputStream(deflatedToken);
+
+        Document responseDoc = StaxUtils.read(new InputStreamReader(tokenStream, "UTF-8"));
+        AuthnRequest request = 
+            (AuthnRequest)OpenSAMLUtil.fromDom(responseDoc.getDocumentElement());
+        if (LOG.isDebugEnabled()) {
+            LOG.debug(DOM2Writer.nodeToString(responseDoc));
+        }
+        return request;
+    }
+    
+    public boolean isSupportDeflateEncoding() {
+        return supportDeflateEncoding;
+    }
+
+    public void setSupportDeflateEncoding(boolean supportDeflateEncoding) {
+        this.supportDeflateEncoding = supportDeflateEncoding;
+    }
+    
+    private void validateRequest(AuthnRequest parsedRequest) throws ProcessingException {
+        if (parsedRequest.getIssuer() == null) {
+            LOG.debug("No Issuer is present in the AuthnRequest");
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+        
+        String format = parsedRequest.getIssuer().getFormat();
+        if (format != null
+            && !"urn:oasis:names:tc:SAML:2.0:nameid-format:entity".equals(format)) {
+            LOG.debug("An invalid Format attribute was received: {}", format);
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+        
+        // No SubjectConfirmation Elements are allowed
+        if (parsedRequest.getSubject() != null 
+            && parsedRequest.getSubject().getSubjectConfirmations() != null
+            && !parsedRequest.getSubject().getSubjectConfirmations().isEmpty()) {
+            LOG.debug("An invalid SubjectConfirmation Element was received");
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+    }
+    
+    private void validateSignature(RequestContext context, AuthnRequest authnRequest, Idp idp, 
+                                   String signature, String relayState, String samlRequest, 
+                                   String realm) throws ProcessingException {
+        try {
+            if (authnRequest.isSigned()) {
+                // Check destination
+                checkDestination(context, authnRequest);
+                
+                // Check signature
+                X509Certificate validatingCert = getValidatingCertificate(idp, realm);
+                Crypto issuerCrypto = 
+                    new CertificateStore(Collections.singletonList(validatingCert).toArray(new X509Certificate[0]));
+                validateAuthnRequestSignature(authnRequest.getSignature(), issuerCrypto);
+            } else if (signature != null) {
+                // Check destination
+                checkDestination(context, authnRequest);
+                
+                // Check signature
+                X509Certificate validatingCert = getValidatingCertificate(idp, realm);
+                
+                java.security.Signature sig = java.security.Signature.getInstance("SHA1withRSA");
+                sig.initVerify(validatingCert);
+                
+                // Recreate request to sign
+                String requestToSign = SSOConstants.SAML_REQUEST + "=" + URLEncoder.encode(samlRequest, "UTF-8")
+                     + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG 
+                     + "=" + URLEncoder.encode(SSOConstants.RSA_SHA1, StandardCharsets.UTF_8.name());
+                
+                sig.update(requestToSign.getBytes(StandardCharsets.UTF_8));
+                
+                if (!sig.verify(Base64.decode(signature))) {
+                    LOG.debug("Signature validation failed");
+                    throw new ProcessingException(TYPE.BAD_REQUEST);
+                }
+            } else if (requireSignature) {
+                LOG.debug("No signature is present, therefore the request is rejected");
+                throw new ProcessingException(TYPE.BAD_REQUEST);
+            } else {
+                LOG.debug("No signature is present, but this is allowed by configuration");
+            }
+        } catch (Exception ex) {
+            LOG.debug("Error validating SAML Signature", ex);
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+    }
+    
+    private X509Certificate getValidatingCertificate(Idp idp, String realm) 
+        throws Exception {
+        Application serviceConfig = idp.findApplication(realm);
+        if (serviceConfig == null || serviceConfig.getValidatingCertificate() == null) {
+            LOG.debug("No validating certificate found for realm {}", realm);
+            throw new ProcessingException(TYPE.ISSUER_NOT_TRUSTED);
+        }
+        
+        return CertsUtils.parseX509Certificate(serviceConfig.getValidatingCertificate());
+    }
+    
+    private void checkDestination(RequestContext context, AuthnRequest authnRequest) throws ProcessingException {
+        // Check destination
+        String destination = authnRequest.getDestination();
+        LOG.debug("Validating destination: {}", destination);
+        
+        String localAddr = WebUtils.getHttpServletRequest(context).getRequestURL().toString();
+        if (destination == null || !localAddr.startsWith(destination)) {
+            LOG.debug("The destination {} does not match the local address {}", destination, localAddr);
+            throw new ProcessingException(TYPE.BAD_REQUEST);
+        }
+    }
+    
+    /**
+     * Validate the AuthnRequest signature
+     */
+    private void validateAuthnRequestSignature(
+        Signature signature,
+        Crypto sigCrypto
+    ) throws WSSecurityException {
+        RequestData requestData = new RequestData();
+        requestData.setSigVerCrypto(sigCrypto);
+        WSSConfig wssConfig = WSSConfig.getNewInstance();
+        requestData.setWssConfig(wssConfig);
+        // requestData.setCallbackHandler(callbackHandler);
+
+        SAMLKeyInfo samlKeyInfo = null;
+
+        KeyInfo keyInfo = signature.getKeyInfo();
+        if (keyInfo != null) {
+            try {
+                Document doc = signature.getDOM().getOwnerDocument();
+                samlKeyInfo =
+                    SAMLUtil.getCredentialFromKeyInfo(
+                        keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(requestData, new WSDocInfo(doc)), sigCrypto
+                    );
+            } catch (WSSecurityException ex) {
+                LOG.debug("Error in getting KeyInfo from SAML AuthnRequest: {}", ex.getMessage(), ex);
+                throw ex;
+            }
+        }
+        
+        if (samlKeyInfo == null) {
+            LOG.debug("No KeyInfo supplied in the AuthnRequest signature");
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+
+        // Validate Signature against profiles
+        validateSignatureAgainstProfiles(signature, samlKeyInfo);
+
+        // Now verify trust on the signature
+        Credential trustCredential = new Credential();
+        trustCredential.setPublicKey(samlKeyInfo.getPublicKey());
+        trustCredential.setCertificates(samlKeyInfo.getCerts());
+
+        try {
+            Validator signatureValidator = new SignatureTrustValidator();
+            signatureValidator.validate(trustCredential, requestData);
+        } catch (WSSecurityException e) {
+            LOG.debug("Error in validating signature on SAML AuthnRequest: {}", e.getMessage(), e);
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+    }
+
+    /**
+     * Validate a signature against the profiles
+     */
+    private void validateSignatureAgainstProfiles(
+        Signature signature,
+        SAMLKeyInfo samlKeyInfo
+    ) throws WSSecurityException {
+        // Validate Signature against profiles
+        SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator();
+        try {
+            validator.validate(signature);
+        } catch (SignatureException ex) {
+            LOG.debug("Error in validating the SAML Signature: {}", ex.getMessage(), ex);
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+
+        BasicCredential credential = null;
+        if (samlKeyInfo.getCerts() != null) {
+            credential = new BasicX509Credential(samlKeyInfo.getCerts()[0]);
+        } else if (samlKeyInfo.getPublicKey() != null) {
+            credential = new BasicCredential(samlKeyInfo.getPublicKey());
+        } else {
+            LOG.debug("Can't get X509Certificate or PublicKey to verify signature");
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+        try {
+            SignatureValidator.validate(signature, credential);
+        } catch (SignatureException ex) {
+            LOG.debug("Error in validating the SAML Signature: {}", ex.getMessage(), ex);
+            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
+        }
+    }
+
+    public boolean isRequireSignature() {
+        return requireSignature;
+    }
+
+    /**
+     * Whether to require a signature or not on the AuthnRequest
+     * @param requireSignature
+     */
+    public void setRequireSignature(boolean requireSignature) {
+        this.requireSignature = requireSignature;
+    }
+    
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/LocalRedirectCreator.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/LocalRedirectCreator.java b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/LocalRedirectCreator.java
new file mode 100644
index 0000000..9dfd626
--- /dev/null
+++ b/services/idp-core/src/main/java/org/apache/cxf/fediz/service/idp/beans/samlsso/LocalRedirectCreator.java
@@ -0,0 +1,54 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.beans.samlsso;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+
+import org.apache.cxf.fediz.service.idp.domain.Idp;
+import org.apache.cxf.fediz.service.idp.util.WebUtils;
+import org.springframework.stereotype.Component;
+import org.springframework.webflow.execution.RequestContext;
+
+/**
+ * Parse the parameters to create the URL for local redirection
+ */
+@Component
+public class LocalRedirectCreator {
+
+    public String createRedirectURL(RequestContext context, Idp idp) throws UnsupportedEncodingException {
+        StringBuilder redirectURL = new StringBuilder();
+        redirectURL.append(idp.getIdpUrl().toString()).append("?");
+        
+        String relayState = (String)WebUtils.getAttributeFromFlowScope(context, "RelayState");
+        redirectURL.append("RelayState=").append(relayState).append("&");
+        String samlRequest = (String)WebUtils.getAttributeFromFlowScope(context, "SAMLRequest");
+        redirectURL.append("SAMLRequest=").append(URLEncoder.encode(samlRequest, "UTF-8"));
+        
+        String signature = (String)WebUtils.getAttributeFromFlowScope(context, "Signature");
+        if (signature != null) {
+            redirectURL.append("&");
+            redirectURL.append("Signature=").append(URLEncoder.encode(signature, "UTF-8"));
+        }
+        
+        return redirectURL.toString();
+    }
+    
+    
+}


[10/19] cxf-fediz git commit: FEDIZ-155 - Move .java components out of idp webapp and into a separate JAR

Posted by co...@apache.org.
http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/flows/signin-request.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/flows/signin-request.xml b/services/idp-core/src/main/webapp/WEB-INF/flows/signin-request.xml
new file mode 100644
index 0000000..2a7b125
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/flows/signin-request.xml
@@ -0,0 +1,171 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<flow xmlns="http://www.springframework.org/schema/webflow"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/webflow
+        http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
+
+    <input name="idpConfig" />
+    <input name="wfresh" />
+    <input name="saml_authn_request" />
+    <input name="realm" />
+    <input name="home_realm" />
+    <input name="protocol" />
+    <input name="return_address" />
+    <input name="request_context" />
+    
+    <!-- ===== Home Realm Discovery ===== -->
+    
+    <decision-state id="processHRDSExpression">
+        <on-entry>
+            <evaluate expression="processHRDSExpressionAction.submit(flowRequestContext, flowScope.home_realm)" 
+                      result="flowScope.home_realm" />
+        </on-entry>
+        <if test="flowScope.home_realm == null or flowScope.home_realm.trim().isEmpty()"
+            then="provideIDPListForUser" else="checkIsThisIDP" />
+    </decision-state>
+    
+    <decision-state id="provideIDPListForUser">
+        <if test="flowScope.idpConfig.trustedIdps == null or idpConfig.trustedIdps.isEmpty()"
+            then="checkDefaultToThisIDP" />
+        <if test="flowScope.idpConfig.isProvideIdpList() == false"
+            then="checkDefaultToThisIDP" else="showIDPList" />
+    </decision-state>
+    
+    <decision-state id="checkDefaultToThisIDP">
+        <if test="flowScope.idpConfig.isUseCurrentIdp()" then="homeRealmSignInEntryPoint"
+            else="viewBadRequest" />
+    </decision-state>
+    
+    <view-state id="showIDPList" view="idplist" model="trustedIDPSelection">
+        <var name="trustedIDPSelection"
+            class="org.apache.cxf.fediz.service.idp.model.TrustedIDPSelection" />
+        <binder>
+            <binding property="homeRealm" required="true" />
+        </binder>
+        <on-entry>
+            <set name="requestScope.idPConfig" value="flowScope.idpConfig" />
+        </on-entry>
+        <transition on="submit" to="checkIsThisIDP" bind="true"
+            validate="true">
+            <set name="flowScope.home_realm" value="trustedIDPSelection.homeRealm" />
+            <evaluate
+                expression="homeRealmReminder.addCookie(flowRequestContext, flowScope.home_realm)" />
+        </transition>
+        <transition on="cancel" to="checkDefaultToThisIDP"
+            bind="false" validate="false" />
+    </view-state>
+    
+    <!-- Home Realm is known then we can store it in cookie -->
+    <decision-state id="checkIsThisIDP">
+        <if test="flowScope.idpConfig.realm.equals(flowScope.home_realm)"
+            then="homeRealmSignInEntryPoint" else="checkRemoteIdpToken" />
+    </decision-state>
+    
+    <!-- ===== Realm independent ===== -->
+    
+    <action-state id="validateReturnAddress">
+        <evaluate expression="commonsURLValidator.isValid(flowRequestContext, flowScope.return_address)
+                              and passiveRequestorValidator.isValid(flowRequestContext, flowScope.return_address, flowScope.realm)"/>
+        <transition on="yes" to="requestRpToken" />
+        <transition on="no" to="viewBadRequest" />
+    </action-state>
+    
+    <!-- ===== Home Realm != this realm ===== -->
+    
+    <decision-state id="checkRemoteIdpToken">
+        <if test="externalContext.sessionMap[flowScope.home_realm] != null"
+            then="checkRemoteIdpTokenExpiry" else="redirectToTrustedIDP" />
+    </decision-state>
+    
+    <action-state id="checkRemoteIdpTokenExpiry">
+        <evaluate
+            expression="idpTokenExpiredAction.isTokenExpired(flowScope.home_realm, flowRequestContext) or
+                        protocol.equals('wsfed') and wfreshParser.authenticationRequired(flowScope.wfresh, flowScope.home_realm, flowRequestContext)
+                        or protocol.equals('samlsso') and authnRequestParser.isForceAuthentication(flowRequestContext)" />
+        <transition on="yes" to="redirectToTrustedIDP" />
+        <transition on="no" to="validateReturnAddress" >
+            <set name="flowScope.idpToken" value="externalContext.sessionMap[flowScope.home_realm]" />
+        </transition>
+        <transition on-exception="java.lang.Throwable" to="viewBadRequest" />
+    </action-state>
+    
+    <!-- ===== Home Realm == this realm ===== -->
+    
+    <decision-state id="homeRealmSignInEntryPoint">
+        <on-entry>
+            <!-- Here, home realm is guaranteed to be THIS realm -->
+            <set name="flowScope.home_realm" value="flowScope.idpConfig.realm" />
+        </on-entry>
+            
+        <!-- check presence of cached IDP token for THIS realm -->
+        <if test="externalContext.sessionMap[flowScope.home_realm] == null"
+            then="cacheSecurityToken" else="checkLocalIdPTokenExpiry" />
+    </decision-state>
+
+    <action-state id="checkLocalIdPTokenExpiry">
+        <evaluate
+            expression="idpTokenExpiredAction.isTokenExpired(flowScope.home_realm, flowRequestContext) or
+                        protocol.equals('wsfed') and wfreshParser.authenticationRequired(flowScope.wfresh, flowScope.home_realm, flowRequestContext)
+                        or protocol.equals('samlsso') and authnRequestParser.isForceAuthentication(flowRequestContext)" />
+        <transition on="yes" to="redirectToLocalIDP" />
+        <transition on="no" to="validateReturnAddress">
+            <set name="flowScope.idpToken" value="externalContext.sessionMap[flowScope.home_realm]" />
+        </transition>
+        <transition on-exception="java.lang.Throwable" to="viewBadRequest" />
+    </action-state>
+
+    <end-state id="redirectToLocalIDP">
+        <on-entry>
+            <evaluate expression="logoutAction.submit(flowRequestContext)" />
+        </on-entry>
+        <output name="home_realm" value="flowScope.home_realm" />
+    </end-state>
+
+    <action-state id="cacheSecurityToken">
+        <secured attributes="IS_AUTHENTICATED_FULLY" />
+        <evaluate expression="cacheSecurityToken.submit(flowRequestContext)" />
+        <transition to="validateReturnAddress">
+            <set name="flowScope.idpToken" value="externalContext.sessionMap[flowScope.home_realm]" />
+        </transition>
+    </action-state>
+    
+    <!-- ============================================================================================================= -->
+
+    <!-- normal exit point -->
+    <end-state id="requestRpToken">
+        <output name="home_realm" value="flowScope.home_realm" />
+        <output name="idpToken" value="flowScope.idpToken" />
+    </end-state>
+
+    <!-- abnormal exit point -->
+    <end-state id="viewBadRequest" />
+    
+    <!-- redirects to requestor idp -->
+    <end-state id="redirectToTrustedIDP">
+        <on-entry>
+            <evaluate expression="signinParametersCacheAction.store(flowRequestContext, protocol)" />
+        </on-entry>
+        <output name="home_realm" value="flowScope.home_realm" />
+        <output name="trusted_idp_context" value="flowScope.trusted_idp_context" />
+    </end-state>
+
+</flow>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/flows/signin-response.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/flows/signin-response.xml b/services/idp-core/src/main/webapp/WEB-INF/flows/signin-response.xml
new file mode 100644
index 0000000..ebfbf1f
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/flows/signin-response.xml
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<!--
+Process a response from a trusted third party IdP. It starts by restoring the original request parameters for the current context. 
+It then converts the response from the third party IdP into a SecurityToken via the TrustedIdPProtocolAction. It then exits this 
+subflow to get a RP token from the STS.
+ -->
+<flow xmlns="http://www.springframework.org/schema/webflow"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/webflow
+        http://www.springframework.org/schema/webflow/spring-webflow-2.0.xsd">
+
+    <input name="idpConfig" />
+    <input name="request_context" />
+    <input name="wresult" />
+    <input name="RelayState" />
+    <input name="SAMLResponse" />
+    <input name="state" />
+    <input name="code" />
+    <input name="home_realm" />
+    <input name="protocol" />
+
+    <on-start>
+        <!-- restore the original request parameters for the current context -->
+        <evaluate expression="signinParametersCacheAction.restore(flowRequestContext, request_context, protocol)" />
+    </on-start>
+    
+    <!-- validate token issued by requestor IDP given its home realm -->
+    <action-state id="validateToken">
+        <evaluate expression="trustedIdpProtocolAction.mapSignInResponse(flowRequestContext, home_realm)"
+            result="flowScope.idpToken" result-type="org.apache.cxf.ws.security.tokenstore.SecurityToken" />
+        <transition to="checkCacheTrustedIdpToken" />
+        <transition
+            on-exception="org.apache.cxf.fediz.core.exception.ProcessingException" to="viewBadRequest" />
+        <transition
+            on-exception="javax.ws.rs.BadRequestException" to="viewBadRequest" />
+        <transition on-exception="java.lang.Throwable" to="scInternalServerError" />
+    </action-state>
+    
+    <action-state id="checkCacheTrustedIdpToken">
+        <evaluate expression="idpConfig.findTrustedIdp(flowScope.home_realm).cacheTokens" />
+        <transition on="yes" to="requestRpToken">
+            <set name="externalContext.sessionMap[flowScope.home_realm]"
+                    value="flowScope.idpToken" />
+        </transition>
+        <transition on="no" to="requestRpToken" />
+    </action-state>
+
+    <end-state id="requestRpToken">
+        <output name="home_realm" value="flowScope.home_realm" />
+        <output name="request_context" value="flowScope.request_context" />
+        <output name="return_address" value="flowScope.return_address" />
+        <output name="realm" value="flowScope.realm" />
+        <output name="idpToken" value="flowScope.idpToken" />
+        <output name="saml_authn_request" value="flowScope.saml_authn_request" />
+    </end-state>
+
+    <!-- abnormal exit point : Http 400 Bad Request -->
+    <end-state id="viewBadRequest">
+        <output name="saml_authn_request" value="flowScope.saml_authn_request" />
+        <output name="RelayState" value="flowScope.RelayState" />
+    </end-state>
+
+    <!-- abnormal exit point : Http 500 Internal Server Error -->
+    <end-state id="scInternalServerError" />
+    
+</flow>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/idp-config-realma.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/idp-config-realma.xml b/services/idp-core/src/main/webapp/WEB-INF/idp-config-realma.xml
new file mode 100644
index 0000000..8e66b57
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/idp-config-realma.xml
@@ -0,0 +1,158 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans profile="spring" xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:util="http://www.springframework.org/schema/util"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util-4.3.xsd
+        ">
+
+    <context:property-placeholder location="classpath:realm.properties" />
+
+    <bean id="config"
+        class="org.apache.cxf.fediz.service.idp.service.ConfigServiceSpring">
+        <property name="idpConfigs">
+            <util:list>
+                <ref bean="idp-realmA" />
+            </util:list>
+        </property>
+        <property name="serviceConfigs">
+            <util:list>
+                <ref bean="srv-fedizhelloworld" />
+            </util:list>
+        </property>
+    </bean>
+
+    <bean id="idp-realmA" class="org.apache.cxf.fediz.service.idp.model.IDPConfig">
+        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-A" />
+        <property name="uri" value="realma" />
+        <!--<property name="hrds" value="" /> --> <!-- TBD, not defined, provide list if enabled -->
+        <property name="provideIdpList" value="true" />
+        <property name="useCurrentIdp" value="true" />
+        <property name="certificate" value="stsKeystoreA.properties" />
+        <property name="certificatePassword" value="realma" />
+        <property name="stsUrl"
+            value="https://localhost:0/fediz-idp-sts/REALMA" />
+        <property name="idpUrl"
+            value="https://localhost:${realmA.port}/fediz-idp/federation" />
+        <property name="supportedProtocols">
+            <util:list>
+                <value>http://docs.oasis-open.org/wsfed/federation/200706
+                </value>
+                <value>http://docs.oasis-open.org/ws-sx/ws-trust/200512
+                </value>
+            </util:list>
+        </property>
+        <property name="services">
+            <util:map>
+                <entry key="urn:org:apache:cxf:fediz:fedizhelloworld"
+                    value-ref="srv-fedizhelloworld" />
+            </util:map>
+        </property>
+        <property name="authenticationURIs">
+            <util:map>
+                <entry key="default" value="federation/up" />
+                <entry key="http://docs.oasis-open.org/wsfed/authorization/200706/authntypes/SslAndKey" 
+                       value="federation/krb" />
+                <entry key="http://docs.oasis-open.org/wsfed/authorization/200706/authntypes/default"
+                       value="federation/up" />
+                <entry key="http://docs.oasis-open.org/wsfed/authorization/200706/authntypes/Ssl"
+                       value="federation/clientcert" />
+            </util:map>
+        </property>
+        <property name="trustedIdps">
+            <util:map>
+                <entry key="urn:org:apache:cxf:fediz:idp:realm-B"
+                    value-ref="trusted-idp-realmB" />
+            </util:map>
+        </property>
+        <property name="serviceDisplayName" value="REALM A" />
+        <property name="serviceDescription" value="IDP of Realm A" />
+        <property name="rpSingleSignOutConfirmation" value="true"/>
+        <property name="rpSingleSignOutCleanupConfirmation" value="false"/>
+    </bean>
+
+    <bean id="trusted-idp-realmB"
+        class="org.apache.cxf.fediz.service.idp.model.TrustedIDPConfig">
+        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-B" />
+        <property name="cacheTokens" value="true" />
+        <property name="url"
+            value="https://localhost:${realmB.port}/fediz-idp-remote/federation" />
+        <property name="certificate" value="realmb.cert" />
+        <property name="trustType" value="PEER_TRUST" />  <!-- Required for Fediz Core, Process SignInResponse -->
+        <property name="protocol"
+            value="http://docs.oasis-open.org/wsfed/federation/200706" />
+        <property name="federationType" value="FEDERATE_IDENTITY" /> <!-- Required for STS Relationship -->
+        <property name="name" value="REALM B" />
+        <property name="description" value="IDP of Realm B" />
+        <!-- todo true / false prop for propagate sign-out of other realms !?-->
+    </bean>
+
+    <bean id="srv-fedizhelloworld" class="org.apache.cxf.fediz.service.idp.model.ServiceConfig">
+        <property name="realm"
+            value="urn:org:apache:cxf:fediz:fedizhelloworld" />
+        <property name="protocol"
+            value="http://docs.oasis-open.org/wsfed/federation/200706" />
+        <property name="serviceDisplayName" value="Fedizhelloworld" />
+        <property name="serviceDescription"
+            value="Web Application to illustrate WS-Federation" />
+        <property name="role" value="ApplicationServiceType" />
+        <property name="tokenType"
+            value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
+        <property name="lifeTime" value="3600" />
+        <!-- <property name="encryptionCertificate" value="" /> -->
+        <property name="requestedClaims">
+            <util:list>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" />
+                    <property name="optional" value="false" />
+                </bean>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" />
+                    <property name="optional" value="false" />
+                </bean>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" />
+                    <property name="optional" value="false" />
+                </bean>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role" />
+                    <property name="optional" value="true" />
+                </bean>
+            </util:list>
+        </property>
+    </bean>
+
+</beans>
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/idp-config-realmb.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/idp-config-realmb.xml b/services/idp-core/src/main/webapp/WEB-INF/idp-config-realmb.xml
new file mode 100644
index 0000000..9494587
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/idp-config-realmb.xml
@@ -0,0 +1,133 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans profile="spring" xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:util="http://www.springframework.org/schema/util"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd
+        http://www.springframework.org/schema/util
+        http://www.springframework.org/schema/util/spring-util-4.3.xsd">
+
+    <context:property-placeholder location="classpath:realm.properties" />
+
+    <bean id="config"
+        class="org.apache.cxf.fediz.service.idp.service.ConfigServiceSpring">
+        <property name="idpConfigs">
+            <util:list>
+                <ref bean="idp-realmB" />
+            </util:list>
+        </property>
+        <property name="serviceConfigs">
+            <util:list>
+                <ref bean="idp-realmA" />
+            </util:list>
+        </property>
+    </bean>
+
+    <bean id="idp-realmB" class="org.apache.cxf.fediz.service.idp.model.IDPConfig">
+        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-B" />
+        <property name="uri" value="realmb" />
+        <!--<property name="hrds" value="" /> --> <!-- TBD, not defined, provide list if enabled -->
+        <property name="provideIdpList" value="false" />
+        <property name="useCurrentIdp" value="true" />
+        <property name="certificate" value="stsKeystoreB.properties" />
+        <property name="certificatePassword" value="realmb" />
+        <property name="stsUrl"
+            value="https://localhost:0/fediz-idp-sts/REALMB" />
+        <property name="idpUrl"
+            value="https://localhost:${realmB.port}/fediz-idp-remote/federation" />
+        <property name="supportedProtocols">
+            <util:list>
+                <value>http://docs.oasis-open.org/wsfed/federation/200706
+                </value>
+                <value>http://docs.oasis-open.org/ws-sx/ws-trust/200512
+                </value>
+            </util:list>
+        </property>
+        <property name="services">
+            <util:map>
+                <entry key="urn:org:apache:cxf:fediz:idp:realm-A"
+                    value-ref="idp-realmA" />
+            </util:map>
+        </property>
+        <property name="authenticationURIs">
+            <util:map>
+                <entry key="default" value="federation/up" />
+                <entry key="http://docs.oasis-open.org/wsfed/authorization/200706/authntypes/SslAndKey" 
+                       value="federation/krb" />
+                <entry key="http://docs.oasis-open.org/wsfed/authorization/200706/authntypes/default"
+                       value="federation/up" />
+                <entry key="http://docs.oasis-open.org/wsfed/authorization/200706/authntypes/Ssl"
+                       value="federation/clientcert" />
+            </util:map>
+        </property>
+        <property name="serviceDisplayName" value="REALM B" />
+        <property name="serviceDescription" value="IDP of Realm B" />
+        <property name="rpSingleSignOutConfirmation" value="true"/>
+        <property name="rpSingleSignOutCleanupConfirmation" value="false"/>
+    </bean>
+
+    <bean id="idp-realmA" class="org.apache.cxf.fediz.service.idp.model.ServiceConfig">
+        <property name="realm" value="urn:org:apache:cxf:fediz:idp:realm-A" />
+        <property name="protocol"
+            value="http://docs.oasis-open.org/wsfed/federation/200706" />
+        <property name="serviceDisplayName" value="Resource IDP Realm A" />
+        <property name="serviceDescription" value="Resource IDP Realm A" />
+        <property name="role" value="SecurityTokenServiceType" />
+        <property name="tokenType"
+            value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
+        <property name="lifeTime" value="3600" />
+        <!-- <property name="encryptionCertificate" value="" /> -->
+        <property name="requestedClaims">
+            <util:list>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" />
+                    <property name="optional" value="false" />
+                </bean>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" />
+                    <property name="optional" value="false" />
+                </bean>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" />
+                    <property name="optional" value="false" />
+                </bean>
+                <bean
+                    class="org.apache.cxf.fediz.service.idp.model.RequestClaim">
+                    <property name="claimType"
+                        value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role" />
+                    <property name="optional" value="false" />
+                </bean>
+            </util:list>
+        </property>
+    </bean>
+
+</beans>
+

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/idp-servlet.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/idp-servlet.xml b/services/idp-core/src/main/webapp/WEB-INF/idp-servlet.xml
new file mode 100644
index 0000000..e7c24ee
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/idp-servlet.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xsi:schemaLocation="http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd">
+
+    <import resource="config/idp-core-servlet.xml" />
+
+    <!-- Define some mutable properties for the IdP -->
+    <context:property-placeholder location="classpath:realm.properties" />
+
+    <bean id="stsClientForRpAction" class="org.apache.cxf.fediz.service.idp.beans.STSClientAction">
+        <property name="wsdlLocation" value="https://localhost:0/fediz-idp-sts/${realm.STS_URI}/STSServiceTransport?wsdl" />
+        <property name="wsdlEndpoint" value="Transport_Port" />
+        <property name="tokenType" value="http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0" />
+    </bean>
+
+</beans>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/security-config.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/security-config.xml b/services/idp-core/src/main/webapp/WEB-INF/security-config.xml
new file mode 100644
index 0000000..e51f906
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/security-config.xml
@@ -0,0 +1,76 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements. See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership. The ASF licenses this file
+  to you 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.
+-->
+<beans xmlns="http://www.springframework.org/schema/beans"
+    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xmlns:security="http://www.springframework.org/schema/security"
+    xmlns:context="http://www.springframework.org/schema/context"
+    xsi:schemaLocation="
+        http://www.springframework.org/schema/beans
+        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
+        http://www.springframework.org/schema/context
+        http://www.springframework.org/schema/context/spring-context-4.3.xsd
+        http://www.springframework.org/schema/security
+        http://www.springframework.org/schema/security/spring-security-3.2.xsd
+        ">
+
+    <context:property-placeholder location="classpath:realm.properties" />
+
+    <import resource="config/security-krb-config.xml" />
+    <import resource="config/security-clientcert-config.xml" />
+    <import resource="config/security-up-config.xml" />
+    <import resource="config/security-rs-config.xml" />
+    
+    <!-- DISABLE in production as it might log confidential information about the user -->
+    <!-- <security:debug /> -->
+
+    <!-- Configure Spring Security -->
+    
+    <!-- If enabled, you can't access the Service layer within the Spring Webflow -->
+    <!-- The user has no role during the login phase of WS-Federation -->
+    <security:global-method-security pre-post-annotations="enabled" />
+
+    <!-- Redirects to a dedicated http config -->
+    <bean id="fedizEntryPoint" class="org.apache.cxf.fediz.service.idp.FedizEntryPoint">
+        <property name="realm" value="${realm-uri}" />
+        <property name="configService" ref="config" />
+    </bean>
+    
+    <!-- Main entry point for WS-Federation -->
+    <security:http pattern="/federation" use-expressions="true" entry-point-ref="fedizEntryPoint">
+        <security:custom-filter after="CHANNEL_FILTER" ref="stsUPPortFilter" />
+        <security:custom-filter after="SERVLET_API_SUPPORT_FILTER" ref="entitlementsEnricher" />
+    </security:http>
+    
+    <!-- Main entry point for SAML SSO -->
+    <security:http pattern="/saml" use-expressions="true" entry-point-ref="fedizEntryPoint">
+        <security:custom-filter after="CHANNEL_FILTER" ref="stsUPPortFilter" />
+        <security:custom-filter after="SERVLET_API_SUPPORT_FILTER" ref="entitlementsEnricher" />
+    </security:http>
+    
+    <security:authentication-manager alias="authenticationManagers">
+        <security:authentication-provider ref="stsUPAuthProvider" />
+        <security:authentication-provider ref="stsKrbAuthProvider" />
+        <security:authentication-provider ref="stsClientCertAuthProvider" />
+    </security:authentication-manager>
+	
+    <bean id="entitlementsEnricher" 
+          class="org.apache.cxf.fediz.service.idp.service.security.GrantedAuthorityEntitlements" />
+	
+</beans>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/views/genericerror.jsp
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/views/genericerror.jsp b/services/idp-core/src/main/webapp/WEB-INF/views/genericerror.jsp
new file mode 100644
index 0000000..c31c77c
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/views/genericerror.jsp
@@ -0,0 +1,11 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+<head>
+<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
+<title>IDP generic error page</title>
+</head>
+<body>
+	<h1>Sorry, CXF Fediz IDP cannot satisfy your request.</h1>
+	<p>Reason : ${reason}</p>
+</body>
+</html>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/views/idplist.jsp
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/views/idplist.jsp b/services/idp-core/src/main/webapp/WEB-INF/views/idplist.jsp
new file mode 100644
index 0000000..0a9cdb1
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/views/idplist.jsp
@@ -0,0 +1,33 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<%@page import="java.util.List"%>
+<%@page import="org.apache.cxf.fediz.service.idp.domain.Idp"%>
+<%@page import="org.apache.cxf.fediz.service.idp.domain.TrustedIdp"%>
+<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
+<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
+<html>
+<head>
+<title>Trusted IDP List</title>
+</head>
+<body>
+	<h1>Trusted IDP List</h1>
+	<i>Where are you from? Please, select one Identity Provider in the list which is able to authenticate you. </i>
+	<form:form method="POST" id="idplist" name="idplist">
+		<br />
+        <% Idp idp = (Idp)request.getAttribute("idpConfig");
+        List<TrustedIdp> trustedIDPs = idp.getTrustedIdps(); %>
+      <select name="homeRealm">
+        <% if (idp.isUseCurrentIdp()) { %>
+        <option value="<%=idp.getRealm()%>" selected="selected" ><%=idp.getServiceDescription()%></option>
+        <% } 
+           for (TrustedIdp trustedIDP : trustedIDPs) { %>
+        <option value="<%=trustedIDP.getRealm()%>"><%=trustedIDP.getDescription()%></option>
+        <% } %>
+      </select>
+      <br />
+      <input type="hidden" id="execution" name="execution" value="${flowExecutionKey}"/>
+      <br />
+      <input type="submit" name="_eventId_submit" value="Select Home Realm" />
+      <input type="submit" name="_eventId_cancel" value="Cancel" />
+    </form:form>
+</body>
+</html>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/views/index.jsp
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/views/index.jsp b/services/idp-core/src/main/webapp/WEB-INF/views/index.jsp
new file mode 100644
index 0000000..1a1ef1d
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/views/index.jsp
@@ -0,0 +1,25 @@
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You 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.
+-->
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<HTML><HEAD><TITLE>WS Federation Tomcat Examples</TITLE>
+<META http-equiv=Content-Type content="text/html">
+</HEAD>
+<BODY>
+<P>
+<H3>Hello World</H3>
+<P></P>
+</BODY></HTML>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/views/samlsigninresponseform.jsp
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/views/samlsigninresponseform.jsp b/services/idp-core/src/main/webapp/WEB-INF/views/samlsigninresponseform.jsp
new file mode 100644
index 0000000..3e7dc36
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/views/samlsigninresponseform.jsp
@@ -0,0 +1,20 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
+<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
+
+<html>
+<head>
+<title>IDP SignIn Response Form</title>
+</head>
+<body>
+	<form:form method="POST" id="samlsigninresponseform" name="samlsigninresponseform" action="${samlAction}" htmlEscape="true">
+        <input type="hidden" name="SAMLResponse" value="${samlResponse}" /><br />
+        <input type="hidden" name="RelayState" value="${relayState}" /><br />
+  		<noscript>
+		<p>Script is disabled. Click Submit to continue.</p>
+		<input type="submit" name="_eventId_submit" value="Submit" /><br />
+ 		</noscript>
+	</form:form>
+ 	<script language="javascript">window.setTimeout('document.forms[0].submit()',0);</script>
+</body>
+</html>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/views/signinform.jsp
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/views/signinform.jsp b/services/idp-core/src/main/webapp/WEB-INF/views/signinform.jsp
new file mode 100644
index 0000000..bcd7916
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/views/signinform.jsp
@@ -0,0 +1,72 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
+<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
+<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
+<html>
+	<head>
+		<title>IDP SignIn Request Form</title>
+		<style type="text/css">
+			.error 			{
+								color: #a94442 !important;
+								background-color: #f2dede !important;
+								border-color: #ebccd1 !important;
+							}
+			.msg 			{
+								padding: 15px;
+								border: 1px solid transparent;
+								border-radius: 4px;
+								color: #31708f;
+								background-color: #d9edf7;
+								border-color: #bce8f1;
+								margin: auto;
+								text-align: center;
+								margin-top: 5px;
+								width: 60%;
+							}
+			h1				{
+								font-size: 24px;
+								margin-top: 25px;
+							}
+			body			{
+								font-family:arial;
+							}
+			label			{
+								width: 90px;
+								display: inline-block;
+							}
+			#login_form		{
+								width: 250px;
+							}
+			#submit_button	{
+								float: right;
+								margin: 5px 12px;
+							}
+		</style>
+	</head>
+	<body onload='document.signinform.username.focus();'>
+		<img src="<c:url value='/images/apache-logo.png' />" alt="Apache Logo" style="margin:5px auto">
+		
+		<c:if test="${param.error != null}">
+			<div class="msg error"><b>Login Failed</b><br />
+                Username and password do not match. Please try again.</div>
+		</c:if>
+		<c:if test="${param.out != null}">
+			<div class="msg info"><b>Logout successful</b></div>
+		</c:if>
+		
+		<h1>Fediz IDP Login</h1>
+		
+		<form:form method="POST" id="signinform" name="signinform" action="login.do" >
+			<div id="login_form">
+				<label for="username">UserId</label>
+				<input type="text" id="username" name="username" placeholder="username" />
+				<br />
+				<label for="password">Password</label>
+				<input type="password" id="password" name="password" placeholder="password" />
+				<br />
+				<!--input type="hidden" id="execution" name="execution" value="${flowExecutionKey}"/-->
+				<input type="submit" id="submit_button" name="authenticate" value="Authenticate" />
+			</div>
+		</form:form>
+	</body>
+</html>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/views/signinresponseform.jsp
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/views/signinresponseform.jsp b/services/idp-core/src/main/webapp/WEB-INF/views/signinresponseform.jsp
new file mode 100644
index 0000000..7a98789
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/views/signinresponseform.jsp
@@ -0,0 +1,25 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
+<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
+
+<html>
+<head>
+<title>IDP SignIn Response Form</title>
+</head>
+<body>
+	<form:form method="POST" id="signinresponseform" name="signinresponseform" action="${fedAction}" htmlEscape="true">
+        <input type="hidden" name="wa" value="wsignin1.0" /><br />
+        <input type="hidden" name="wresult" value="${fedWResult}" /><br />
+        <% String wctx = (String)request.getAttribute("fedWCtx");
+           if (wctx != null && !wctx.isEmpty()) { %>
+        	<input type="hidden" name="wctx" value="${fedWCtx}" /><br />
+	    <% } %>
+        <input type="hidden" name="wtrealm" value="${fedWTrealm}" /><br />
+  		<noscript>
+		<p>Script is disabled. Click Submit to continue.</p>
+		<input type="submit" name="_eventId_submit" value="Submit" /><br />
+ 		</noscript>
+	</form:form>
+ 	<script language="javascript">window.setTimeout('document.forms[0].submit()',0);</script>
+</body>
+</html>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/views/signoutconfirmationresponse.jsp
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/views/signoutconfirmationresponse.jsp b/services/idp-core/src/main/webapp/WEB-INF/views/signoutconfirmationresponse.jsp
new file mode 100644
index 0000000..3e7a547
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/views/signoutconfirmationresponse.jsp
@@ -0,0 +1,65 @@
+<%@ page import="java.util.Map" %>
+<%@ page import="org.apache.cxf.fediz.service.idp.beans.SigninParametersCacheAction" %>
+<%@ page import="org.apache.cxf.fediz.service.idp.domain.Application" %>
+<%@ page import="org.apache.cxf.fediz.core.FederationConstants" %>
+<%@ page import="java.util.List" %>
+<%@ page import="java.util.Iterator" %>
+<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
+<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+<head>
+<title>IDP SignOut Confirmation Response Page</title>
+</head>
+<body>
+    <%
+        @SuppressWarnings("unchecked")
+        Map<String, Application> rcm =
+        (Map<String, Application>) request.getSession().getAttribute(SigninParametersCacheAction.ACTIVE_APPLICATIONS);
+    	String wreply = (String) request.getAttribute("wreply");
+
+        if (rcm == null) {
+    %>
+	        <p>You have already logged out</p>
+    <%
+        } else {
+    %>
+	        <h1>Logout from the following Applications?</h1>
+			<div>	   
+    <%
+            Iterator<Map.Entry<String, Application>> iterator = rcm.entrySet().iterator();
+                
+            while (iterator.hasNext()) {
+                Application next = iterator.next().getValue();
+                if (next != null) {
+    %>
+                    <%= next.getServiceDisplayName() %>
+                    <br/>
+    <%
+                }
+            }
+        }
+        
+        if (rcm != null && !rcm.isEmpty()) {
+    %>
+	    	</div>
+	    	<br/>
+	    	<br/>
+	        <form:form method="POST" id="signoutconfirmationresponseform" name="signoutconfirmationresponseform">
+	            <input type="hidden" name="wa" value="wsignout1.0" />
+	            <input type="hidden" id="execution" name="execution" value="${flowExecutionKey}" />
+	            <input type="submit" name="_eventId_submit" value="Logout" />
+			    <%     
+			        if (wreply != null && !wreply.isEmpty()) {
+			    %>
+			    <input type="hidden" name="wreply" value="<%= wreply%>" />        
+	            <input type="submit" name="_eventId_cancel" value="Cancel" />
+	            <%     
+			        }
+			    %>
+	        </form:form>
+    <%     
+        }
+    %>
+</body>
+</html>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/views/signoutresponse.jsp
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/views/signoutresponse.jsp b/services/idp-core/src/main/webapp/WEB-INF/views/signoutresponse.jsp
new file mode 100644
index 0000000..429c026
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/views/signoutresponse.jsp
@@ -0,0 +1,56 @@
+<%@page import="org.opensaml.soap.wsfed.WSFedConstants"%>
+<%@ page import="java.util.Map" %>
+<%@ page import="org.apache.cxf.fediz.service.idp.beans.SigninParametersCacheAction" %>
+<%@ page import="org.apache.cxf.fediz.service.idp.domain.Application" %>
+<%@ page import="org.apache.cxf.fediz.core.FederationConstants" %>
+<%@ page import="java.util.List" %>
+<%@ page import="java.util.Iterator" %>
+<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
+<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html>
+<head>
+<title>IDP SignOut Response Page</title>
+</head>
+<body>
+    <%
+        @SuppressWarnings("unchecked")
+        Map<String, Application> apps =
+                (Map<String, Application>) request.getAttribute(SigninParametersCacheAction.ACTIVE_APPLICATIONS);
+    	String wreply = (String) request.getAttribute("wreply");
+
+        if (apps == null) {
+    %>
+	        <p>You have already logged out</p>
+    <%
+        } else {
+    %>
+            <h1>CXF Fediz IDP successful logout.</h1>
+        
+            <p>
+    <%
+            Iterator<Map.Entry<String, Application>> iterator = apps.entrySet().iterator();
+            
+            while (iterator.hasNext()) {
+                Application next = iterator.next().getValue();
+                if (next != null) {
+    %>
+                    <%= next.getServiceDisplayName() %> 
+                    <img src="<%=next.getPassiveRequestorEndpoint() + "?" + FederationConstants.PARAM_ACTION 
+                        + "=" + FederationConstants.ACTION_SIGNOUT_CLEANUP %>"/>
+                    <br/>
+    <%
+                }
+            }
+    %>
+	        </p>
+    <%
+        }
+        if (wreply != null && !wreply.isEmpty()) {
+    %>
+    <p><a href="<%= wreply%>">continue</a></p>
+    <%
+        }
+    %>
+</body>
+</html>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/WEB-INF/web.xml
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/WEB-INF/web.xml b/services/idp-core/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000..807fa23
--- /dev/null
+++ b/services/idp-core/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,131 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you 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.
+
+-->
+<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
+    version="3.0" metadata-complete="true">
+
+	<description>Fediz IDP</description>
+	<display-name>Fediz IDP</display-name>
+	
+	<session-config>
+	    <cookie-config>
+            <http-only>true</http-only>
+        </cookie-config>
+		<tracking-mode>COOKIE</tracking-mode>
+	</session-config>
+
+	<context-param>
+		<param-name>contextConfigLocation</param-name>
+		<param-value>/WEB-INF/applicationContext.xml</param-value>
+	</context-param>
+
+	<context-param>
+		<param-name>spring.profiles.active</param-name>
+		<param-value>jpa</param-value>
+	</context-param>
+
+	<filter>
+		<filter-name>encodingFilter</filter-name>
+		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
+		<init-param>
+			<param-name>encoding</param-name>
+			<param-value>UTF-8</param-value>
+		</init-param>
+		<init-param>
+			<param-name>forceEncoding</param-name>
+			<param-value>true</param-value>
+		</init-param>
+	</filter>
+	<filter-mapping>
+		<filter-name>encodingFilter</filter-name>
+		<url-pattern>/*</url-pattern>
+	</filter-mapping>
+
+	<filter>
+		<filter-name>springSecurityFilterChain</filter-name>
+		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
+	</filter>
+	<filter-mapping>
+		<filter-name>springSecurityFilterChain</filter-name>
+		<url-pattern>/*</url-pattern>
+	</filter-mapping>
+
+	<servlet>
+		<servlet-name>idp</servlet-name>
+		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
+		<init-param>
+			<param-name>publishContext</param-name>
+			<param-value>false</param-value>
+		</init-param>
+		<load-on-startup>1</load-on-startup>
+	</servlet>
+	<servlet-mapping>
+		<servlet-name>idp</servlet-name>
+		<url-pattern>/</url-pattern>
+		<url-pattern>/federation</url-pattern>
+		<url-pattern>/federation/up</url-pattern>
+		<url-pattern>/federation/krb</url-pattern>
+		<url-pattern>/federation/clientcert</url-pattern>
+		<url-pattern>/saml</url-pattern>
+		<url-pattern>/saml/up</url-pattern>
+		<url-pattern>/saml/krb</url-pattern>
+		<url-pattern>/saml/clientcert</url-pattern>
+	</servlet-mapping>
+
+	<servlet>
+		<servlet-name>metadata</servlet-name>
+		<servlet-class>org.apache.cxf.fediz.service.idp.MetadataServlet</servlet-class>
+		<init-param>
+			<param-name>realm</param-name>
+			<param-value>${realm-uri}</param-value>
+		</init-param>
+	</servlet>
+	<servlet-mapping>
+		<servlet-name>metadata</servlet-name>
+		<url-pattern>/FederationMetadata/2007-06/FederationMetadata.xml</url-pattern>
+		<url-pattern>/metadata/*</url-pattern>
+	</servlet-mapping>
+
+	<servlet>
+		<servlet-name>CXFServlet</servlet-name>
+		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
+		<load-on-startup>1</load-on-startup>
+	</servlet>
+	<servlet-mapping>
+		<servlet-name>CXFServlet</servlet-name>
+		<url-pattern>/services/*</url-pattern>
+	</servlet-mapping>
+
+	<listener>
+		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
+	</listener>
+
+	<!-- Uncomment this when using JNDI DataSource -->
+	<!-- The property jpa.platform must be updated in persistence.properties even you use JNDI Datasource -->
+	<!-- 
+    <resource-ref>
+        <res-ref-name>jdbc/fedizDataSource</res-ref-name>
+        <res-type>javax.sql.DataSource</res-type>
+        <res-auth>Container</res-auth>
+    </resource-ref>
+    -->
+
+</web-app>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/resources/images/apache-logo.png
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/resources/images/apache-logo.png b/services/idp-core/src/main/webapp/resources/images/apache-logo.png
new file mode 100644
index 0000000..39b040e
Binary files /dev/null and b/services/idp-core/src/main/webapp/resources/images/apache-logo.png differ

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/main/webapp/resources/swagger/index.html
----------------------------------------------------------------------
diff --git a/services/idp-core/src/main/webapp/resources/swagger/index.html b/services/idp-core/src/main/webapp/resources/swagger/index.html
new file mode 100644
index 0000000..223cf1e
--- /dev/null
+++ b/services/idp-core/src/main/webapp/resources/swagger/index.html
@@ -0,0 +1,156 @@
+<!DOCTYPE html>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements.  See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership.  The ASF licenses this file
+to you 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.
+-->
+<html>
+<head>
+  <meta charset="UTF-8">
+    <!-- <ApacheFediz -->
+    <!--<title>Swagger UI</title>-->
+    <title>Swagger UI - Apache Fediz ${project.version}</title>
+    <!-- </ApacheFediz -->
+  <link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32" />
+  <link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16" />
+  <link href='css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
+  <link href='css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
+  <link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
+  <link href='css/reset.css' media='print' rel='stylesheet' type='text/css'/>
+  <link href='css/print.css' media='print' rel='stylesheet' type='text/css'/>
+  <script src='lib/jquery-1.8.0.min.js' type='text/javascript'></script>
+  <script src='lib/jquery.slideto.min.js' type='text/javascript'></script>
+  <script src='lib/jquery.wiggle.min.js' type='text/javascript'></script>
+  <script src='lib/jquery.ba-bbq.min.js' type='text/javascript'></script>
+  <script src='lib/handlebars-2.0.0.js' type='text/javascript'></script>
+  <script src='lib/underscore-min.js' type='text/javascript'></script>
+  <script src='lib/backbone-min.js' type='text/javascript'></script>
+  <script src='swagger-ui.js' type='text/javascript'></script>
+  <script src='lib/highlight.7.3.pack.js' type='text/javascript'></script>
+  <script src='lib/jsoneditor.min.js' type='text/javascript'></script>
+  <script src='lib/marked.js' type='text/javascript'></script>
+  <script src='lib/swagger-oauth.js' type='text/javascript'></script>
+
+  <!-- Some basic translations -->
+  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
+  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
+  <!-- <script src='lang/en.js' type='text/javascript'></script> -->
+
+  <script type="text/javascript">
+    $(function () {
+        // <ApacheFediz>
+        /*var url = window.location.search.match(/url=([^&]+)/);
+      if (url && url.length > 1) {
+        url = decodeURIComponent(url[1]);
+      } else {
+        url = "http://petstore.swagger.io/v2/swagger.json";
+         }*/
+        var url = window.location.href.substring(0, window.location.href.lastIndexOf('/')) + "/../services/rs/swagger.json";
+        // </ApacheFediz>
+      // Pre load translate...
+      if(window.SwaggerTranslator) {
+        window.SwaggerTranslator.translate();
+      }
+      window.swaggerUi = new SwaggerUi({
+        url: url,
+        dom_id: "swagger-ui-container",
+        supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'patch'],
+        onComplete: function(swaggerApi, swaggerUi){
+          if(typeof initOAuth == "function") {
+            initOAuth({
+              clientId: "your-client-id",
+              clientSecret: "your-client-secret-if-required",
+              realm: "your-realms",
+              appName: "your-app-name", 
+              scopeSeparator: ",",
+              additionalQueryStringParams: {}
+            });
+          }
+          if(window.SwaggerTranslator) {
+            window.SwaggerTranslator.translate();
+          }
+          $('pre code').each(function(i, e) {
+            hljs.highlightBlock(e)
+          });
+          addApiKeyAuthorization();
+        },
+        onFailure: function(data) {
+          log("Unable to Load SwaggerUI");
+        },
+        docExpansion: "none",
+        jsonEditor: false,
+        apisSorter: "alpha",
+        defaultModelRendering: 'schema',
+        showRequestHeaders: false
+      });
+        function addApiKeyAuthorization() {
+          // <ApacheFediz>
+          /*var key = encodeURIComponent($('#input_apiKey')[0].value);
+           if (key && key.trim() != "") {
+            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization("api_key", key, "query");
+            window.swaggerUi.api.clientAuthorizations.add("api_key", apiKeyAuth);
+            log("added key " + key);
+           }*/
+          var username = $('#input_username').val().trim();
+          var password = $('#input_password').val().trim();
+          if (username !== "" && password !== "") {
+            window.swaggerUi.api.clientAuthorizations.add(
+                    "basicAuth", new SwaggerClient.PasswordAuthorization(username, password));
+        }
+          // </ApacheFediz>
+      }
+        // <ApacheFediz>
+        //$('#input_apiKey').change(addApiKeyAuthorization);
+        $("#input_username").blur(function () {
+          addApiKeyAuthorization();
+        });
+        $("#input_password").blur(function () {
+          addApiKeyAuthorization();
+        });
+        // </ApacheFediz>
+      // if you have an apiKey you would like to pre-populate on the page for demonstration purposes...
+      /*
+        var apiKey = "myApiKeyXXXX123456789";
+        $('#input_apiKey').val(apiKey);
+      */
+      window.swaggerUi.load();
+      function log() {
+        if ('console' in window) {
+          console.log.apply(console, arguments);
+        }
+      }
+  });
+  </script>
+</head>
+
+<body class="swagger-section">
+<div id='header'>
+  <div class="swagger-ui-wrap">
+    <a id="logo" href="http://swagger.io">swagger</a>
+    <form id='api_selector'>
+       <!-- <ApacheFediz -->
+      <!--<div class='input'><input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl" type="text"/></div>-->
+      <!--<div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>-->
+      <!--<div class='input'><a id="explore" href="#" data-sw-translate>Explore</a></div>-->
+          <div class='input'><input placeholder="username" id="input_username" name="username" type="text"/></div>
+          <div class='input'><input placeholder="password" id="input_password" name="password" type="password"/></div>
+          <!-- </ApacheFediz -->
+    </form>
+  </div>
+</div>
+
+<div id="message-bar" class="swagger-ui-wrap" data-sw-translate>&nbsp;</div>
+<div id="swagger-ui-container" class="swagger-ui-wrap"></div>
+</body>
+</html>
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPATest.java b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPATest.java
new file mode 100644
index 0000000..4a2970c
--- /dev/null
+++ b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ApplicationDAOJPATest.java
@@ -0,0 +1,348 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.net.URI;
+import java.util.Arrays;
+import java.util.List;
+
+
+import org.apache.cxf.fediz.service.idp.domain.Application;
+import org.apache.cxf.fediz.service.idp.domain.RequestClaim;
+import org.apache.cxf.fediz.service.idp.service.ApplicationDAO;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.EmptyResultDataAccessException;
+import org.springframework.orm.jpa.JpaObjectRetrievalFailureException;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.util.Assert;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = { "classpath:testContext.xml" })
+public class ApplicationDAOJPATest {
+
+    @Autowired
+    private ApplicationDAO applicationDAO;
+    
+    
+    @BeforeClass
+    public static void init() {
+        System.setProperty("spring.profiles.active", "jpa");
+    }
+    
+    
+    @Test
+    public void testReadAllApplications() {
+        List<Application> applications = applicationDAO.getApplications(0, 999, null);
+        // Application could have been removed, Order not given as per JUnit design
+        Assert.isTrue(1 < applications.size(), "Size doesn't match [" + applications.size() + "]");
+    }
+    
+    
+    @Test
+    public void testReadExistingApplicationEmbeddedAll() {
+        Application application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld",
+                                                                Arrays.asList("all"));
+        
+        Assert.isTrue(application.getLifeTime() == 3600,
+                      "LifeTime doesn't match");
+        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(application.getProtocol()),
+                      "Protocol doesn't match");
+        Assert.isTrue("urn:org:apache:cxf:fediz:fedizhelloworld".equals(application.getRealm()),
+                      "Realm doesn't match");
+        Assert.isTrue("ApplicationServiceType".equals(application.getRole()),
+                      "Role doesn't match");
+        Assert.isTrue("Web Application to illustrate WS-Federation".equals(application.getServiceDescription()),
+                      "ServiceDescription doesn't match");
+        Assert.isTrue("Fedizhelloworld".equals(application.getServiceDisplayName()),
+                      "ServiceDisplayName doesn't match");
+        Assert.isTrue("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
+                      .equals(application.getTokenType()),
+                      "TokenType doesn't match");
+        Assert.isTrue(4 == application.getRequestedClaims().size(),
+                      "Number of claims doesn't match [" + application.getRequestedClaims().size() + "]");
+    }
+    
+    @Test
+    public void testReadExistingApplicationEmbeddedClaims() {
+        Application application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld",
+                                                                Arrays.asList("claims"));
+        
+        Assert.isTrue(4 == application.getRequestedClaims().size(),
+                      "Number of claims doesn't match");
+    }
+    
+    @Test
+    public void testReadExistingApplicationEmbeddedNull() {
+        Application application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld",
+                                                                null);
+        
+        Assert.isTrue(0 == application.getRequestedClaims().size(),
+                      "Number of claims doesn't match");
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryReadNonexistingApplication() {
+        applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld:NOTEXIST", null);
+    }
+    
+    
+    @Test
+    public void testAddNewApplication() {
+        
+        String realm = "urn:org:apache:cxf:fediz:application:testaddnew";
+        Application application = createApplication(realm);
+        applicationDAO.addApplication(application);
+        
+        application = applicationDAO.getApplication(realm, null);
+        
+        Assert.isTrue("".equals(application.getEncryptionCertificate()),
+                      "EncryptionCertificate doesn't match");
+        Assert.isTrue(application.getLifeTime() == 3600,
+                      "LifeTime doesn't match");
+        Assert.isTrue("http://docs.oasis-open.org/wsfed/federation/200706".equals(application.getProtocol()),
+                      "Protocol doesn't match");
+        Assert.isTrue(realm.equals(application.getRealm()),
+                      "Realm doesn't match");
+        Assert.isTrue("ApplicationServiceType".equals(application.getRole()),
+                      "Role doesn't match");
+        Assert.isTrue("Fedizhelloworld2 description".equals(application.getServiceDescription()),
+                      "ServiceDescription doesn't match");
+        Assert.isTrue("Fedizhelloworld2".equals(application.getServiceDisplayName()),
+                      "ServiceDisplayName doesn't match");
+        Assert.isTrue("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"
+                      .equals(application.getTokenType()),
+                      "TokenType doesn't match");
+        Assert.isTrue("http://www.w3.org/ns/ws-policy"
+                      .equals(application.getPolicyNamespace()),
+                      "Policy Namespace doesn't match");
+        Assert.isTrue(0 == application.getRequestedClaims().size(),
+                      "Number of claims doesn't match");
+    }
+    
+    @Test
+    public void testUpdateApplication() {
+        String realm = "urn:org:apache:cxf:fediz:application:testupdate";
+        
+        //Prepare
+        Application application = createApplication(realm);
+        applicationDAO.addApplication(application);
+        
+        //Testcase
+        application = new Application();
+        application.setRealm(realm);
+        application.setEncryptionCertificate("U");
+        application.setLifeTime(1800);
+        application.setProtocol("Uhttp://docs.oasis-open.org/wsfed/federation/200706");
+        application.setRole("UApplicationServiceType");
+        application.setServiceDescription("UFedizhelloworld2 description");
+        application.setServiceDisplayName("UFedizhelloworld2");
+        application.setTokenType("Uhttp://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1");
+        application.setPolicyNamespace("Uhttp://www.w3.org/ns/ws-policy");
+        
+        Assert.isTrue("U".equals(application.getEncryptionCertificate()),
+                      "EncryptionCertificate doesn't match");
+        Assert.isTrue(application.getLifeTime() == 1800,
+                      "LifeTime doesn't match");
+        Assert.isTrue("Uhttp://docs.oasis-open.org/wsfed/federation/200706".equals(application.getProtocol()),
+                      "Protocol doesn't match");
+        Assert.isTrue(realm.equals(application.getRealm()),
+                      "Realm doesn't match");
+        Assert.isTrue("UApplicationServiceType".equals(application.getRole()),
+                      "Role doesn't match");
+        Assert.isTrue("UFedizhelloworld2 description".equals(application.getServiceDescription()),
+                      "ServiceDescription doesn't match");
+        Assert.isTrue("UFedizhelloworld2".equals(application.getServiceDisplayName()),
+                      "ServiceDisplayName doesn't match");
+        Assert.isTrue("Uhttp://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"
+                      .equals(application.getTokenType()),
+                      "TokenType doesn't match");
+        Assert.isTrue("Uhttp://www.w3.org/ns/ws-policy"
+                      .equals(application.getPolicyNamespace()),
+                      "Policy Namespace doesn't match");
+        Assert.isTrue(0 == application.getRequestedClaims().size(),
+                      "Number of claims doesn't match");
+    }
+    
+    @Test(expected = DataIntegrityViolationException.class)
+    public void testTryAddExistingApplication() {
+        Application application = new Application();
+        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
+        application.setEncryptionCertificate("");
+        application.setLifeTime(3600);
+        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+        application.setRole("ApplicationServiceType");
+        application.setServiceDescription("Fedizhelloworld description");
+        application.setServiceDisplayName("Fedizhelloworld");
+        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
+        
+        applicationDAO.addApplication(application);
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryRemoveUnknownApplication() {
+        applicationDAO.deleteApplication("urn:org:apache:cxf:fediz:fedizhelloworld:NOTEXIST");
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testRemoveExistingApplication() {
+        String realm = "urn:org:apache:cxf:fediz:app:testdelete";
+        Application application = createApplication(realm);
+        
+        applicationDAO.addApplication(application);
+        
+        applicationDAO.deleteApplication(realm);
+        
+        applicationDAO.getApplication(realm, null);
+    }
+    
+    @Test
+    public void testAddClaimToApplication() {
+        //Prepare step
+        Application application = new Application();
+        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld:testaddclaim");
+        application.setEncryptionCertificate("");
+        application.setLifeTime(3600);
+        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+        application.setRole("ApplicationServiceType");
+        application.setServiceDescription("Fedizhelloworld description");
+        application.setServiceDisplayName("Fedizhelloworld");
+        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
+        
+        applicationDAO.addApplication(application);
+        
+        //Testcase
+        RequestClaim requestClaim = new RequestClaim();
+        requestClaim.setOptional(false);
+        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
+        
+        applicationDAO.addClaimToApplication(application, requestClaim);
+               
+        application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld:testaddclaim",
+                                                    Arrays.asList("all"));
+        
+        Assert.isTrue(1 == application.getRequestedClaims().size(), "requestedClaims size doesn't match");
+    }
+    
+    @Test(expected = DataIntegrityViolationException.class)
+    public void testTryAddExistingClaimToApplication() {
+        Application application = new Application();
+        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
+        
+        RequestClaim requestClaim = new RequestClaim();
+        requestClaim.setOptional(false);
+        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
+        
+        applicationDAO.addClaimToApplication(application, requestClaim);
+    }
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryAddUnknownClaimToApplication() {
+        Application application = new Application();
+        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
+        
+        RequestClaim requestClaim = new RequestClaim();
+        requestClaim.setOptional(false);
+        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/UNKOWN"));
+        
+        applicationDAO.addClaimToApplication(application, requestClaim);
+    }
+    
+    
+    @Test
+    public void testRemoveClaimFromApplication() {
+        //Prepare step
+        Application application = new Application();
+        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld:testremoveclaim");
+        application.setEncryptionCertificate("");
+        application.setLifeTime(3600);
+        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+        application.setRole("ApplicationServiceType");
+        application.setServiceDescription("Fedizhelloworld description");
+        application.setServiceDisplayName("Fedizhelloworld");
+        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0");
+        
+        applicationDAO.addApplication(application);
+        
+        RequestClaim requestClaim = new RequestClaim();
+        requestClaim.setOptional(false);
+        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
+        
+        applicationDAO.addClaimToApplication(application, requestClaim);
+               
+        application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld:testremoveclaim",
+                                                    Arrays.asList("all"));
+        Assert.isTrue(1 == application.getRequestedClaims().size(), "requestedClaims size doesn't match");
+        
+        //Testcase
+        applicationDAO.removeClaimFromApplication(application, requestClaim);
+        application = applicationDAO.getApplication("urn:org:apache:cxf:fediz:fedizhelloworld:testremoveclaim",
+                                                    Arrays.asList("all"));
+        Assert.isTrue(0 == application.getRequestedClaims().size(), "requestedClaims size doesn't match");
+    }
+    
+    @Test(expected = JpaObjectRetrievalFailureException.class)
+    public void testTryRemoveNotAssignedClaimFromApplication() {
+        Application application = new Application();
+        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
+                
+        RequestClaim requestClaim = new RequestClaim();
+        requestClaim.setOptional(false);
+        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/city"));
+        
+        applicationDAO.removeClaimFromApplication(application, requestClaim);
+    }
+    
+    @Test(expected = JpaObjectRetrievalFailureException.class)
+    public void testTryRemoveUnknownClaimFromApplication() {
+        Application application = new Application();
+        application.setRealm("urn:org:apache:cxf:fediz:fedizhelloworld");
+                
+        RequestClaim requestClaim = new RequestClaim();
+        requestClaim.setOptional(false);
+        requestClaim.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/UNKNOWN"));
+        
+        applicationDAO.removeClaimFromApplication(application, requestClaim);
+    }
+    
+    private static Application createApplication(String realm) {
+        Application application = new Application();
+        application.setRealm(realm);
+        application.setEncryptionCertificate("");
+        application.setLifeTime(3600);
+        application.setProtocol("http://docs.oasis-open.org/wsfed/federation/200706");
+        application.setRole("ApplicationServiceType");
+        application.setServiceDescription("Fedizhelloworld2 description");
+        application.setServiceDisplayName("Fedizhelloworld2");
+        application.setTokenType("http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1");
+        application.setPolicyNamespace("http://www.w3.org/ns/ws-policy");
+        return application;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/bf309400/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPATest.java
----------------------------------------------------------------------
diff --git a/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPATest.java b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPATest.java
new file mode 100644
index 0000000..767a989
--- /dev/null
+++ b/services/idp-core/src/test/java/org/apache/cxf/fediz/service/idp/service/jpa/ClaimDAOJPATest.java
@@ -0,0 +1,115 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cxf.fediz.service.idp.service.jpa;
+
+import java.net.URI;
+import java.util.List;
+
+import org.apache.cxf.fediz.service.idp.domain.Claim;
+import org.apache.cxf.fediz.service.idp.service.ClaimDAO;
+
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.dao.DataIntegrityViolationException;
+import org.springframework.dao.EmptyResultDataAccessException;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.util.Assert;
+
+
+@RunWith(SpringJUnit4ClassRunner.class)
+@ContextConfiguration(locations = { "classpath:testContext.xml" })
+public class ClaimDAOJPATest {
+
+    @Autowired
+    private ClaimDAO claimDAO;
+    
+    
+    @BeforeClass
+    public static void init() {
+        System.setProperty("spring.profiles.active", "jpa");
+    }
+    
+    
+    @Test
+    public void testReadAllClaims() {
+        List<Claim> claims = claimDAO.getClaims(0, 999);
+        Assert.isTrue(5 == claims.size(), "Size doesn't match");
+    }
+    
+    @Test
+    public void testReadExistingClaim() {
+        Claim claim = claimDAO.getClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname");
+        Assert.isTrue("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"
+                      .equals(claim.getClaimType().toString()),
+                      "ClaimType doesn't match");
+        Assert.isTrue("firstname".equals(claim.getDisplayName()),
+                      "Claim Display name doesn't match");
+        Assert.isTrue("Description for firstname".equals(claim.getDescription()),
+                      "Claim Description name doesn't match");
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryReadNonexistingClaim() {
+        claimDAO.getClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givennamenotexist");
+    }
+    
+    
+    @Test
+    public void testAddNewClaim() {
+        Claim claim5 = new Claim();
+        claim5.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/town"));
+        claim5.setDisplayName("Town");
+        claim5.setDescription("Town Description");
+        claimDAO.addClaim(claim5);
+        
+        List<Claim> claims = claimDAO.getClaims(0, 999);
+        Assert.isTrue(6 == claims.size(), "Size doesn't match. Claim not added");
+    }
+    
+    
+    @Test(expected = DataIntegrityViolationException.class)
+    public void testTryAddExistingClaim() {
+        Claim claim5 = new Claim();
+        claim5.setClaimType(URI.create("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname"));
+        claim5.setDisplayName("firstname");
+        claim5.setDescription("Description for firstname");
+        claimDAO.addClaim(claim5);
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testTryRemoveUnknownClaim() {
+        claimDAO.deleteClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/town/WRONG");
+    }
+    
+    
+    @Test(expected = EmptyResultDataAccessException.class)
+    public void testRemoveExistingClaim() {
+        claimDAO.deleteClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email");
+        
+        claimDAO.getClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email");
+    }
+    
+
+}